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
5d1195c92f937ccae40233a03fd941b3e0d71450
1,363
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'ua_parser/version' Gem::Specification.new do |spec| spec.name = "ua_parser" spec.version = UAParser::VERSION spec.authors = ["Jason Meller"] spec.email = ["[email protected]"] spec.summary = %q{Ruby bridge to JS UAParser library.} spec.description = %q{Ruby bridge to JS UAParser library.} spec.homepage = "https://github.com/kolide/ua-parser-ruby" spec.license = "MIT" # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host' # to allow pushing to a single host or delete this section to allow pushing to any host. if spec.respond_to?(:metadata) spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'" else raise "RubyGems 2.0 or newer is required to protect against " \ "public gem pushes." end spec.add_dependency 'execjs' spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.13" spec.add_development_dependency "rake", "~> 10.0" end
35.868421
96
0.661775
e91b259b8ffe7a81483cc110aa8585c687df1248
3,051
# frozen_string_literal: true require "bindata" require "webauthn/authenticator_data/attested_credential_data" require "webauthn/error" module WebAuthn class AuthenticatorDataFormatError < WebAuthn::Error; end class AuthenticatorData < BinData::Record RP_ID_HASH_LENGTH = 32 FLAGS_LENGTH = 1 SIGN_COUNT_LENGTH = 4 endian :big count_bytes_remaining :data_length string :rp_id_hash, length: RP_ID_HASH_LENGTH struct :flags do bit1 :extension_data_included bit1 :attested_credential_data_included bit1 :reserved_for_future_use_4 bit1 :reserved_for_future_use_3 bit1 :reserved_for_future_use_2 bit1 :user_verified bit1 :reserved_for_future_use_1 bit1 :user_present end bit32 :sign_count count_bytes_remaining :trailing_bytes_length string :trailing_bytes, length: :trailing_bytes_length def self.deserialize(data) read(data) rescue EOFError raise AuthenticatorDataFormatError end def data to_binary_s end def valid? (!attested_credential_data_included? || attested_credential_data.valid?) && (!extension_data_included? || extension_data) && valid_length? end def user_flagged? user_present? || user_verified? end def user_present? flags.user_present == 1 end def user_verified? flags.user_verified == 1 end def attested_credential_data_included? flags.attested_credential_data_included == 1 end def extension_data_included? flags.extension_data_included == 1 end def credential if attested_credential_data_included? attested_credential_data.credential end end def attested_credential_data @attested_credential_data ||= AttestedCredentialData.deserialize(trailing_bytes) rescue AttestedCredentialDataFormatError raise AuthenticatorDataFormatError end def extension_data @extension_data ||= CBOR.decode(raw_extension_data) end def aaguid raw_aaguid = attested_credential_data.raw_aaguid unless raw_aaguid == WebAuthn::AuthenticatorData::AttestedCredentialData::ZEROED_AAGUID attested_credential_data.aaguid end end private def valid_length? data_length == base_length + attested_credential_data_length + extension_data_length end def raw_extension_data if extension_data_included? if attested_credential_data_included? trailing_bytes[attested_credential_data.length..-1] else trailing_bytes.snapshot end end end def attested_credential_data_length if attested_credential_data_included? attested_credential_data.length else 0 end end def extension_data_length if extension_data_included? raw_extension_data.length else 0 end end def base_length RP_ID_HASH_LENGTH + FLAGS_LENGTH + SIGN_COUNT_LENGTH end end end
23.290076
93
0.709276
910e17e0613c7f658adb131241b8f72f28e0ec69
9,984
# # Filename:: alertmanager_spec.rb # Description:: Verifies alertmanager recipe(s). # # Author: Elijah Caine <[email protected]> # require 'spec_helper' # Caution: This is a carbon-copy of default_spec.rb with some variable replacements. describe 'prometheus::alertmanager' do let(:chef_run) do ChefSpec::SoloRunner.new( platform: 'ubuntu', version: '16.04', file_cache_path: '/tmp/chef/cache' ).converge(described_recipe) end before do stub_command('/usr/local/go/bin/go version | grep "go1.5 "').and_return(0) end it 'creates a user with correct attributes' do expect(chef_run).to create_user('prometheus').with( system: true, shell: '/bin/false', home: '/opt/prometheus' ) end it 'creates a directory at /opt/prometheus' do expect(chef_run).to create_directory('/opt/prometheus').with( owner: 'prometheus', group: 'prometheus', mode: '0755', recursive: true ) end it 'creates a directory at /var/log/prometheus' do expect(chef_run).to create_directory('/var/log/prometheus').with( owner: 'prometheus', group: 'prometheus', mode: '0755', recursive: true ) end it 'renders a prometheus job configuration file and notifies prometheus to restart' do resource = chef_run.template('/opt/prometheus/alertmanager.yml') expect(resource).to notify('service[alertmanager]').to(:restart) end # Test for source.rb context 'source' do let(:chef_run) do ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '16.04', file_cache_path: '/var/chef/cache') do |node| node.normal['prometheus']['alertmanager']['version'] = '0.14.0' node.normal['prometheus']['alertmanager']['install_method'] = 'source' end.converge(described_recipe) end it 'includes build-essential' do expect(chef_run).to build_essential 'install compilation tools' end %w(curl git-core mercurial gzip sed).each do |pkg| it "installs #{pkg}" do expect(chef_run).to install_package(pkg) end end it 'checks out alertmanager from github' do expect(chef_run).to checkout_git("#{Chef::Config[:file_cache_path]}/alertmanager-0.14.0").with( repository: 'https://github.com/prometheus/alertmanager.git', revision: 'v0.14.0' ) end it 'compiles alertmanager source' do expect(chef_run).to run_bash('compile_alertmanager_source') end it 'notifies alertmanager to restart' do resource = chef_run.bash('compile_alertmanager_source') expect(resource).to notify('service[alertmanager]').to(:restart) end context 'runit' do let(:chef_run) do ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '16.04', file_cache_path: '/var/chef/cache') do |node| node.normal['prometheus']['init_style'] = 'runit' end.converge(described_recipe) end it 'includes runit::default recipe' do expect(chef_run).to include_recipe('runit::default') end it 'enables runit_service' do expect(chef_run).to enable_runit_service('alertmanager') end end context 'init' do let(:chef_run) do ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '16.04', file_cache_path: '/var/chef/cache') do |node| node.normal['prometheus']['init_style'] = 'init' end.converge(described_recipe) end it 'renders an init.d configuration file' do expect(chef_run).to render_file('/etc/init.d/alertmanager') end end context 'systemd' do unit_file = '/etc/systemd/system/alertmanager.service' let(:chef_run) do ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '16.04', file_cache_path: '/var/chef/cache') do |node| node.normal['prometheus']['init_style'] = 'systemd' node.normal['prometheus']['user'] = 'prom_user' node.normal['prometheus']['group'] = 'prom_group' node.normal['prometheus']['alertmanager']['binary'] = '/tmp/alertmanager' node.normal['prometheus']['alertmanager']['storage.path'] = '/tmp/alertmanager_data' node.normal['prometheus']['alertmanager']['config.file'] = '/tmp/alertmanager.conf' node.normal['prometheus']['flags']['alertmanager.url'] = 'http://0.0.0.0:8080' end.converge(described_recipe) end it 'renders a systemd service file' do expect(chef_run).to render_file(unit_file) end it 'renders systemd unit with custom variables' do expect(chef_run).to render_file(unit_file).with_content { |content| expect(content).to include('ExecStart=/tmp/alertmanager') expect(content).to include('-storage.path=/tmp/alertmanager_data \\') expect(content).to include('-config.file=/tmp/alertmanager.conf \\') expect(content).to include('-web.external-url=http://0.0.0.0:8080') expect(content).to include('User=prom_user') expect(content).to include('Group=prom_group') } end end context 'upstart' do job_file = '/etc/init/alertmanager.conf' let(:chef_run) do ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '16.04', file_cache_path: '/var/chef/cache') do |node| node.normal['prometheus']['init_style'] = 'upstart' node.normal['prometheus']['user'] = 'prom_user' node.normal['prometheus']['group'] = 'prom_group' node.normal['prometheus']['alertmanager']['binary'] = '/tmp/alertmanager' node.normal['prometheus']['alertmanager']['storage.path'] = '/tmp/alertmanager_data' node.normal['prometheus']['alertmanager']['config.file'] = '/tmp/alertmanager.conf' node.normal['prometheus']['flags']['alertmanager.url'] = 'http://0.0.0.0:8080' node.normal['prometheus']['log_dir'] = '/tmp' end.converge(described_recipe) end it 'renders an upstart job configuration file' do expect(chef_run).to render_file(job_file) end it 'renders an upstart job configuration with custom variables' do expect(chef_run).to render_file(job_file).with_content { |content| expect(content).to include('setuid prom_user') expect(content).to include('setgid prom_group') expect(content).to include('exec >> "/tmp/alertmanager.log"') expect(content).to include('exec /tmp/alertmanager') expect(content).to include('-storage.path=/tmp/alertmanager_data') expect(content).to include('-config.file=/tmp/alertmanager.conf') expect(content).to include('-web.external-url=http://0.0.0.0:8080') } end end end # Test for binary.rb context 'binary' do let(:chef_run) do ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '16.04', file_cache_path: '/var/chef/cache') do |node| node.normal['prometheus']['alertmanager']['version'] = '0.14.0' node.normal['prometheus']['alertmanager']['install_method'] = 'binary' end.converge(described_recipe) end it 'runs ark with correct attributes' do expect(chef_run).to put_ark('prometheus').with( url: 'https://github.com/prometheus/alertmanager/releases/download/v0.14.0/alertmanager-0.14.0.linux-amd64.tar.gz', checksum: 'caddbbbe3ef8545c6cefb32f9a11207ae18dcc788e8d0fb19659d88c58d14b37', version: '0.14.0', prefix_root: Chef::Config['file_cache_path'], path: '/opt', owner: 'prometheus', group: 'prometheus' ) end it 'runs ark with given file_extension' do chef_run.node.default['prometheus']['alertmanager']['file_extension'] = 'tar.gz' chef_run.converge(described_recipe) expect(chef_run).to put_ark('prometheus').with( extension: 'tar.gz' ) end context 'runit' do let(:chef_run) do ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '16.04', file_cache_path: '/var/chef/cache') do |node| node.normal['prometheus']['init_style'] = 'runit' node.normal['prometheus']['alertmanager']['install_method'] = 'binary' end.converge(described_recipe) end it 'includes runit::default recipe' do expect(chef_run).to include_recipe('runit::default') end it 'enables runit_service' do expect(chef_run).to enable_runit_service('alertmanager') end end context 'init' do let(:chef_run) do ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '16.04', file_cache_path: '/var/chef/cache') do |node| node.normal['prometheus']['init_style'] = 'init' node.normal['prometheus']['alertmanager']['install_method'] = 'binary' end.converge(described_recipe) end it 'renders an init.d configuration file' do expect(chef_run).to render_file('/etc/init.d/alertmanager') end end context 'systemd' do let(:chef_run) do ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '16.04', file_cache_path: '/var/chef/cache') do |node| node.normal['prometheus']['init_style'] = 'systemd' node.normal['prometheus']['alertmanager']['install_method'] = 'binary' end.converge(described_recipe) end it 'renders a systemd service file' do expect(chef_run).to render_file('/etc/systemd/system/alertmanager.service') end end context 'upstart' do let(:chef_run) do ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '16.04', file_cache_path: '/var/chef/cache') do |node| node.normal['prometheus']['init_style'] = 'upstart' node.normal['prometheus']['alertmanager']['install_method'] = 'binary' end.converge(described_recipe) end it 'renders an upstart job configuration file' do expect(chef_run).to render_file('/etc/init/alertmanager.conf') end end end end
36.841328
123
0.646635
4aeda6e643a3b61937982e33ab0dfde710ed64eb
2,602
describe 'Updating System Level Groups', js: true do context 'when editing a system level group as an admin' do before :all do @group_name = random_group_name @group_description = random_group_description @group = create_group( name: @group_name, description: @group_description, provider_id: nil, # System Level groups do not have a provider_id admin: true, members: %w(rarxd5taqea qhw5mjoxgs2vjptmvzco q6ddmkhivmuhk) ) end after :all do # System level groups need to be cleaned up to avoid attempting to create # a group with the same name in another test (Random names don't seem to be reliable) delete_group(concept_id: @group['concept_id'], admin: true) end before do login_admin VCR.use_cassette('urs/multiple_users', record: :none) do visit edit_group_path(@group['concept_id']) end end it 'displays the page and populated fields on the form' do expect(page).to have_content("Edit #{@group_name}") # SYS badge expect(page).to have_content('SYS') expect(page).to have_css('span.eui-badge--sm') expect(page).to have_field('Name', with: @group_name) expect(page).to have_checked_field('System Level Group?') expect(page).to have_field('Description', with: @group_description) end it 'has the approprate fields disabled' do expect(page).to have_field('Name', readonly: true) expect(page).to have_checked_field('System Level Group?', readonly: true) end context 'when updating the system level group' do let(:new_group_description) { 'New system group description' } before do fill_in 'Description', with: new_group_description within '.group-form' do VCR.use_cassette('urs/multiple_users', record: :none) do click_on 'Submit' end end wait_for_cmr end it 'displays the original and new group information' do expect(page).to have_content('Group was successfully updated.') expect(page).to have_content(@group_name) expect(page).to have_content(new_group_description) # SYS badge expect(page).to have_content('SYS') expect(page).to have_css('span.eui-badge--sm') within '#group-members' do expect(page).to have_content('Execktamwrwcqs 02Wvhznnzjtrunff') expect(page).to have_content('06dutmtxyfxma Sppfwzsbwz') expect(page).to have_content('Rvrhzxhtra Vetxvbpmxf') end end end end end
32.525
91
0.659877
1ae45a41e2dbe924ff0c59dcf4e150a650476ae0
6,625
require_relative '../../test_helper' describe Spinach::Runner::FeatureRunner do let(:feature) { stub('feature', name: 'Feature', scenarios: [], background_steps: [] ) } subject{ Spinach::Runner::FeatureRunner.new(feature) } describe '#initialize' do it 'initializes the given filename' do subject.feature.must_equal feature end it 'initalizes the given scenario line' do @runner = Spinach::Runner::FeatureRunner.new(feature, '34') @runner.instance_variable_get(:@line).must_equal 34 end end describe '#scenarios' do it 'delegates to the feature' do subject.feature.stubs(scenarios: [1,2,3]) subject.scenarios.must_equal [1,2,3] end end describe '#run' do it 'runs the hooks in order' do hooks = sequence('hooks') Spinach.hooks.expects(:run_before_feature).with(feature).in_sequence(hooks) Spinach.expects(:find_step_definitions).returns(false).in_sequence(hooks) Spinach.hooks.expects(:run_after_feature).with(feature).in_sequence(hooks) subject.run end describe 'when the steps exist' do before do @feature = stub('feature', name: 'Feature') Spinach.stubs(:find_step_definitions).returns(true) @scenarios = [ scenario = stub(tags: []), another_scenario = stub(tags: []) ] @feature.stubs(:scenarios).returns @scenarios @runner = Spinach::Runner::FeatureRunner.new(@feature) end describe 'and the scenarios pass' do it 'runs the scenarios and returns true' do @scenarios.each do |scenario| runner = stub(run: true) Spinach::Runner::ScenarioRunner.expects(:new).with(scenario).returns runner end @runner.run.must_equal true end end describe 'and the scenarios fail' do it 'runs the scenarios and returns false' do @scenarios.each do |scenario| runner = stub(run: false) Spinach::Runner::ScenarioRunner.expects(:new).with(scenario).returns runner end @runner.run.must_equal false end describe "with config option fail_fast set" do let(:runners) { [ stub('runner1', run: false), stub('runner2') ] } before(:each) do Spinach.config.stubs(:fail_fast).returns(true) @scenarios.each_with_index do |scenario, i| Spinach::Runner::ScenarioRunner.stubs(:new).with(scenario).returns runners[i] end end it "breaks with fail_fast config option" do runners[1].expects(:run).never @runner.run.must_equal(false) end end end end describe "when the steps don't exist" do it 'runs the corresponding hooks and returns false' do Spinach.stubs(:find_step_definitions).returns(false) Spinach.hooks.expects(:run_on_undefined_feature).with(feature) subject.run.must_equal false end end describe "when a line is given" do before do @feature = stub('feature', name: 'Feature') Spinach.stubs(:find_step_definitions).returns(true) @scenarios = [ scenario = stub(line: 4, tags: []), another_scenario = stub(line: 12, tags: []) ] @feature.stubs(:scenarios).returns @scenarios end it "runs exactly matching scenario" do Spinach::Runner::ScenarioRunner.expects(:new).with(@scenarios[1]).returns stub(run: true) @runner = Spinach::Runner::FeatureRunner.new(@feature, "12") @runner.run end it "runs no scenario and returns false" do Spinach::Runner::ScenarioRunner.expects(:new).never @runner = Spinach::Runner::FeatureRunner.new(@feature, "3") @runner.run end it "runs matching scenario" do Spinach::Runner::ScenarioRunner.expects(:new).with(@scenarios[0]).returns stub(run: true) @runner = Spinach::Runner::FeatureRunner.new(@feature, "8") @runner.run end it "runs last scenario" do Spinach::Runner::ScenarioRunner.expects(:new).with(@scenarios[1]).returns stub(run: true) @runner = Spinach::Runner::FeatureRunner.new(@feature, "15") @runner.run end end describe "when running for specific tags configured" do describe "with feature" do before do @feature = stub('feature', name: 'Feature', tags: ["feature_tag"]) Spinach.stubs(:find_step_definitions).returns(true) @scenario = stub(line: 4, tags: []) @feature.stubs(:scenarios).returns [@scenario] end it "runs matching feature" do Spinach::TagsMatcher.expects(:match).with(["feature_tag"]).returns true Spinach::Runner::ScenarioRunner.expects(:new).with(@scenario).returns stub(run: true) @runner = Spinach::Runner::FeatureRunner.new(@feature) @runner.run end end describe "with scenario" do before do @feature = stub('feature', name: 'Feature', tags: ["feature_tag"]) Spinach.stubs(:find_step_definitions).returns(true) @scenario = stub(line: 4, tags: ["scenario_tag"]) @feature.stubs(:scenarios).returns [@scenario] end it "runs matching scenario" do Spinach::TagsMatcher.expects(:match).with(["feature_tag", "scenario_tag"]).returns true Spinach::Runner::ScenarioRunner.expects(:new).with(@scenario).returns stub(run: true) @runner = Spinach::Runner::FeatureRunner.new(@feature) @runner.run end it "skips scenarios that do not match" do Spinach::TagsMatcher.expects(:match).with(["feature_tag", "scenario_tag"]).returns false Spinach::Runner::ScenarioRunner.expects(:new).never @runner = Spinach::Runner::FeatureRunner.new(@feature) @runner.run end it "doesn't accumulate tags from one scenario to the next" do next_scenario = stub(line: 14, tags: []) @feature.stubs(:scenarios).returns [@scenario, next_scenario] Spinach::TagsMatcher.expects(:match).with(["feature_tag", "scenario_tag"]).returns true Spinach::TagsMatcher.expects(:match).with(["feature_tag"]).returns false Spinach::Runner::ScenarioRunner.expects(:new).with(@scenario).returns stub(run: true) @runner = Spinach::Runner::FeatureRunner.new(@feature) @runner.run end end end end end
34.149485
98
0.61917
4a010a5c30ddedb83647666cd9c9aeb02f233c45
132
FactoryBot.define do factory :work do title { ["Work"] } access_control skip_create override_new_record end end
14.666667
23
0.681818
110ea87c20364015309c04d1cb1d32ce5528e53c
3,714
class OpensshAT78 < Formula desc "OpenBSD freely-licensed SSH connectivity tools" homepage "https://www.openssh.com/" url "https://ftp.openbsd.org/pub/OpenBSD/OpenSSH/portable/openssh-7.8p1.tar.gz" mirror "https://mirror.vdms.io/pub/OpenBSD/OpenSSH/portable/openssh-7.8p1.tar.gz" version "7.8p1" revision 1 sha256 "1a484bb15152c183bb2514e112aa30dd34138c3cfb032eee5490a66c507144ca" keg_only :versioned_formula patch do url "https://raw.githubusercontent.com/z80oolong/openssh-debian-noroot-fix/master/openssh-7.8p1_1-fix.diff" sha256 "b336fd3bdf5400488860cab23e8a33932f66ecf58b7de04e5016fbe800884b9f" end # Please don't resubmit the keychain patch option. It will never be accepted. # https://github.com/Homebrew/homebrew-dupes/pull/482#issuecomment-118994372 depends_on "openssl" depends_on "ldns" => :optional depends_on "pkg-config" => :build if build.with? "ldns" depends_on "krb5" depends_on "libedit" depends_on "zlib" depends_on "lsof" => :test depends_on "daemonize" => :recommended resource "com.openssh.sshd.sb" do url "https://opensource.apple.com/source/OpenSSH/OpenSSH-209.50.1/com.openssh.sshd.sb" sha256 "a273f86360ea5da3910cfa4c118be931d10904267605cdd4b2055ced3a829774" end def install ENV.append "CFLAGS", "-DDEBIAN_NOROOT" ENV.append "CPPFLAGS", "-DDEBIAN_NOROOT" system "autoreconf" if build.head? args = %W[ --with-libedit --with-kerberos5 --prefix=#{prefix} --sysconfdir=#{etc}/ssh@#{version} --with-ssl-dir=#{Formula["openssl"].opt_prefix} ] args << "--with-privsep-path=#{var}/lib/sshd" args << "--with-ldns" if build.with? "ldns" system "./configure", *args system "make" ENV.deparallelize system "make", "install" # This was removed by upstream with very little announcement and has # potential to break scripts, so recreate it for now. # Debian have done the same thing. bin.install_symlink bin/"ssh" => "slogin" buildpath.install resource("com.openssh.sshd.sb") (etc/"ssh@#{version}").install "com.openssh.sshd.sb" => "org.openssh.sshd.sb" end def post_install unless (etc/"ssh@#{version}/openssh.d").exist? ohai "Create #{etc}/ssh@#{version}/openssh.d ..." (etc/"ssh@#{version}/openssh.d").atomic_write(<<~EOS) #!#{ENV['SHELL']} OPENSSH=#{opt_sbin}/sshd SERVER_OPTION="-f #{etc}/ssh@#{version}/sshd_config" PID_FILE=/var/run/openssh.pid LOG_FILE=/var/log/openssh.log LOCK_FILE=/var/run/openssh.lock start_daemon () { echo "Start OpenSSH Daemon..." export PATH=#{HOMEBREW_PREFIX}/sbin:#{HOMEBREW_PREFIX}/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin #{%x[which daemonize].chomp} -a -p $PID_FILE -l $LOCK_FILE -e $LOG_FILE -o $LOG_FILE -v $OPENSSH $SERVER_OPTION -E $LOG_FILE } stop_daemon () { if [ -e $LOCK_FILE ]; then echo "Stop OpenSSH Daemon..." kill -TERM `cat $PID_FILE`; rm -f $LOCK_FILE fi } if [ "x$1" = "xstop" ]; then stop_daemon exit 0 elif [ "x$1" = "xstart" ]; then stop_daemon start_daemon exit 0 else echo "Usage: $0 {start|stop}" exit 255 fi EOS (etc/"ssh@#{version}/openssh.d").chmod(0700) end end test do assert_match "OpenSSH_", shell_output("#{bin}/ssh -V 2>&1") begin pid = fork { exec sbin/"sshd", "-D", "-p", "8022" } sleep 2 assert_match "sshd", shell_output("lsof -i :8022") ensure Process.kill(9, pid) Process.wait(pid) end end end
30.95
133
0.640819
01152a55314484bd971b34b865c11e9f4161a9ad
1,089
# frozen_string_literal: true module Spandx module Ruby class Index include Enumerable attr_reader :directory, :name, :rubygems def initialize(directory:) @directory = directory @name = 'rubygems' @cache = ::Spandx::Core::Cache.new(@name, root: directory) @rubygems = ::Spandx::Ruby::Gateway.new end def update!(*) queue = Queue.new [fetch(queue), save(queue)].each(&:join) cache.rebuild_index end private attr_reader :cache def fetch(queue) Thread.new do rubygems.each do |item| queue.enq( item.merge( licenses: rubygems.licenses(item[:name], item[:version]) ) ) end queue.enq(:stop) end end def save(queue) Thread.new do loop do item = queue.deq break if item == :stop cache.insert(item[:name], item[:version], item[:licenses]) end end end end end end
20.54717
72
0.515152
089c7a9db9410875eec33e5afb2c1ef8fbad812f
508
eu_vat = Spree::Zone.find_or_create_by!(name: "EU_VAT", description: "Countries that make up the EU VAT zone.") north_america = Spree::Zone.find_or_create_by!(name: "North America", description: "USA + Canada") %w(PL FI PT RO DE FR SK HU SI IE AT ES IT BE SE LV BG GB LT CY LU MT DK NL EE). each do |symbol| eu_vat.zone_members.create!(zoneable: Spree::Country.find_by!(iso: symbol)) end %w(US CA).each do |symbol| north_america.zone_members.create!(zoneable: Spree::Country.find_by!(iso: symbol)) end
42.333333
111
0.732283
f7d1f93dffb6951ff90dd49eaaf12dfee77bf3dc
945
class Exploitdb < Formula desc "The official Exploit Database" homepage "https://www.exploit-db.com/" url "https://github.com/offensive-security/exploitdb.git", :tag => "2019-11-20", :revision => "72cddaee5157cd67d25653f16b34790b074cd680" version "2019-11-20" head "https://github.com/offensive-security/exploitdb.git" bottle :unneeded def install inreplace "searchsploit", "rc_file=\"\"", "rc_file=\"#{etc}/searchsploit_rc\"" optpath = opt_share/"exploitdb" inreplace ".searchsploit_rc" do |s| s.gsub! "\"/opt/exploitdb\"", optpath s.gsub! "\"/opt/exploitdb-papers\"", "#{optpath}-papers" end bin.install "searchsploit" etc.install ".searchsploit_rc" => "searchsploit_rc" pkgshare.install %w[.git exploits files_exploits.csv files_shellcodes.csv shellcodes] end test do system "#{bin}/searchsploit", "sendpage" end end
28.636364
77
0.65291
e9a87e7ac95c4485932a8a084552c540fc326051
982
require 'spec_helper' require 'autoscaler/heroku_scaler' describe Autoscaler::HerokuScaler, :online => true do let(:cut) {Autoscaler::HerokuScaler} let(:client) {cut.new} subject {client} its(:workers) {should == 0} describe 'scaled' do around do |example| client.workers = 1 example.yield client.workers = 0 end its(:workers) {should == 1} end describe 'exception handling', :focus => true do before do def client.client raise Excon::Errors::SocketError.new(Exception.new('oops')) end end describe "default handler" do it {expect{client.workers}.to_not raise_error} it {client.workers.should == 0} it {expect{client.workers = 1}.to_not raise_error} end describe "custom handler" do before do @caught = false client.exception_handler = lambda {|exception| @caught = true} end it {client.workers; @caught.should be_true} end end end
22.318182
70
0.641548
e9851eacdf61e6afead2bd3f449e8b46874161b0
6,402
require 'test_helper' class RemotePinTest < Test::Unit::TestCase def setup @gateway = PinGateway.new(fixtures(:pin)) @amount = 100 @credit_card = credit_card('5520000000000000', :year => Time.now.year + 2) @visa_credit_card = credit_card('4200000000000000', :year => Time.now.year + 3) @declined_card = credit_card('4100000000000001') @options = { :email => '[email protected]', :ip => '203.59.39.62', :order_id => '1', :billing_address => address, :description => "Store Purchase #{DateTime.now.to_i}" } end def test_successful_purchase response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert_equal true, response.params['response']['captured'] end def test_successful_purchase_with_metadata options_with_metadata = { metadata: { order_id: generate_unique_id, purchase_number: generate_unique_id } } response = @gateway.purchase(@amount, @credit_card, @options.merge(options_with_metadata)) assert_success response assert_equal true, response.params['response']['captured'] assert_equal options_with_metadata[:metadata][:order_id], response.params['response']['metadata']['order_id'] assert_equal options_with_metadata[:metadata][:purchase_number], response.params['response']['metadata']['purchase_number'] end def test_successful_purchase_with_reference response = @gateway.purchase(@amount, @credit_card, @options.merge(reference: 'statement descriptor')) assert_success response end def test_successful_authorize_and_capture authorization = @gateway.authorize(@amount, @credit_card, @options) assert_success authorization assert_equal false, authorization.params['response']['captured'] response = @gateway.capture(@amount, authorization.authorization, @options) assert_success response assert_equal true, response.params['response']['captured'] end def test_failed_authorize response = @gateway.authorize(@amount, @declined_card, @options) assert_failure response end def test_failed_capture_due_to_invalid_token response = @gateway.capture(@amount, 'bogus', @options) assert_failure response end def test_failed_capture_due_to_invalid_amount authorization = @gateway.authorize(@amount, @credit_card, @options) assert_success authorization assert_equal authorization.params['response']['captured'], false response = @gateway.capture(@amount - 1, authorization.authorization, @options) assert_failure response assert_equal 'invalid_capture_amount', response.params['error'] end def test_successful_purchase_without_description @options.delete(:description) response = @gateway.purchase(@amount, @credit_card, @options) assert_success response end def test_unsuccessful_purchase response = @gateway.purchase(@amount, @declined_card, @options) assert_failure response end # This is a bit manual as we have to create a working card token as # would be returned from Pin.js / the card tokens API which # falls outside of active merchant def test_store_and_charge_with_pinjs_card_token headers = { 'Content-Type' => 'application/json', 'Authorization' => "Basic #{Base64.strict_encode64(@gateway.options[:api_key] + ':').strip}" } # Get a token equivalent to what is returned by Pin.js card_attrs = { :number => @credit_card.number, :expiry_month => @credit_card.month, :expiry_year => @credit_card.year, :cvc => @credit_card.verification_value, :name => "#{@credit_card.first_name} #{@credit_card.last_name}", :address_line1 => '42 Sevenoaks St', :address_city => 'Lathlain', :address_postcode => '6454', :address_start => 'WA', :address_country => 'Australia' } url = @gateway.test_url + '/cards' body = JSON.parse(@gateway.ssl_post(url, card_attrs.to_json, headers)) card_token = body['response']['token'] store = @gateway.store(card_token, @options) assert_success store assert_not_nil store.authorization purchase = @gateway.purchase(@amount, card_token, @options) assert_success purchase assert_not_nil purchase.authorization end def test_store_and_customer_token_charge response = @gateway.store(@credit_card, @options) assert_success response assert_not_nil response.authorization token = response.authorization assert response1 = @gateway.purchase(@amount, token, @options) assert_success response1 assert response2 = @gateway.purchase(@amount, token, @options) assert_success response2 assert_not_equal response1.authorization, response2.authorization end def test_store_and_update response = @gateway.store(@credit_card, @options) assert_success response assert_not_nil response.authorization assert_equal @credit_card.year, response.params['response']['card']['expiry_year'] response = @gateway.update(response.authorization, @visa_credit_card, :address => address) assert_success response assert_not_nil response.authorization assert_equal @visa_credit_card.year, response.params['response']['card']['expiry_year'] end def test_refund response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert_not_nil response.authorization token = response.authorization response = @gateway.refund(@amount, token, @options) assert_success response assert_not_nil response.authorization end def test_failed_refund response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert_not_nil response.authorization token = response.authorization response = @gateway.refund(@amount, token.reverse, @options) assert_failure response end def test_invalid_login gateway = PinGateway.new(:api_key => '') response = gateway.purchase(@amount, @credit_card, @options) assert_failure response end def test_transcript_scrubbing transcript = capture_transcript(@gateway) do @gateway.purchase(@amount, @credit_card, @options) end clean_transcript = @gateway.scrub(transcript) assert_scrubbed(@credit_card.number, clean_transcript) assert_scrubbed(@credit_card.verification_value.to_s, clean_transcript) end end
33.873016
127
0.728054
e2c1c604d4ff6b496f3ba387b20052929a38d050
555
require 'travis/cli/setup' module Travis module CLI class Setup class CloudFiles < Service description "automatic pushing to Rackspace Cloud Files" def run deploy 'cloudfiles' do |config| config['username'] = ask("Rackspace Username: ").to_s config['api_key'] = ask("Rackspace Api Key: ") { |q| q.echo = "*" }.to_s config['region'] = ask("Cloud Files Region: ").to_s config['container'] = ask("Container: ").to_s end end end end end end
26.428571
84
0.567568
f77013251c54002523172c6b0b5f23927f1d97c9
9,745
=begin #Kleister OpenAPI #API definition for Kleister, manage mod packs for Minecraft The version of the OpenAPI document: 1.0.0-alpha1 Generated by: https://openapi-generator.tech OpenAPI Generator version: 5.1.0 =end require 'date' require 'time' module Kleister class Build attr_accessor :id attr_accessor :pack_id attr_accessor :minecraft_id attr_accessor :forge_id attr_accessor :slug attr_accessor :name attr_accessor :min_java attr_accessor :min_memory attr_accessor :published attr_accessor :hidden attr_accessor :private attr_accessor :public attr_accessor :created_at attr_accessor :updated_at # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'id' => :'id', :'pack_id' => :'pack_id', :'minecraft_id' => :'minecraft_id', :'forge_id' => :'forge_id', :'slug' => :'slug', :'name' => :'name', :'min_java' => :'min_java', :'min_memory' => :'min_memory', :'published' => :'published', :'hidden' => :'hidden', :'private' => :'private', :'public' => :'public', :'created_at' => :'created_at', :'updated_at' => :'updated_at' } 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 { :'id' => :'String', :'pack_id' => :'String', :'minecraft_id' => :'String', :'forge_id' => :'String', :'slug' => :'String', :'name' => :'String', :'min_java' => :'String', :'min_memory' => :'String', :'published' => :'Boolean', :'hidden' => :'Boolean', :'private' => :'Boolean', :'public' => :'Boolean', :'created_at' => :'Time', :'updated_at' => :'Time' } 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 `Kleister::Build` 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 `Kleister::Build`. 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?(:'id') self.id = attributes[:'id'] end if attributes.key?(:'pack_id') self.pack_id = attributes[:'pack_id'] end if attributes.key?(:'minecraft_id') self.minecraft_id = attributes[:'minecraft_id'] end if attributes.key?(:'forge_id') self.forge_id = attributes[:'forge_id'] end if attributes.key?(:'slug') self.slug = attributes[:'slug'] end if attributes.key?(:'name') self.name = attributes[:'name'] end if attributes.key?(:'min_java') self.min_java = attributes[:'min_java'] end if attributes.key?(:'min_memory') self.min_memory = attributes[:'min_memory'] end if attributes.key?(:'published') self.published = attributes[:'published'] end if attributes.key?(:'hidden') self.hidden = attributes[:'hidden'] end if attributes.key?(:'private') self.private = attributes[:'private'] end if attributes.key?(:'public') self.public = attributes[:'public'] end if attributes.key?(:'created_at') self.created_at = attributes[:'created_at'] end if attributes.key?(:'updated_at') self.updated_at = attributes[:'updated_at'] 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 @pack_id.nil? invalid_properties.push('invalid value for "pack_id", pack_id cannot be nil.') end if @name.nil? invalid_properties.push('invalid value for "name", name cannot be nil.') 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 @pack_id.nil? return false if @name.nil? 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 && id == o.id && pack_id == o.pack_id && minecraft_id == o.minecraft_id && forge_id == o.forge_id && slug == o.slug && name == o.name && min_java == o.min_java && min_memory == o.min_memory && published == o.published && hidden == o.hidden && private == o.private && public == o.public && created_at == o.created_at && updated_at == o.updated_at 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 [id, pack_id, minecraft_id, forge_id, slug, name, min_java, min_memory, published, hidden, private, public, created_at, updated_at].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 /\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 = Kleister.const_get(type) klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.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) 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
28.328488
193
0.594253
1a556c0346fd5a48b0e922798cc93d53e3378ca9
825
require_relative "../canvas_base_input_type" module LMSGraphQL module Types module Canvas class CanvasCreatedEventDatumInput < BaseInputObject description "Course Audit log. API Docs: https://canvas.instructure.com/doc/api/course_audit_log.html" argument :name, [String], "Example: , Course 1", required: false argument :start_at, [LMSGraphQL::Types::DateTimeType], "Example: , 2012-01-19T15:00:00-06:00", required: false argument :conclude_at, [LMSGraphQL::Types::DateTimeType], "Example: , 2012-01-19T15:00:00-08:00", required: false argument :is_public, [Boolean], "Example: , false", required: false argument :created_source, String, "The type of action that triggered the creation of the course..Example: manual|sis|api", required: false end end end end
45.833333
144
0.716364
878f8809a172369e3714de181ed335cc4ef27848
1,618
# frozen_string_literal: true require 'recursive-open-struct' require_relative '../concerns/currencyable' require_relative '../concerns/environmentable' require_relative '../concerns/humanizeable' require_relative '../concerns/terminalable' require_relative '../gemini_api/get' require_relative '../gemini_api/post' module GeminiTraderTerminal # Parent class for Gemini Trader terminal. Classes which inherit the parent class generally represent an isolated interactive pathway. class Base include Currencyable include Environmentable include Humanizeable include Terminalable def initialize(**attributes) populate_terminalable validate_and_assign_environment(attributes[:environment]) validate_and_assign_default_fiat_currency(attributes[:default_fiat_currency]) initialize_and_assign_api end private attr_accessor :api def validate_and_assign_environment(value) raise ArgumentError, "Environment must be one of the following: #{ENVIRONMENTS.join(', ')}" unless ENVIRONMENTS.include?(value) self.environment = value end def validate_and_assign_default_fiat_currency(value) raise ArgumentError, "Default fiat currency must be one of the following: #{DEFAULT_FIAT_CURRENCIES.join(', ')}" unless DEFAULT_FIAT_CURRENCIES.include?(value) self.default_fiat_currency = value end def initialize_and_assign_api self.api = RecursiveOpenStruct.new( get: GeminiApi::Get.new(environment: environment), post: GeminiApi::Post.new(environment: environment) ) end end end
31.72549
165
0.754635
1aa07fd07b693234d4c44ff2147ea18dd55531f9
3,543
# -*- encoding: utf-8 -*- # stub: sprockets 3.5.2 ruby lib Gem::Specification.new do |s| s.name = "sprockets" s.version = "3.5.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Sam Stephenson", "Joshua Peek"] s.date = "2015-12-08" s.description = "Sprockets is a Rack-based asset packaging system that concatenates and serves JavaScript, CoffeeScript, CSS, LESS, Sass, and SCSS." s.email = ["[email protected]", "[email protected]"] s.executables = ["sprockets"] s.files = ["bin/sprockets"] s.homepage = "https://github.com/rails/sprockets" s.licenses = ["MIT"] s.required_ruby_version = Gem::Requirement.new(">= 1.9.3") s.rubyforge_project = "sprockets" s.rubygems_version = "2.4.5.1" s.summary = "Rack-based asset packaging system" s.installed_by_version = "2.4.5.1" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rack>, ["< 3", "> 1"]) s.add_runtime_dependency(%q<concurrent-ruby>, ["~> 1.0"]) s.add_development_dependency(%q<closure-compiler>, ["~> 1.1"]) s.add_development_dependency(%q<coffee-script-source>, ["~> 1.6"]) s.add_development_dependency(%q<coffee-script>, ["~> 2.2"]) s.add_development_dependency(%q<eco>, ["~> 1.0"]) s.add_development_dependency(%q<ejs>, ["~> 1.0"]) s.add_development_dependency(%q<execjs>, ["~> 2.0"]) s.add_development_dependency(%q<minitest>, ["~> 5.0"]) s.add_development_dependency(%q<nokogiri>, ["~> 1.3"]) s.add_development_dependency(%q<rack-test>, ["~> 0.6"]) s.add_development_dependency(%q<rake>, ["~> 10.0"]) s.add_development_dependency(%q<sass>, ["~> 3.1"]) s.add_development_dependency(%q<uglifier>, ["~> 2.3"]) s.add_development_dependency(%q<yui-compressor>, ["~> 0.12"]) else s.add_dependency(%q<rack>, ["< 3", "> 1"]) s.add_dependency(%q<concurrent-ruby>, ["~> 1.0"]) s.add_dependency(%q<closure-compiler>, ["~> 1.1"]) s.add_dependency(%q<coffee-script-source>, ["~> 1.6"]) s.add_dependency(%q<coffee-script>, ["~> 2.2"]) s.add_dependency(%q<eco>, ["~> 1.0"]) s.add_dependency(%q<ejs>, ["~> 1.0"]) s.add_dependency(%q<execjs>, ["~> 2.0"]) s.add_dependency(%q<minitest>, ["~> 5.0"]) s.add_dependency(%q<nokogiri>, ["~> 1.3"]) s.add_dependency(%q<rack-test>, ["~> 0.6"]) s.add_dependency(%q<rake>, ["~> 10.0"]) s.add_dependency(%q<sass>, ["~> 3.1"]) s.add_dependency(%q<uglifier>, ["~> 2.3"]) s.add_dependency(%q<yui-compressor>, ["~> 0.12"]) end else s.add_dependency(%q<rack>, ["< 3", "> 1"]) s.add_dependency(%q<concurrent-ruby>, ["~> 1.0"]) s.add_dependency(%q<closure-compiler>, ["~> 1.1"]) s.add_dependency(%q<coffee-script-source>, ["~> 1.6"]) s.add_dependency(%q<coffee-script>, ["~> 2.2"]) s.add_dependency(%q<eco>, ["~> 1.0"]) s.add_dependency(%q<ejs>, ["~> 1.0"]) s.add_dependency(%q<execjs>, ["~> 2.0"]) s.add_dependency(%q<minitest>, ["~> 5.0"]) s.add_dependency(%q<nokogiri>, ["~> 1.3"]) s.add_dependency(%q<rack-test>, ["~> 0.6"]) s.add_dependency(%q<rake>, ["~> 10.0"]) s.add_dependency(%q<sass>, ["~> 3.1"]) s.add_dependency(%q<uglifier>, ["~> 2.3"]) s.add_dependency(%q<yui-compressor>, ["~> 0.12"]) end end
44.848101
150
0.607113
03c542d458e42223fbbe060add6bf7a80be56331
302
# frozen_string_literal: true module AcaEntities module Medicaid module Atp # entity for atp MedicaidMagiFormerFosterCareEligibilityBasis class MedicaidMagiFormerFosterCareEligibilityBasis < EligibilityBasis # Additional attributes, if necessary end end end end
21.571429
75
0.758278
f8d5d8a595b35e027df175c86bf6cf1ccd9e9ba2
896
require 'pry' tries = 3 random_number = rand(1..10) binding.pry puts "What is your name?" name = gets.strip puts "Hello" + " " + name + "!" puts "Want to play a game, " + name + "?" answer = gets.strip.downcase if answer == "yes" print 'Great!' loop do print "I'm thinking of a number..." print "Can you guess it? " guess = gets.to_i if tries == 1 puts "It was #{random_number}. You are out of tries. You lose, #{name}. :(" break end if guess < random_number tries -= 1 puts "My number's bigger than that. You have #{tries} left. Try again." elsif guess > random_number tries -= 1 puts "My number's smaller than that. You have #{tries} left. Try again." elsif guess == random_number puts "Wow! You got it, #{name}! :)" break end end end
22.4
83
0.554688
081e15f2fb28b76b3aa890c07c3b44a2f464f1f6
8,022
module Selenium module WebDriver module Support class Select # # @param [Element] element The select element to use # def initialize(element) tag_name = element.tag_name unless tag_name.downcase == "select" raise ArgumentError, "unexpected tag name #{tag_name.inspect}" end @element = element @multi = ![nil, "false"].include?(element.attribute(:multiple)) end # # Does this select element support selecting multiple options? # # @return [Boolean] # def multiple? @multi end # # Get all options for this select element # # @return [Array<Element>] # def options @element.find_elements :tag_name, 'option' end # # Get all selected options for this select element # # @return [Array<Element>] # def selected_options options.select { |e| e.selected? } end # # Get the first selected option in this select element # # @raise [Error::NoSuchElementError] if no options are selected # @return [Element] # def first_selected_option option = options.find { |e| e.selected? } option or raise Error::NoSuchElementError, 'no options are selected' end # # Select options by visible text, index or value. # # When selecting by :text, selects options that display text matching the argument. That is, when given "Bar" this # would select an option like: # # <option value="foo">Bar</option> # # When slecting by :value, selects all options that have a value matching the argument. That is, when given "foo" this # would select an option like: # # <option value="foo">Bar</option> # # When selecting by :index, selects the option at the given index. This is done by examining the "index" attribute of an # element, and not merely by counting. # # @param [:text, :index, :value] how How to find the option # @param [String] what What value to find the option by. # def select_by(how, what) case how when :text select_by_text what when :index select_by_index what when :value select_by_value what else raise ArgumentError, "can't select options by #{how.inspect}" end end # # Deselect options by visible text, index or value. # # @param [:text, :index, :value] how How to find the option # @param [String] what What value to find the option by. # # @see Select#select_by # def deselect_by(how, what) case how when :text deselect_by_text what when :value deselect_by_value what when :index deselect_by_index what else raise ArgumentError, "can't deselect options by #{how.inspect}" end end # # Select all unselected options. Only valid if the element supports multiple selections. # # @raise [Error::UnsupportedOperationError] if the element does not support multiple selections. # def select_all unless multiple? raise Error::UnsupportedOperationError, 'you may only select all options of a multi-select' end options.each { |e| select_option e } end # # Deselect all selected options. Only valid if the element supports multiple selections. # # @raise [Error::UnsupportedOperationError] if the element does not support multiple selections. # def deselect_all unless multiple? raise Error::UnsupportedOperationError, 'you may only deselect all options of a multi-select' end options.each { |e| deselect_option e } end private def select_by_text(text) opts = find_by_text text if opts.empty? raise Error::NoSuchElementError, "cannot locate element with text: #{text.inspect}" end select_options opts end def select_by_index(index) opts = find_by_index index if opts.empty? raise Error::NoSuchElementError, "cannot locate element with index: #{index.inspect}" end select_options opts end def select_by_value(value) opts = find_by_value value if opts.empty? raise Error::NoSuchElementError, "cannot locate option with value: #{value.inspect}" end select_options opts end def deselect_by_text(text) opts = find_by_text text if opts.empty? raise Error::NoSuchElementError, "cannot locate element with text: #{text.inspect}" end deselect_options opts end def deselect_by_value(value) opts = find_by_value value if opts.empty? raise Error::NoSuchElementError, "cannot locate option with value: #{value.inspect}" end deselect_options opts end def deselect_by_index(index) opts = find_by_index index if opts.empty? raise Error::NoSuchElementError, "cannot locate option with index: #{index}" end deselect_options opts end private def select_option(option) option.click unless option.selected? end def deselect_option(option) option.click if option.selected? end def select_options(opts) if multiple? opts.each { |o| select_option o } else select_option opts.first end end def deselect_options(opts) if multiple? opts.each { |o| deselect_option o } else deselect_option opts.first end end def find_by_text(text) xpath = ".//option[normalize-space(.) = #{Escaper.escape text}]" opts = @element.find_elements(:xpath, xpath) if opts.empty? && text =~ /\s+/ longest_word = text.split(/\s+/).max_by { |item| item.length } if longest_word.empty? candidates = options else xpath = ".//option[contains(., #{Escaper.escape longest_word})]" candidates = @element.find_elements(:xpath, xpath) end if multiple? candidates.select { |option| text == option.text } else Array(candidates.find { |option| text == option.text }) end else opts end end def find_by_index(index) index = index.to_s options.select { |option| option.attribute(:index) == index } end def find_by_value(value) @element.find_elements(:xpath, ".//option[@value = #{Escaper.escape value}]") end # # @api private # module Escaper def self.escape(str) if str.include?('"') && str.include?("'") parts = str.split('"', -1).map { |part| %{"#{part}"} } quoted = parts.join(%{, '"', }). gsub(/^"", |, ""$/, '') "concat(#{quoted})" elsif str.include?('"') # escape string with just a quote into being single quoted: f"oo -> 'f"oo' "'#{str}'" else # otherwise return the quoted string %{"#{str}"} end end end end end end end
27.285714
128
0.538893
ff8db76f8c47605674d666a5dd6c3db8bc65609c
16,257
#!/usr/bin/env rspec require 'spec_helper' MCollective::PluginManager.clear require File.dirname(__FILE__) + '/../../../../../plugins/mcollective/connector/stomp.rb' module MCollective module Connector describe Stomp do before do unless ::Stomp::Error.constants.map{|c| c.to_s}.include?("NoCurrentConnection") class ::Stomp::Error::NoCurrentConnection < RuntimeError ; end end @config = mock @config.stubs(:configured).returns(true) @config.stubs(:identity).returns("rspec") @config.stubs(:collectives).returns(["mcollective"]) @config.stubs(:topicprefix).returns("/topic/") @config.stubs(:topicsep).returns(".") logger = mock logger.stubs(:log) logger.stubs(:start) Log.configure(logger) Config.stubs(:instance).returns(@config) @msg = mock @msg.stubs(:base64_encode!) @msg.stubs(:payload).returns("msg") @msg.stubs(:agent).returns("agent") @msg.stubs(:type).returns(:reply) @msg.stubs(:collective).returns("mcollective") @subscription = mock @subscription.stubs("<<").returns(true) @subscription.stubs("include?").returns(false) @subscription.stubs("delete").returns(false) @connection = mock @connection.stubs(:subscribe).returns(true) @connection.stubs(:unsubscribe).returns(true) @c = Stomp.new @c.instance_variable_set("@subscriptions", @subscription) @c.instance_variable_set("@connection", @connection) end describe "#initialize" do it "should set the @config variable" do c = Stomp.new c.instance_variable_get("@config").should == @config end it "should set @subscriptions to an empty list" do c = Stomp.new c.instance_variable_get("@subscriptions").should == [] end end describe "#connect" do it "should not try to reconnect if already connected" do Log.expects(:debug).with("Already connection, not re-initializing connection").once @c.connect end it "should support old style config" do @config.expects(:pluginconf).returns({}).at_least_once @c.expects(:get_bool_option).with("stomp.base64", false) @c.expects(:get_option).with("stomp.priority", 0) @c.expects(:get_env_or_option).with("STOMP_SERVER", "stomp.host").returns("host") @c.expects(:get_env_or_option).with("STOMP_PORT", "stomp.port", 6163).returns(6163) @c.expects(:get_env_or_option).with("STOMP_USER", "stomp.user").returns("test_user") @c.expects(:get_env_or_option).with("STOMP_PASSWORD", "stomp.password").returns("test_password") connector = mock connector.expects(:new).with("test_user", "test_password", "host", 6163, true) @c.instance_variable_set("@connection", nil) @c.connect(connector) end it "should support new style config" do pluginconf = {"stomp.pool.size" => "2", "stomp.pool.host1" => "host1", "stomp.pool.port1" => "6163", "stomp.pool.user1" => "user1", "stomp.pool.password1" => "password1", "stomp.pool.ssl1" => "false", "stomp.pool.host2" => "host2", "stomp.pool.port2" => "6164", "stomp.pool.user2" => "user2", "stomp.pool.password2" => "password2", "stomp.pool.ssl2" => "true", "stomp.pool.initial_reconnect_delay" => "0.02", "stomp.pool.max_reconnect_delay" => "40", "stomp.pool.use_exponential_back_off" => "false", "stomp.pool.back_off_multiplier" => "3", "stomp.pool.max_reconnect_attempts" => "5", "stomp.pool.randomize" => "true", "stomp.pool.backup" => "true", "stomp.pool.connect_timeout" => 30, "stomp.pool.timeout" => "1"} ENV.delete("STOMP_USER") ENV.delete("STOMP_PASSWORD") @config.expects(:pluginconf).returns(pluginconf).at_least_once Stomp::EventLogger.expects(:new).returns("logger") connector = mock connector.expects(:new).with(:backup => true, :back_off_multiplier => 2, :max_reconnect_delay => 40.0, :timeout => 1, :use_exponential_back_off => false, :max_reconnect_attempts => 5, :initial_reconnect_delay => 0.02, :connect_timeout => 30, :randomize => true, :reliable => true, :logger => "logger", :hosts => [{:passcode => 'password1', :host => 'host1', :port => 6163, :ssl => false, :login => 'user1'}, {:passcode => 'password2', :host => 'host2', :port => 6164, :ssl => true, :login => 'user2'} ]) @c.instance_variable_set("@connection", nil) @c.connect(connector) end end describe "#receive" do it "should receive from the middleware" do payload = mock payload.stubs(:body).returns("msg") payload.stubs(:headers).returns("headers") @connection.expects(:receive).returns(payload) Message.expects(:new).with("msg", payload, :base64 => true, :headers => "headers").returns("message") @c.instance_variable_set("@base64", true) received = @c.receive received.should == "message" end it "should sleep and retry if recieving while disconnected" do payload = mock payload.stubs(:body).returns("msg") payload.stubs(:headers).returns("headers") Message.stubs(:new).returns("rspec") @connection.expects(:receive).raises(::Stomp::Error::NoCurrentConnection).returns(payload).twice @c.expects(:sleep).with(1) @c.receive.should == "rspec" end end describe "#publish" do before do @connection.stubs("respond_to?").with("publish").returns(true) @connection.stubs(:publish).with("test", "msg", {}).returns(true) end it "should base64 encode a message if configured to do so" do @c.instance_variable_set("@base64", true) @c.expects(:msgheaders).returns({}) @c.expects(:make_target).returns("test") @connection.expects(:publish).with("test", "msg", {}) @msg.stubs(:reply_to) @c.publish(@msg) end it "should not base64 encode if not configured to do so" do @c.instance_variable_set("@base64", false) @c.expects(:msgheaders).returns({}) @c.expects(:make_target).returns("test") @connection.expects(:publish).with("test", "msg", {}) @msg.stubs(:reply_to) @c.publish(@msg) end it "should publish direct requests for each discovered host" do @msg.expects(:type).returns(:direct_request).times(3) @msg.expects(:discovered_hosts).returns(["one", "two"]) @c.expects(:make_target).with("agent", :direct_request, "mcollective", "one").returns("target_one") @c.expects(:make_target).with("agent", :direct_request, "mcollective", "two").returns("target_two") @c.expects(:publish_msg).with("target_one", "msg") @c.expects(:publish_msg).with("target_two", "msg") @msg.stubs(:reply_to) @c.publish(@msg) end it "should raise an error if specific reply targets are requested" do @c.instance_variable_set("@base64", false) @msg.expects(:reply_to).returns(:foo) expect { @c.publish(@msg) }.to raise_error("Cannot set specific reply to targets with the STOMP plugin") end end describe "#publish_msg" do it "should use the publish method if it exists" do @connection.expects("respond_to?").with("publish").returns(true) @connection.expects(:publish).with("test", "msg", {}).once @c.stubs(:msgheaders).returns({}) @c.publish_msg("test", "msg") end it "should use the send method if publish does not exist" do @connection.expects("respond_to?").with('publish').returns(false) @connection.expects(:send).with("test", "msg", {}).once @c.stubs(:msgheaders).returns({}) @c.publish_msg("test", "msg") end it "should publish the correct message to the correct target with msgheaders" do @connection.expects("respond_to?").with("publish").returns(true) @connection.expects(:publish).with("test", "msg", {"test" => "test"}).once @c.expects(:msgheaders).returns({"test" => "test"}) @c.publish_msg("test", "msg") end end describe "#make_target" do it "should create correct targets" do @config.expects(:queueprefix).returns("/queue/").twice @c.make_target("test", :broadcast, "mcollective").should == "/topic/mcollective.test.command" @c.make_target("test", :directed, "mcollective").should == "/queue/mcollective.2bc84dc69b73db9383b9c6711d2011b7" @c.make_target("test", :direct_request, "mcollective", "rspec").should == "/queue/mcollective.2bc84dc69b73db9383b9c6711d2011b7" @c.make_target("test", :reply, "mcollective").should == "/topic/mcollective.test.reply" @c.make_target("test", :request, "mcollective").should == "/topic/mcollective.test.command" end it "should raise an error for unknown collectives" do expect { @c.make_target("test", :broadcast, "foo") }.to raise_error("Unknown collective 'foo' known collectives are 'mcollective'") end it "should raise an error for unknown types" do expect { @c.make_target("test", :test, "mcollective") }.to raise_error("Unknown target type test") end end describe "#unsubscribe" do it "should use make_target correctly" do @c.expects("make_target").with("test", :broadcast, "mcollective").returns({:target => "test", :headers => {}}) @c.unsubscribe("test", :broadcast, "mcollective") end it "should unsubscribe from the target" do @c.expects("make_target").with("test", :broadcast, "mcollective").returns("test") @connection.expects(:unsubscribe).with("test").once @c.unsubscribe("test", :broadcast, "mcollective") end it "should delete the source from subscriptions" do @c.expects("make_target").with("test", :broadcast, "mcollective").returns({:target => "test", :headers => {}}) @subscription.expects(:delete).with({:target => "test", :headers => {}}).once @c.unsubscribe("test", :broadcast, "mcollective") end end describe "#subscribe" do it "should use the make_target correctly" do @c.expects("make_target").with("test", :broadcast, "mcollective").returns("test") @c.subscribe("test", :broadcast, "mcollective") end it "should check for existing subscriptions" do @c.expects("make_target").returns("test").once @subscription.expects("include?").with("test").returns(false) @connection.expects(:subscribe).never @c.subscribe("test", :broadcast, "mcollective") end it "should subscribe to the middleware" do @c.expects("make_target").returns("test") @connection.expects(:subscribe).with("test").once @c.subscribe("test", :broadcast, "mcollective") end it "should add to the list of subscriptions" do @c.expects("make_target").returns("test") @subscription.expects("<<").with("test") @c.subscribe("test", :broadcast, "mcollective") end end describe "#disconnect" do it "should disconnect from the stomp connection" do @connection.expects(:disconnect) @c.disconnect end end describe "#msgheaders" do it "should return empty headers if priority is 0" do @c.instance_variable_set("@msgpriority", 0) @c.msgheaders.should == {} end it "should return a priority if prioritu is non 0" do @c.instance_variable_set("@msgpriority", 1) @c.msgheaders.should == {"priority" => 1} end end describe "#get_env_or_option" do it "should return the environment variable if set" do ENV["test"] = "rspec_env_test" @c.get_env_or_option("test", nil, nil).should == "rspec_env_test" ENV.delete("test") end it "should return the config option if set" do @config.expects(:pluginconf).returns({"test" => "rspec_test"}).twice @c.get_env_or_option("test", "test", "test").should == "rspec_test" end it "should return default if nothing else matched" do @config.expects(:pluginconf).returns({}).once @c.get_env_or_option("test", "test", "test").should == "test" end it "should raise an error if no default is supplied" do @config.expects(:pluginconf).returns({}).once expect { @c.get_env_or_option("test", "test") }.to raise_error("No test environment or plugin.test configuration option given") end end describe "#get_option" do it "should return the config option if set" do @config.expects(:pluginconf).returns({"test" => "rspec_test"}).twice @c.get_option("test").should == "rspec_test" end it "should return default option was not found" do @config.expects(:pluginconf).returns({}).once @c.get_option("test", "test").should == "test" end it "should raise an error if no default is supplied" do @config.expects(:pluginconf).returns({}).once expect { @c.get_option("test") }.to raise_error("No plugin.test configuration option given") end end describe "#get_bool_option" do it "should return the default if option isnt set" do @config.expects(:pluginconf).returns({}).once @c.get_bool_option("test", "default").should == "default" end ["1", "yes", "true"].each do |boolean| it "should map options to true correctly" do @config.expects(:pluginconf).returns({"test" => boolean}).twice @c.get_bool_option("test", "default").should == true end end ["0", "no", "false"].each do |boolean| it "should map options to false correctly" do @config.expects(:pluginconf).returns({"test" => boolean}).twice @c.get_bool_option("test", "default").should == false end end it "should return default for non boolean options" do @config.expects(:pluginconf).returns({"test" => "foo"}).twice @c.get_bool_option("test", "default").should == "default" end end end end end
38.707143
137
0.550101
ff8c9578c084c0e6d590d82828b1c8ce57ebf884
3,037
## # This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # web site for more information on licensing and terms of use. # http://metasploit.com/ ## require 'msf/core' class Metasploit3 < Msf::Auxiliary include Msf::Exploit::Capture include Msf::Auxiliary::Scanner include Msf::Auxiliary::Report def initialize super( 'Name' => 'TCP ACK Firewall Scanner', 'Description' => %q{ Map out firewall rulesets with a raw ACK scan. Any unfiltered ports found means a stateful firewall is not in place for them. }, 'Author' => 'kris katterjohn', 'License' => MSF_LICENSE ) register_options([ OptString.new('PORTS', [true, "Ports to scan (e.g. 22-25,80,110-900)", "1-10000"]), OptInt.new('TIMEOUT', [true, "The reply read timeout in milliseconds", 500]), OptInt.new('BATCHSIZE', [true, "The number of hosts to scan per set", 256]), OptString.new('INTERFACE', [false, 'The name of the interface']) ], self.class) deregister_options('FILTER','PCAPFILE') end # No IPv6 support yet def support_ipv6? false end def run_batch_size datastore['BATCHSIZE'] || 256 end def run_batch(hosts) open_pcap pcap = self.capture ports = Rex::Socket.portspec_crack(datastore['PORTS']) if ports.empty? print_error("Error: No valid ports specified") return end to = (datastore['TIMEOUT'] || 500).to_f / 1000.0 # Spread the load across the hosts ports.each do |dport| hosts.each do |dhost| shost, sport = getsource(dhost) pcap.setfilter(getfilter(shost, sport, dhost, dport)) begin probe = buildprobe(shost, sport, dhost, dport) capture_sendto(probe, dhost) reply = probereply(pcap, to) next if not reply print_status(" TCP UNFILTERED #{dhost}:#{dport}") #Add Report report_note( :host => dhost, :proto => 'tcp', :port => dport, :type => "TCP UNFILTERED #{dhost}:#{dport}", :data => "TCP UNFILTERED #{dhost}:#{dport}" ) rescue ::Exception print_error("Error: #{$!.class} #{$!}") end end end close_pcap end def getfilter(shost, sport, dhost, dport) # Look for associated RSTs "tcp and (tcp[13] & 0x04) != 0 and " + "src host #{dhost} and src port #{dport} and " + "dst host #{shost} and dst port #{sport}" end def getsource(dhost) # srcip, srcport [ Rex::Socket.source_address(dhost), rand(0xffff - 1025) + 1025 ] end def buildprobe(shost, sport, dhost, dport) p = PacketFu::TCPPacket.new p.ip_saddr = shost p.ip_daddr = dhost p.tcp_sport = sport p.tcp_ack = rand(0x100000000) p.tcp_flags.ack = 1 p.tcp_dport = dport p.tcp_win = 3072 p.recalc p end def probereply(pcap, to) reply = nil begin Timeout.timeout(to) do pcap.each do |r| pkt = PacketFu::Packet.parse(r) next unless pkt.is_tcp? reply = pkt break end end rescue Timeout::Error end return reply end end
21.848921
86
0.648996
6292e1dd8a0e1a96dacc8790d3698ca2c762f9b2
42
module SendWithUs VERSION = '4.1.0' end
10.5
19
0.690476
1d85ada1324aac744066a5a4546c3de217da76b8
239
class CreateResponseCacheMaps < ActiveRecord::Migration def change create_table :response_cache_maps do |t| t.integer :origin_id t.integer :target_id t.integer :response_set_id t.timestamps end end end
19.916667
55
0.707113
e8f60eb9e27fae0ab2a36f16072696aabf33b6a2
3,008
=begin #OpenAPI Petstore #This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech OpenAPI Generator version: 5.0.0-SNAPSHOT =end require 'cgi' module Petstore class FakeClassnameTags123Api attr_accessor :api_client def initialize(api_client = ApiClient.default) @api_client = api_client end # To test class name in snake case # To test class name in snake case # @param client [Client] client model # @param [Hash] opts the optional parameters # @return [Client] def test_classname(client, opts = {}) data, _status_code, _headers = test_classname_with_http_info(client, opts) data end # To test class name in snake case # To test class name in snake case # @param client [Client] client model # @param [Hash] opts the optional parameters # @return [Array<(Client, Integer, Hash)>] Client data, response status code and response headers def test_classname_with_http_info(client, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: FakeClassnameTags123Api.test_classname ...' end # verify the required parameter 'client' is set if @api_client.config.client_side_validation && client.nil? fail ArgumentError, "Missing the required parameter 'client' when calling FakeClassnameTags123Api.test_classname" end # resource path local_var_path = '/fake_classname_test' # query parameters query_params = opts[:query_params] || {} # header parameters header_params = opts[:header_params] || {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) # form parameters form_params = opts[:form_params] || {} # http body (model) post_body = opts[:debug_body] || @api_client.object_to_http_body(client) # return_type return_type = opts[:debug_return_type] || 'Client' # auth_names auth_names = opts[:debug_auth_names] || ['api_key_query'] new_options = opts.merge( :header_params => header_params, :query_params => query_params, :form_params => form_params, :body => post_body, :auth_names => auth_names, :return_type => return_type ) data, status_code, headers = @api_client.call_api(:PATCH, local_var_path, new_options) if @api_client.config.debugging @api_client.config.logger.debug "API called: FakeClassnameTags123Api#test_classname\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end return data, status_code, headers end end end
34.574713
165
0.688497
6288dbc49c9c6f943b3bcb55ab5604be1649e3d3
2,745
require './lib/token' class Lexer TOKENS = { # keywords, current list was taken from java # and does not match the final keyword list if: 'if', elif: 'elif', else: 'else', while: 'while', for: 'for', do: 'do', return: 'return', boolean: 'bool', int: 'int', void: 'void', class: 'class', new: 'new', private: 'private', protected: 'protected', public: 'public', static: 'static', super: 'super', this: 'this', # punctuation. i.e. symbols that seperate stuff instruction_seperator: ';', list_seperator: ',', identifier_seperator: '.', # brackets. i.e. symbols that group stuff together open_paren: '(', close_paren: ')', open_bracket: '[', close_bracket: ']', open_brace: '{', close_brace: '}', # comparison operators eqeq: '==', gteq: '>=', lteq: '<=', nteq: '!=', gt: '>', lt: '<', # assignment operators eq: '=', plus_eq: '+=', minus_eq: '-=', mult_eq: '*=', div_eq: '/=', mod_eq: '%=', # mathamatical operators incrament: '++', decrament: '--', plus: '+', minus: '-', mult: '*', div: '/', mod: '%', # boolean operators bool_and: '&&', bool_or: '||', bool_not: '!', # literal statements bool_true: 'true', bool_false: 'false', string: /\"(\\\"|[^\"])*\"/, decimal: /\d+\.\d+/, integer: /\d+/, # variables, methods, constants, classes, etc. identifier: /[A-Za-z_]\w*/, # comments comment_line: /\/\/[^\n]*(?=\n)/, # "// comment here" comment_block: /\/\*(\\.|[^\*]|\*(?!\/))*\*\//, # "/* comment here */" # white space white_space: /[ \t]/, new_line: '\n', # when something breaks unknown: /./ }.freeze def self.tokenize(str) matches = TOKENS.map { |symbol, pattern| match = match_regex(pattern, str); match ? [symbol, match] : nil }.compact.to_h len = matches.values.map(&:length).max matches = matches.map { |symbol, match| match.length == len ? [symbol, match] : nil }.compact.to_h token = nil if matches.length == 1 token = Token.new(matches.keys[0], matches[matches.keys[0]]) else matches.each do |symbol, match| token = Token.new(symbol, match) if TOKENS[symbol].is_a?(String) end if token.nil? token = Token.new(matches.keys[0], matches[matches.keys[0]]) end end if ( str.length == len ) return token else return [token, tokenize(str[len..-1])].flatten end end def self.match_regex(regex, str) if regex.is_a?(String) && regex == str[0..regex.length-1] return regex elsif regex.is_a?(Regexp) && /^#{regex}/.match?(str) return /^#{regex}/.match(str)[0] else return nil end end end
26.911765
80
0.553005
ac2b8c21e0e4407161648f8abb67da386f897cb0
1,847
class Libbdplus < Formula desc "Implements the BD+ System Specifications" homepage "https://www.videolan.org/developers/libbdplus.html" url "https://download.videolan.org/pub/videolan/libbdplus/0.1.2/libbdplus-0.1.2.tar.bz2" mirror "https://ftp.osuosl.org/pub/videolan/libbdplus/0.1.2/libbdplus-0.1.2.tar.bz2" sha256 "a631cae3cd34bf054db040b64edbfc8430936e762eb433b1789358ac3d3dc80a" bottle do cellar :any sha256 "0f6679a9e46eebf5d7a37a7b09d77b57512774fb3766eb4a359a60de8997a0e0" => :catalina sha256 "d8f4b53ec0ea12bbc02b2962e94dfe5df98ef55005f10209f4fd40213a80f601" => :mojave sha256 "478e405b0f9687edcea3f651f4ec922a1bd12c12476c3aa14d1a35d0bb0362bb" => :high_sierra sha256 "8205ed5218393f7aa7f2035f089e91a417f13d73f4b7e3d46f3afc5073ce7e37" => :sierra sha256 "7136cdf433318efb9691d43d078eb20e9647f2ae4999b42cf791736d95047a81" => :el_capitan sha256 "13f271c0bb73d496cda7314d6665478c19193f0eb3b9b7a9fbc1eb4a957894c9" => :yosemite sha256 "e2189073d60ed520ed852355aebf1a5137fec5bead346ebc68f2b202d495db36" => :mavericks end head do url "https://code.videolan.org/videolan/libbdplus.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end depends_on "libgcrypt" def install system "./bootstrap" if build.head? system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end test do (testpath/"test.c").write <<~EOS #include <libbdplus/bdplus.h> int main() { int major = -1; int minor = -1; int micro = -1; bdplus_get_version(&major, &minor, &micro); return 0; } EOS system ENV.cc, "test.c", "-L#{lib}", "-I#{include}", "-lbdplus", "-o", "test" system "./test" end end
36.215686
93
0.709258
5d9731cddf6029f3a06647d3a8df2eeaa5e3eb55
6,857
module ChatWork::Client::RoomMethods # Get the list of all chats on your account # # @see http://developer.chatwork.com/ja/endpoint_rooms.html#GET-rooms # @see http://download.chatwork.com/ChatWork_API_Documentation.pdf # # @yield [response_body, response_header] if block was given, return response body and response header through block arguments # @yieldparam response_body [Array<Hashie::Mash>] response body # @yieldparam response_header [Hash<String, String>] response header (e.g. X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset) # # @return [Array<Hashie::Mash>] # # @example response format # [ # { # "room_id": 123, # "name": "Group Chat Name", # "type": "group", # "role": "admin", # "sticky": false, # "unread_num": 10, # "mention_num": 1, # "mytask_num": 0, # "message_num": 122, # "file_num": 10, # "task_num": 17, # "icon_path": "https://example.com/ico_group.png", # "last_update_time": 1298905200 # } # ] def get_rooms(&block) get("/rooms", &block) end # rubocop:disable Metrics/ParameterLists # Create a new group chat # # @see http://developer.chatwork.com/ja/endpoint_rooms.html#POST-rooms # @see http://download.chatwork.com/ChatWork_API_Documentation.pdf # # @param description [String] Description of the group chat # @param icon_preset [String] Type of the group chat icon (group, check, document, meeting, event, project, business, # study, security, star, idea, heart, magcup, beer, music, sports, travel) # @param members_admin_ids [Array<Integer>, String] List of user IDs who will be given administrator permission for the group chat. # At least one user must be specified as an administrator. # @param members_member_ids [Array<Integer>, String] List of user IDs who will be given member permission for the group chat. # @param members_readonly_ids [Array<Integer>, String] List of user IDs who will be given read-only permission for the group chat. # @param name [String] Title of the group chat. # @param link [Boolean] whether create invitation link # @param link_code [String] link path (default. random string) # @param link_need_acceptance [Boolean] Approval necessity. Whether participation requires administrator approval. # # @yield [response_body, response_header] if block was given, return response body and response header through block arguments # @yieldparam response_body [Hashie::Mash] response body # @yieldparam response_header [Hash<String, String>] response header (e.g. X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset) # # @return [Hashie::Mash] # # @example response format # { # "room_id": 1234 # } def create_room(description: nil, icon_preset: nil, members_admin_ids:, members_member_ids: nil, members_readonly_ids: nil, name:, link: nil, link_code: nil, link_need_acceptance: nil, &block) params = { description: description, icon_preset: icon_preset, members_admin_ids: Array(members_admin_ids).join(","), name: name, link: boolean_to_integer(link), link_need_acceptance: boolean_to_integer(link_need_acceptance), link_code: link_code, } params[:members_member_ids] = Array(members_member_ids).join(",") if members_member_ids params[:members_readonly_ids] = Array(members_readonly_ids).join(",") if members_readonly_ids post("/rooms", params, &block) end # rubocop:enable Metrics/ParameterLists # Get chat name, icon, and Type (my, direct, or group) # # @see http://developer.chatwork.com/ja/endpoint_rooms.html#GET-rooms-room_id # @see http://download.chatwork.com/ChatWork_API_Documentation.pdf # # @param room_id [Integer] # # @yield [response_body, response_header] if block was given, return response body and response header through block arguments # @yieldparam response_body [Hashie::Mash] response body # @yieldparam response_header [Hash<String, String>] response header (e.g. X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset) # # @return [Hashie::Mash] # # @example response format # { # "room_id": 123, # "name": "Group Chat Name", # "type": "group", # "role": "admin", # "sticky": false, # "unread_num": 10, # "mention_num": 1, # "mytask_num": 0, # "message_num": 122, # "file_num": 10, # "task_num": 17, # "icon_path": "https://example.com/ico_group.png", # "last_update_time": 1298905200, # "description": "room description text" # } def find_room(room_id:, &block) get("/rooms/#{room_id}", &block) end # Change the title and icon type of the specified chat # # @see http://developer.chatwork.com/ja/endpoint_rooms.html#PUT-rooms-room_id # @see http://download.chatwork.com/ChatWork_API_Documentation.pdf # # @param room_id [Integer] # @param description [String] Description of the group chat # @param icon_preset [String] Type of the group chat icon (group, check, document, meeting, event, project, business, # study, security, star, idea, heart, magcup, beer, music, sports, travel) # @param name [String] Title of the group chat. # # @yield [response_body, response_header] if block was given, return response body and response header through block arguments # @yieldparam response_body [Hashie::Mash] response body # @yieldparam response_header [Hash<String, String>] response header (e.g. X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset) # # @return [Hashie::Mash] # # @example response format # { # "room_id": 1234 # } def update_room(room_id:, description: nil, icon_preset: nil, name: nil, &block) put("/rooms/#{room_id}", description: description, icon_preset: icon_preset, name: name, &block) end # Leave/Delete a group chat # # @see http://developer.chatwork.com/ja/endpoint_rooms.html#DELETE-rooms-room_id # @see http://download.chatwork.com/ChatWork_API_Documentation.pdf # # @param room_id [Integer] # @param action_type [String] leave from a room or delete a room (leave, delete) # # @yield [response_body, response_header] if block was given, return response body and response header through block arguments # @yieldparam response_body [Hashie::Mash] response body # @yieldparam response_header [Hash<String, String>] response header (e.g. X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset) def destroy_room(room_id:, action_type:, &block) delete("/rooms/#{room_id}", action_type: action_type, &block) end end
43.675159
137
0.674347
f89666167193af84a4e5638d1b98d8853f7ff961
3,408
# frozen_string_literal: true require 'uri' require 'http' RSpec.describe HTTP::Tracer do context 'without instrumentation' do it 'does not add headers' do uri = URI('http://localhost:3000') opts = HTTP::Options.new client = HTTP::Client.new allow(client).to receive(:request) client.request('GET', uri, opts) expect(client).to have_received(:request).with('GET', uri, opts) end end context 'with instrumentation' do after do HTTP::Tracer.remove end it 'starts a span for the request' do tracer = double(start_active_span: true) HTTP::Tracer.instrument(tracer: tracer) client = HTTP::Client.new client.request('GET', URI('http://localhost:3000')) expect(tracer).to have_received(:start_active_span) end it 'can be configured to skip creating a span for some requests' do tracer = double(start_active_span: true) HTTP::Tracer.instrument( tracer: tracer, ignore_request: ->(_, uri, _) { uri.host == 'localhost' } ) client = HTTP::Client.new allow(client).to receive(:request_original) client.request('GET', URI('http://localhost:3000')) expect(tracer).not_to have_received(:start_active_span) expect(client).to have_received(:request_original) client.request('GET', URI('http://myhost.com:3000')) expect(tracer).to have_received(:start_active_span) end it 'follows semantic conventions for the span tags' do tracer = double(start_active_span: true) HTTP::Tracer.instrument(tracer: tracer) client = HTTP::Client.new client.request('POST', URI('http://localhost/api/data')) expect(tracer).to have_received(:start_active_span).with( 'http.request', tags: { 'component' => 'ruby-httprb', 'span.kind' => 'client', 'http.method' => 'POST', 'http.url' => '/api/data', 'peer.host' => 'localhost', 'peer.port' => 80 } ) end it 'handles non standard URI object from client' do CustomURI = Struct.new(:host) uri = CustomURI.new("localhost") tracer = double(start_active_span: true) HTTP::Tracer.instrument(tracer: tracer) client = HTTP::Client.new client.request('POST', uri) expect(tracer).to have_received(:start_active_span).with( 'http.request', tags: { 'component' => 'ruby-httprb', 'span.kind' => 'client', 'http.method' => 'POST', 'http.url' => nil, 'peer.host' => 'localhost', 'peer.port' => nil } ) end it 'tags the span as an error when the response is an error' do error = StandardError.new('500 error') allow(error).to receive(:status).and_return(500) span = double(set_tag: true, context: nil) scope = double(span: span) tracer = double(start_active_span: true) allow(tracer).to receive(:start_active_span).and_yield(scope) HTTP::Tracer.instrument(tracer: tracer) client = HTTP::Client.new allow(client).to receive(:request_original).and_return(error) client.request('GET', URI('http://localhost:3000')) expect(span).to have_received(:set_tag).with('http.status_code', 500) expect(span).to have_received(:set_tag).with('error', true) end end end
28.881356
75
0.620012
bfadfb7af38ad46d2c0fdca40b65707c72b1564f
6,908
module RedCloth::Formatters::HTML include RedCloth::Formatters::Base [:h1, :h2, :h3, :h4, :h5, :h6, :p, :pre, :div].each do |m| define_method(m) do |opts| "<#{m}#{pba(opts)}>#{opts[:text]}</#{m}>\n" end end [:strong, :code, :em, :i, :b, :ins, :sup, :sub, :span, :cite].each do |m| define_method(m) do |opts| opts[:block] = true "<#{m}#{pba(opts)}>#{opts[:text]}</#{m}>" end end def hr(opts) "<hr#{pba(opts)} />\n" end def acronym(opts) opts[:block] = true "<acronym#{pba(opts)}>#{caps(:text => opts[:text])}</acronym>" end def caps(opts) if no_span_caps opts[:text] else opts[:class] = 'caps' span(opts) end end def del(opts) opts[:block] = true "<del#{pba(opts)}>#{opts[:text]}</del>" end [:ol, :ul].each do |m| define_method("#{m}_open") do |opts| opts[:block] = true "#{"\n" if opts[:nest] > 1}#{"\t" * (opts[:nest] - 1)}<#{m}#{pba(opts)}>\n" end define_method("#{m}_close") do |opts| "#{"\t" * (opts[:nest] - 1)}</#{m}>#{"\n" if opts[:nest] <= 1}" end end def li_open(opts) "#{"\t" * opts[:nest]}<li#{pba(opts)}>#{opts[:text]}" end def li_close(opts=nil) "</li>\n" end def dl_open(opts) opts[:block] = true "<dl#{pba(opts)}>\n" end def dl_close(opts=nil) "</dl>\n" end [:dt, :dd].each do |m| define_method(m) do |opts| "\t<#{m}#{pba(opts)}>#{opts[:text]}</#{m}>\n" end end def td(opts) tdtype = opts[:th] ? 'th' : 'td' "\t\t<#{tdtype}#{pba(opts)}>#{opts[:text]}</#{tdtype}>\n" end def tr_open(opts) "\t<tr#{pba(opts)}>\n" end def tr_close(opts) "\t</tr>\n" end def table_open(opts) "<table#{pba(opts)}>\n" end def table_close(opts) "</table>\n" end def bc_open(opts) opts[:block] = true "<pre#{pba(opts)}>" end def bc_close(opts) "</pre>\n" end def bq_open(opts) opts[:block] = true cite = opts[:cite] ? " cite=\"#{ escape_attribute opts[:cite] }\"" : '' "<blockquote#{cite}#{pba(opts)}>\n" end def bq_close(opts) "</blockquote>\n" end def link(opts) "<a href=\"#{escape_attribute opts[:href]}\"#{pba(opts)}>#{opts[:name]}</a>" end def image(opts) opts.delete(:align) opts[:alt] = opts[:title] img = "<img src=\"#{escape_attribute opts[:src]}\"#{pba(opts)} alt=\"#{escape_attribute opts[:alt].to_s}\" />" img = "<a href=\"#{escape_attribute opts[:href]}\">#{img}</a>" if opts[:href] img end def footno(opts) opts[:id] ||= opts[:text] %Q{<sup class="footnote" id=\"fnr#{opts[:id]}\"><a href=\"#fn#{opts[:id]}\">#{opts[:text]}</a></sup>} end def fn(opts) no = opts[:id] opts[:id] = "fn#{no}" opts[:class] = ["footnote", opts[:class]].compact.join(" ") "<p#{pba(opts)}><a href=\"#fnr#{no}\"><sup>#{no}</sup></a> #{opts[:text]}</p>\n" end def snip(opts) "<pre#{pba(opts)}><code>#{opts[:text]}</code></pre>\n" end def quote1(opts) "&#8216;#{opts[:text]}&#8217;" end def quote2(opts) "&#8220;#{opts[:text]}&#8221;" end def multi_paragraph_quote(opts) "&#8220;#{opts[:text]}" end def ellipsis(opts) "#{opts[:text]}&#8230;" end def emdash(opts) "&#8212;" end def endash(opts) " &#8211; " end def arrow(opts) "&#8594;" end def dim(opts) opts[:text].gsub!('x', '&#215;') opts[:text].gsub!("'", '&#8242;') opts[:text].gsub!('"', '&#8243;') opts[:text] end def trademark(opts) "&#8482;" end def registered(opts) "&#174;" end def copyright(opts) "&#169;" end def entity(opts) "&#{opts[:text]};" end def amp(opts) "&amp;" end def gt(opts) "&gt;" end def lt(opts) "&lt;" end def br(opts) if hard_breaks == false "\n" else "<br#{pba(opts)} />\n" end end def quot(opts) "&quot;" end def squot(opts) "&#8217;" end def apos(opts) "&#39;" end def html(opts) "#{opts[:text]}\n" end def html_block(opts) inline_html(:text => "#{opts[:indent_before_start]}#{opts[:start_tag]}#{opts[:indent_after_start]}") + "#{opts[:text]}" + inline_html(:text => "#{opts[:indent_before_end]}#{opts[:end_tag]}#{opts[:indent_after_end]}") end def notextile(opts) if filter_html html_esc(opts[:text], :html_escape_preformatted) else opts[:text] end end def inline_html(opts) if filter_html html_esc(opts[:text], :html_escape_preformatted) else "#{opts[:text]}" # nil-safe end end def ignored_line(opts) opts[:text] + "\n" end private # escapement for regular HTML (not in PRE tag) def escape(text) html_esc(text) end # escapement for HTML in a PRE tag def escape_pre(text) html_esc(text, :html_escape_preformatted) end # escaping for HTML attributes def escape_attribute(text) html_esc(text, :html_escape_attributes) end def after_transform(text) text.chomp! end def before_transform(text) clean_html(text) if sanitize_html end # HTML cleansing stuff BASIC_TAGS = { 'a' => ['href', 'title'], 'img' => ['src', 'alt', 'title'], 'br' => [], 'i' => nil, 'u' => nil, 'b' => nil, 'pre' => nil, 'kbd' => nil, 'code' => ['lang'], 'cite' => nil, 'strong' => nil, 'em' => nil, 'ins' => nil, 'sup' => nil, 'sub' => nil, 'del' => nil, 'table' => nil, 'tr' => nil, 'td' => ['colspan', 'rowspan'], 'th' => nil, 'ol' => ['start'], 'ul' => nil, 'li' => nil, 'p' => nil, 'h1' => nil, 'h2' => nil, 'h3' => nil, 'h4' => nil, 'h5' => nil, 'h6' => nil, 'blockquote' => ['cite'], 'notextile' => nil } # Clean unauthorized tags. def clean_html( text, allowed_tags = BASIC_TAGS ) text.gsub!( /<!\[CDATA\[/, '' ) text.gsub!( /<(\/*)([A-Za-z]\w*)([^>]*?)(\s?\/?)>/ ) do |m| raw = $~ tag = raw[2].downcase if allowed_tags.has_key? tag pcs = [tag] allowed_tags[tag].each do |prop| ['"', "'", ''].each do |q| q2 = ( q != '' ? q : '\s' ) if raw[3] =~ /#{prop}\s*=\s*#{q}([^#{q2}]+)#{q}/i attrv = $1 next if (prop == 'src' or prop == 'href') and not attrv =~ %r{^(http|https|ftp):} pcs << "#{prop}=\"#{attrv.gsub('"', '\\"')}\"" break end end end if allowed_tags[tag] "<#{raw[1]}#{pcs.join " "}#{raw[4]}>" else # Unauthorized tag if block_given? yield m else '' end end end end end
19.965318
116
0.490735
01a6ad491ab1d0d08e7fa4fbb1862fd14382e0ac
2,330
class Supervisor < Formula include Language::Python::Virtualenv desc "Process Control System" homepage "http://supervisord.org/" url "https://files.pythonhosted.org/packages/b3/41/2806c3c66b3e4a847843821bc0db447a58b7a9b0c39a49b354f287569130/supervisor-4.2.4.tar.gz" sha256 "40dc582ce1eec631c3df79420b187a6da276bbd68a4ec0a8f1f123ea616b97a2" license "BSD-3-Clause-Modification" head "https://github.com/Supervisor/supervisor.git", branch: "master" bottle do root_url "https://github.com/gromgit/homebrew-core-mojave/releases/download/supervisor" sha256 cellar: :any_skip_relocation, mojave: "7831c5348e5af718d21a3f806c1fd9c35da9a75c8a61a3aa91c639c17cf7989f" end depends_on "[email protected]" def install inreplace buildpath/"supervisor/skel/sample.conf" do |s| s.gsub! %r{/tmp/supervisor\.sock}, var/"run/supervisor.sock" s.gsub! %r{/tmp/supervisord\.log}, var/"log/supervisord.log" s.gsub! %r{/tmp/supervisord\.pid}, var/"run/supervisord.pid" s.gsub!(/^;\[include\]$/, "[include]") s.gsub! %r{^;files = relative/directory/\*\.ini$}, "files = #{etc}/supervisor.d/*.ini" end virtualenv_install_with_resources etc.install buildpath/"supervisor/skel/sample.conf" => "supervisord.conf" end def post_install (var/"run").mkpath (var/"log").mkpath conf_warn = <<~EOS The default location for supervisor's config file is now: #{etc}/supervisord.conf Please move your config file to this location and restart supervisor. EOS old_conf = etc/"supervisord.ini" opoo conf_warn if old_conf.exist? end service do run [opt_bin/"supervisord", "-c", etc/"supervisord.conf", "--nodaemon"] keep_alive true end test do (testpath/"sd.ini").write <<~EOS [unix_http_server] file=supervisor.sock [supervisord] loglevel=debug [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix://supervisor.sock EOS begin pid = fork { exec bin/"supervisord", "--nodaemon", "-c", "sd.ini" } sleep 1 output = shell_output("#{bin}/supervisorctl -c sd.ini version") assert_match version.to_s, output ensure Process.kill "TERM", pid end end end
31.486486
138
0.695279
d5e02409726d8c1aefc605e47ea01c85ca8a128b
744
class Company < ActiveRecord::Base belongs_to :user belongs_to :industry has_many :job_descriptions, dependent: :destroy has_many :activities, as: :trackable, dependent: :destroy has_many :applicants, dependent: :destroy validates :company_name, :clientname, :role, :email, :phonenumber, :about, presence: true validates :phonenumber, format: { with: /\A[-+]?[0-9]*\.?[0-9]+\Z/, message: "only allows numbers" } def updated? self.update_button? end def contact self.update(contacted: true) end def no_contact self.update(contacted: false) end def no_deal self.update(deal: false) end def deal_true self.update(deal: true) end def remove_related_activities_from_newsfeed end end
21.257143
102
0.706989
03675f2f729c68cd9ee00c37a232876c985f5b20
2,757
module Geminabox class GemStore attr_accessor :gem, :overwrite def self.create(gem, overwrite = false) gem_store = new(gem, overwrite) gem_store.save end def initialize(gem, overwrite = false) @gem = gem @overwrite = overwrite && overwrite == 'true' end def save ensure_gem_valid prepare_data_folders check_replacement_status write_and_index end def prepare_data_folders ensure_existing_data_folder_compatible begin FileUtils.mkdir_p(File.join(Geminabox.data, "gems")) rescue raise GemStoreError.new( 500, "Could not create #{File.expand_path(Geminabox.data)}." ) end end def check_replacement_status if !overwrite and Geminabox::Server.disallow_replace? and File.exist?(gem.dest_filename) if existing_file_digest != gem.hexdigest raise GemStoreError.new(409, "Updating an existing gem is not permitted.\nYou should either delete the existing version, or change your version number.") else raise GemStoreError.new(200, "Ignoring upload, you uploaded the same thing previously.\nPlease use -o to overwrite.") end end end def ensure_gem_valid raise GemStoreError.new(400, "Cannot process gem") unless gem.valid? end private def ensure_existing_data_folder_compatible if File.exist? Geminabox.data ensure_data_folder_is_directory ensure_data_folder_is_writable end end def ensure_data_folder_is_directory raise GemStoreError.new( 500, "Please ensure #{File.expand_path(Geminabox.data)} is a directory." ) unless File.directory? Geminabox.data end def ensure_data_folder_is_writable raise GemStoreError.new( 500, "Please ensure #{File.expand_path(Geminabox.data)} is writable by the geminabox web server." ) unless File.writable? Geminabox.data end def existing_file_digest Digest::SHA1.file(gem.dest_filename).hexdigest end def write_and_index tmpfile = gem.gem_data atomic_write(gem.dest_filename) do |f| while blk = tmpfile.read(65536) f << blk end end Geminabox::Server.reindex end # based on http://as.rubyonrails.org/classes/File.html def atomic_write(file_name) temp_dir = File.join(Geminabox.data, "_temp") FileUtils.mkdir_p(temp_dir) temp_file = Tempfile.new("." + File.basename(file_name), temp_dir) temp_file.binmode yield temp_file temp_file.close File.rename(temp_file.path, file_name) File.chmod(Geminabox::Server.gem_permissions, file_name) end end end
27.57
163
0.670294
bb8ce7367a349e16118cf98cd2905f6b9ecbd5ff
460
class ApplicationController < ActionController::Base protect_from_forgery def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end helper_method :current_user def authenticate! unless current_user redirect_to(login_url, alert: "Anmeldung erforderlich.") and return end end rescue_from CanCan::AccessDenied do |e| flash[:error] = "Zugriff verweigert!" redirect_to(root_url) end end
20.909091
73
0.732609
26c7f1935625e1614d012ce5ebf703331c9871bf
283
require 'flynn-schema/version' module FlynnSchema def self.dir @dir ||= File.expand_path(File.join(__FILE__, '..', '..')) end def self.paths @paths ||= Dir[File.join(dir, '**', '*.json')].reject do |path| path.index(File.join(dir, 'lib', '')) end end end
20.214286
67
0.59364
e9e854b0928f1d89334405d0ad4a0d41aa9dd762
2,145
class Hspell < Formula desc "Free Hebrew linguistic project" homepage "http://hspell.ivrix.org.il/" url "http://hspell.ivrix.org.il/hspell-1.4.tar.gz" sha256 "7310f5d58740d21d6d215c1179658602ef7da97a816bc1497c8764be97aabea3" license "AGPL-3.0-only" livecheck do url "http://hspell.ivrix.org.il/download.html" regex(/href=.*?hspell[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do rebuild 1 sha256 arm64_monterey: "743ad6762f4452a62702961c030950a6d70d36877140dd8728ce45f8d06411c3" sha256 arm64_big_sur: "421fdc3ab5d0ebde258ce7bdb235d2b50144966a27a74cbbe5c607dff0984c7f" sha256 monterey: "21abb651324e2e46eae76ae915efe203f198a7a74f7c9144b3d21060fc5a2dfd" sha256 big_sur: "426c87d91350f33392c862296b5d1b0081bc953adae5c04a9769ebb2a626213f" sha256 catalina: "a0406d5a4d5adefa40b5e820510a9b7f461fcea6a61112103c112775fff49ae8" sha256 mojave: "32e8037e9d494241b975c7558635456991285d53c9bbc89005cd6c86744f30e3" sha256 x86_64_linux: "fd7cae8024a97aadce0f713008dba1f27e7254969f689a21c9501d42be84fcdb" end depends_on "autoconf" => :build uses_from_macos "zlib" on_macos do # hspell was built for linux and compiles a .so shared library, to comply with macOS # standards this patch creates a .dylib instead patch :p0 do url "https://raw.githubusercontent.com/Homebrew/formula-patches/85fa66a9/hspell/1.3.patch" sha256 "63cc1bc753b1062d1144dcdd959a0a8f712b8872dce89e54ddff2d24f2ca2065" end end def install ENV.deparallelize # The build scripts rely on "." being in @INC which was disabled by default in perl 5.26 ENV["PERL_USE_UNSAFE_INC"] = "1" # autoconf needs to pick up on the patched configure.in and create a new ./configure # script system "autoconf" system "./configure", "--prefix=#{prefix}", "--enable-shared", "--enable-linginfo" system "make", "dolinginfo" system "make", "install" end test do File.open("test.txt", "w:ISO8859-8") do |f| f.write "שלום" end system "#{bin}/hspell", "-l", "test.txt" end end
35.163934
96
0.713287
2127c787cba2144aff9161c592317d35431cf388
304
module IronWorkerNG module Code module Runtime module Mono include IronWorkerNG::Feature::Common::MergeExec::InstanceMethods def runtime_run_code(local, params) <<RUN_CODE mono #{File.basename(@exec.path)} #{params} RUN_CODE end end end end end
19
73
0.651316
ff6897e741cef54b67985b7cf8f07225172a35be
3,100
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20160614210722) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "albums", force: :cascade do |t| t.string "title", null: false t.string "artist", null: false t.string "cover" t.text "description" t.text "thoughts" t.integer "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "albums", ["title", "artist"], name: "index_albums_on_title_and_artist", unique: true, using: :btree add_index "albums", ["user_id"], name: "index_albums_on_user_id", using: :btree create_table "examples", force: :cascade do |t| t.text "text", null: false t.integer "user_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "examples", ["user_id"], name: "index_examples_on_user_id", using: :btree create_table "relationships", force: :cascade do |t| t.integer "follower_id" t.integer "followed_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "relationships", ["followed_id"], name: "index_relationships_on_followed_id", using: :btree add_index "relationships", ["follower_id", "followed_id"], name: "index_relationships_on_follower_id_and_followed_id", unique: true, using: :btree add_index "relationships", ["follower_id"], name: "index_relationships_on_follower_id", using: :btree create_table "users", force: :cascade do |t| t.string "email", null: false t.string "token", null: false t.string "password_digest", null: false t.string "username", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "users", ["email", "username"], name: "index_users_on_email_and_username", unique: true, using: :btree add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree add_index "users", ["token"], name: "index_users_on_token", unique: true, using: :btree add_index "users", ["username"], name: "index_users_on_username", unique: true, using: :btree add_foreign_key "albums", "users" add_foreign_key "examples", "users" end
44.285714
148
0.706452
e2ad06c4e52bcf23b7944b1e6394609826582aea
1,794
module Tronprint # The Statistics class is your gateway to fetching statistics about # the energy usage and footprint of your app. class Statistics attr_accessor :aggregator, :cpu_monitor def initialize(aggregator, cpu_monitor) self.aggregator = aggregator self.cpu_monitor = cpu_monitor end # Fetch the total CPU time (in seconds) used by the application. def total_duration aggregator[cpu_monitor.key] end # Fetch total CPU time (in seconds) for a given range def range_duration(from, to) aggregator.range_total cpu_monitor.key, from, to end # Calculate emissions using aggregated data. A call is made to # Brighter Planet's CM1 emission estimate service. Specifically, # the call is made to the {computation emitter}[http://impact.brighterplanet.com/models/computation] def impact(from = nil, to = nil) duration = from.nil? ? total_duration : range_duration(from, to) app = Application.new :zip_code => Tronprint.zip_code, :duration => duration, :brighter_planet_key => Tronprint.brighter_planet_key app.impact end def emission_estimate(from = nil, to = nil) if response = impact(from, to) response.decisions.carbon.object.value end end # The total amount of CO2e generated by the application. def total_footprint emission_estimate end # The total amount of electricity used by the application. def total_electricity if response = impact impact.decisions.electricity_use.object end end # A URL for the methodology statement of the total_footprint calculation. def total_footprint_methodology if response = impact response.methodology end end end end
29.9
104
0.697882
abec44dc8b6ff470d3495cf25a732849fa0160e9
199
module Jinaki module Helper module Slack private def slack_webhook @slack_webhook ||= ::Slack::Incoming::Webhooks.new(ENV['SLACK_WEBHOOK_URL']) end end end end
16.583333
84
0.638191
913728a5980cfaad2eabc667004408bdead0bc88
7,038
=begin #OpenAPI Petstore #This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech OpenAPI Generator version: 5.3.2-SNAPHOT =end require 'date' require 'time' module Petstore class OuterComposite attr_accessor :my_number attr_accessor :my_string attr_accessor :my_boolean # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'my_number' => :'my_number', :'my_string' => :'my_string', :'my_boolean' => :'my_boolean' } 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 { :'my_number' => :'Float', :'my_string' => :'String', :'my_boolean' => :'Boolean' } 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 `Petstore::OuterComposite` initialize method" end # check to see if the attribute exists and convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| if (!self.class.attribute_map.key?(k.to_sym)) fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::OuterComposite`. 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?(:'my_number') self.my_number = attributes[:'my_number'] end if attributes.key?(:'my_string') self.my_string = attributes[:'my_string'] end if attributes.key?(:'my_boolean') self.my_boolean = attributes[:'my_boolean'] 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 && my_number == o.my_number && my_string == o.my_string && my_boolean == o.my_boolean 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 [my_number, my_string, my_boolean].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 /\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 = Petstore.const_get(type) klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.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) 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
29.696203
202
0.62262
bb52e12d8c8fde058f2fc769412a06dc185fba13
317
#!/usr/bin/env ruby $: << File.expand_path('lib') <%= run sq(<<-'rb') require 'cl' class Add < Cl::Cmd register :add opt '--to GROUP', type: :array def run p to end end rb -%> <%= run "Cl.new('owners').run(%w(add --to one --to two))" %> <%= out '["one", "two"]' %>
14.409091
60
0.463722
e9b8ee216f842b4fcc29b54c91ad23d8132d18ca
937
module Observee class Daemon class << self def run Observee.config.observers.each do |observer_data| observer_data = observer_data.map{ |k, v| [k.to_sym, v] }.to_h @supervisor = Observer.supervise(args: [observer_data]) end timers = Timers::Group.new timers.now_and_every(Observee.config.interval || 5) do observers.each do |observer| observer.async.check_and_log end end begin loop do timers.wait end rescue Exception => e supervisor.terminate raise e end end def stop if supervisor supervisor.terminate end end def restart stop run end private def supervisor @supervisor end def observers supervisor.actors end end end end
18.372549
72
0.532551
ab187f26fa31ffd6c6137c9a7998e38e35657c03
1,902
# -*- encoding: utf-8 -*- # stub: http_parser.rb 0.6.0 ruby lib # stub: ext/ruby_http_parser/extconf.rb Gem::Specification.new do |s| s.name = "http_parser.rb".freeze s.version = "0.6.0" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["Marc-Andre Cournoyer".freeze, "Aman Gupta".freeze] s.date = "2013-12-11" s.description = "Ruby bindings to http://github.com/ry/http-parser and http://github.com/a2800276/http-parser.java".freeze s.email = ["[email protected]".freeze, "[email protected]".freeze] s.extensions = ["ext/ruby_http_parser/extconf.rb".freeze] s.files = ["ext/ruby_http_parser/extconf.rb".freeze] s.homepage = "http://github.com/tmm1/http_parser.rb".freeze s.licenses = ["MIT".freeze] s.rubygems_version = "3.3.8".freeze s.summary = "Simple callback-based HTTP request/response parser".freeze s.installed_by_version = "3.3.8" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 end if s.respond_to? :add_runtime_dependency then s.add_development_dependency(%q<rake-compiler>.freeze, [">= 0.7.9"]) s.add_development_dependency(%q<rspec>.freeze, [">= 2.0.1"]) s.add_development_dependency(%q<json>.freeze, [">= 1.4.6"]) s.add_development_dependency(%q<benchmark_suite>.freeze, [">= 0"]) s.add_development_dependency(%q<ffi>.freeze, [">= 0"]) s.add_development_dependency(%q<yajl-ruby>.freeze, [">= 0.8.1"]) else s.add_dependency(%q<rake-compiler>.freeze, [">= 0.7.9"]) s.add_dependency(%q<rspec>.freeze, [">= 2.0.1"]) s.add_dependency(%q<json>.freeze, [">= 1.4.6"]) s.add_dependency(%q<benchmark_suite>.freeze, [">= 0"]) s.add_dependency(%q<ffi>.freeze, [">= 0"]) s.add_dependency(%q<yajl-ruby>.freeze, [">= 0.8.1"]) end end
43.227273
124
0.684543
bbf409e37d2e45dee0c61ecbbd64cf66ab9ef769
5,892
# frozen_string_literal: true require "rails_helper" describe "Signup feature" do before do create(:admin) APP_CONFIG["first_user_admin"] = { "enabled" => true } APP_CONFIG["signup"] = { "enabled" => true } visit new_user_registration_url end let!(:registry) { create(:registry) } let(:user) { build(:user) } it "As a guest I am able to signup from login page" do visit new_user_session_url click_link("Create a new account") expect(page).to have_field("user_email") expect(page).not_to have_css("section.first-user") expect(page).not_to have_css("#user_admin", visible: false) end it "The first user to be created is the admin if first_user_admin is enabled" do User.delete_all visit new_user_registration_url expect(page).to have_content("Create admin") expect(page).to have_css("#user_admin", visible: false) end it "The first user to be created is NOT admin if first_user_admin is disabled" do User.delete_all APP_CONFIG["first_user_admin"] = { "enabled" => false } visit new_user_registration_url expect(page).not_to have_content("Create admin") expect(page).not_to have_css("#user_admin", visible: false) end it "The portus user does not interfere with regular admin creation" do User.delete_all create_portus_user! visit new_user_registration_url expect(page).to have_content("Create admin") expect(page).to have_css("#user_admin", visible: false) end it "As a guest I am able to signup" do expect(page).not_to have_content("Create admin") fill_in "user_username", with: user.username fill_in "user_email", with: user.email fill_in "user_password", with: user.password fill_in "user_password_confirmation", with: user.password click_button("Create account") expect(page).to have_content("Recent activities") expect(page).to have_content("Repositories") expect(page).to have_content("Welcome! You have signed up successfully. "\ "Your personal namespace is '#{user.username}'.") expect(current_url).to eq root_url end it "As a guest I am able to signup with a weird username" do username = user.username + "!" expect(page).not_to have_content("Create admin") fill_in "user_username", with: username fill_in "user_email", with: user.email fill_in "user_password", with: user.password fill_in "user_password_confirmation", with: user.password click_button("Create account") expect(page).to have_content("Recent activities") expect(page).to have_content("Repositories") expect(page).to have_content("Welcome! You have signed up successfully. "\ "Your personal namespace is '#{user.username}' " \ "(your username was not a valid Docker namespace, "\ "so we had to tweak it).") expect(current_url).to eq root_url end it "always redirects to the signup page when there are no users" do User.delete_all visit new_user_session_url expect(current_url).to eq new_user_registration_url visit root_url expect(current_url).to eq new_user_registration_url expect(page).to have_css("section.first-user") end it "always redirects to the signin page when there are no users but LDAP is enabled" do User.delete_all APP_CONFIG["ldap"]["enabled"] = true visit new_user_session_url expect(current_url).to eq new_user_session_url visit new_user_registration_url expect(current_url).to eq new_user_session_url end it "I am redirected to the signup page if only the portus user exists" do User.delete_all create(:admin, username: "portus") visit new_user_session_url expect(current_url).to eq new_user_registration_url visit root_url expect(current_url).to eq new_user_registration_url expect(page).to have_css("section.first-user") end it "does not exist a link to login if there are no users" do expect(page).to have_content("Login") User.delete_all visit new_user_registration_url expect(page).not_to have_content("Login") end it "As a guest I can see error prohibiting my registration to be completed" do fill_in "user_username", with: user.username fill_in "user_email", with: "gibberish" fill_in "user_password", with: user.password fill_in "user_password_confirmation", with: user.password click_button("Create account") expect(page).to have_content("Email is invalid") expect(page).not_to have_content("Create admin") expect(current_url).to eq new_user_registration_url end it "Multiple errors are displayed in a list" do fill_in "user_username", with: user.username fill_in "user_email", with: "gibberish" fill_in "user_password", with: "12341234" fill_in "user_password_confirmation", with: "532" click_button("Create account") expect(page).to have_css("#fixed-alert ul") expect(page).to have_selector("#fixed-alert ul li", count: 2) expect(page).to have_selector("#fixed-alert ul li", text: "Email is invalid") expect(page).to have_selector("#fixed-alert ul li", text: "Password confirmation doesn't match Password") end it "If there are users on the system, and can move through sign_in and sign_up" do click_link("Login") expect(page).to have_current_path(new_user_session_path) click_link("Create a new account") expect(page).to have_current_path(new_user_registration_path) end describe "signup disabled" do before do APP_CONFIG["signup"] = { "enabled" => false } end it "does not allow the user to access the signup page if disabled" do visit new_user_registration_path expect(page).to have_current_path(new_user_session_path) end end end
35.493976
89
0.702817
e293ea7d7fdffa3ccfbba7fa22e84a99aea46aa6
723
require_relative "boot" require "csv" require "rails/all" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module InventoryApp class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 6.1 # Configuration for the application, engines, and railties goes here. # # These settings can be overridden in specific environments using the files # in config/environments, which are processed later. # # config.time_zone = "Central Time (US & Canada)" # config.eager_load_paths << Rails.root.join("extras") end end
30.125
79
0.738589
b910c14989b2a2813a53a219172ef096e71032b1
390
require 'spec_helper' describe Spree::Chimpy::SubscribersController do let(:spree_chimpy_subscriber) { create(:subscriber) } let(:valid_attributes) { attributes_for(:subscriber) } context '#create' do it 'raise error when empty hash found' do expect { post :create, params: { chimpy_subscriber: {} } }.to raise_error(ActionController::ParameterMissing) end end end
27.857143
115
0.730769
5da70cfa38040ab4a712bb1a12f0eff690991681
51
module SpreePagarmePayment VERSION = "0.0.1" end
12.75
26
0.745098
330b3db8096db80cb6aaf1fde121a7a1740a8969
31,379
# -*- encoding: utf-8 -*- # HTTPClient - HTTP client library. # Copyright (C) 2000-2015 NAKAMURA, Hiroshi <[email protected]>. # # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'time' if defined?(Encoding::ASCII_8BIT) require 'open-uri' # for encoding end require 'httpclient/util' # A namespace module for HTTP Message definitions used by HTTPClient. module HTTP # Represents HTTP response status code. Defines constants for HTTP response # and some conditional methods. module Status OK = 200 CREATED = 201 ACCEPTED = 202 NON_AUTHORITATIVE_INFORMATION = 203 NO_CONTENT = 204 RESET_CONTENT = 205 PARTIAL_CONTENT = 206 MOVED_PERMANENTLY = 301 FOUND = 302 SEE_OTHER = 303 TEMPORARY_REDIRECT = MOVED_TEMPORARILY = 307 BAD_REQUEST = 400 UNAUTHORIZED = 401 PROXY_AUTHENTICATE_REQUIRED = 407 INTERNAL = 500 # Status codes for successful HTTP response. SUCCESSFUL_STATUS = [ OK, CREATED, ACCEPTED, NON_AUTHORITATIVE_INFORMATION, NO_CONTENT, RESET_CONTENT, PARTIAL_CONTENT ] # Status codes which is a redirect. REDIRECT_STATUS = [ MOVED_PERMANENTLY, FOUND, SEE_OTHER, TEMPORARY_REDIRECT, MOVED_TEMPORARILY ] # Returns true if the given status represents successful HTTP response. # See also SUCCESSFUL_STATUS. def self.successful?(status) SUCCESSFUL_STATUS.include?(status) end # Returns true if the given status is thought to be redirect. # See also REDIRECT_STATUS. def self.redirect?(status) REDIRECT_STATUS.include?(status) end end # Represents a HTTP message. A message is for a request or a response. # # Request message is generated from given parameters internally so users # don't need to care about it. Response message is the instance that # methods of HTTPClient returns so users need to know how to extract # HTTP response data from Message. # # Some attributes are only for a request or a response, not both. # # == How to use HTTP response message # # 1. Gets response message body. # # res = clnt.get(url) # p res.content #=> String # # 2. Gets response status code. # # res = clnt.get(url) # p res.status #=> 200, 501, etc. (Integer) # # 3. Gets response header. # # res = clnt.get(url) # res.header['set-cookie'].each do |value| # p value # end # assert_equal(1, res.header['last-modified'].size) # p res.header['last-modified'].first # class Message include HTTPClient::Util CRLF = "\r\n" # Represents HTTP message header. class Headers # HTTP version in a HTTP header. String. attr_accessor :http_version # Size of body. nil when size is unknown (e.g. chunked response). attr_reader :body_size # Request/Response is chunked or not. attr_accessor :chunked # Request only. Requested method. attr_reader :request_method # Request only. Requested URI. attr_accessor :request_uri # Request only. Requested query. attr_accessor :request_query # Request only. Requested via proxy or not. attr_accessor :request_absolute_uri # Response only. HTTP status attr_reader :status_code # Response only. HTTP status reason phrase. attr_accessor :reason_phrase # Used for dumping response. attr_accessor :body_type # :nodoc: # Used for dumping response. attr_accessor :body_charset # :nodoc: # Used for dumping response. attr_accessor :body_date # :nodoc: # Used for keeping content encoding. attr_reader :body_encoding # :nodoc: # HTTP response status code to reason phrase mapping definition. STATUS_CODE_MAP = { Status::OK => 'OK', Status::CREATED => "Created", Status::NON_AUTHORITATIVE_INFORMATION => "Non-Authoritative Information", Status::NO_CONTENT => "No Content", Status::RESET_CONTENT => "Reset Content", Status::PARTIAL_CONTENT => "Partial Content", Status::MOVED_PERMANENTLY => 'Moved Permanently', Status::FOUND => 'Found', Status::SEE_OTHER => 'See Other', Status::TEMPORARY_REDIRECT => 'Temporary Redirect', Status::MOVED_TEMPORARILY => 'Temporary Redirect', Status::BAD_REQUEST => 'Bad Request', Status::INTERNAL => 'Internal Server Error', } # $KCODE to charset mapping definition. CHARSET_MAP = { 'NONE' => 'us-ascii', 'EUC' => 'euc-jp', 'SJIS' => 'shift_jis', 'UTF8' => 'utf-8', } # Creates a Message::Headers. Use init_request, init_response, or # init_connect_request for acutual initialize. def initialize @http_version = '1.1' @body_size = nil @chunked = false @request_method = nil @request_uri = nil @request_query = nil @request_absolute_uri = nil @status_code = nil @reason_phrase = nil @body_type = nil @body_charset = nil @body_date = nil @body_encoding = nil @is_request = nil @header_item = [] @dumped = false end # Initialize this instance as a CONNECT request. def init_connect_request(uri) @is_request = true @request_method = 'CONNECT' @request_uri = uri @request_query = nil @http_version = '1.0' end # Placeholder URI object for nil uri. NIL_URI = HTTPClient::Util.urify('http://nil-uri-given/') # Initialize this instance as a general request. def init_request(method, uri, query = nil) @is_request = true @request_method = method @request_uri = uri || NIL_URI @request_query = query @request_absolute_uri = false self end # Initialize this instance as a response. def init_response(status_code, req = nil) @is_request = false self.status_code = status_code if req @request_method = req.request_method @request_uri = req.request_uri @request_query = req.request_query end self end # Sets status code and reason phrase. def status_code=(status_code) @status_code = status_code @reason_phrase = STATUS_CODE_MAP[@status_code] end # Returns 'Content-Type' header value. def content_type self['Content-Type'][0] end # Sets 'Content-Type' header value. Overrides if already exists. def content_type=(content_type) delete('Content-Type') self['Content-Type'] = content_type end alias contenttype content_type alias contenttype= content_type= if defined?(Encoding::ASCII_8BIT) def set_body_encoding if type = self.content_type OpenURI::Meta.init(o = '') o.meta_add_field('content-type', type) @body_encoding = o.encoding end end else def set_body_encoding @body_encoding = nil end end # Sets byte size of message body. # body_size == nil means that the body is_a? IO def body_size=(body_size) @body_size = body_size end # Dumps message header part and returns a dumped String. def dump set_header str = nil if @is_request str = request_line else str = response_status_line end str + @header_item.collect { |key, value| "#{ key }: #{ value }#{ CRLF }" }.join end # Set Date header def set_date_header set('Date', Time.now.httpdate) end # Adds a header. Addition order is preserved. def add(key, value) if value.is_a?(Array) value.each do |v| @header_item.push([key, v]) end else @header_item.push([key, value]) end end # Sets a header. def set(key, value) delete(key) add(key, value) end # Returns an Array of headers for the given key. Each element is a pair # of key and value. It returns an single element Array even if the only # one header exists. If nil key given, it returns all headers. def get(key = nil) if key.nil? all else key = key.upcase @header_item.find_all { |k, v| k.upcase == key } end end # Returns an Array of all headers. def all @header_item end # Deletes headers of the given key. def delete(key) key = key.upcase @header_item.delete_if { |k, v| k.upcase == key } end # Adds a header. See set. def []=(key, value) set(key, value) end # Returns an Array of header values for the given key. def [](key) get(key).collect { |item| item[1] } end def set_headers(headers) headers.each do |key, value| add(key, value) end set_body_encoding end def create_query_uri() if @request_method == 'CONNECT' return "#{@request_uri.host}:#{@request_uri.port}" end path = @request_uri.path path = '/' if path.nil? or path.empty? if query_str = create_query_part() path += "?#{query_str}" end path end def create_query_part() query_str = nil if @request_uri.query query_str = @request_uri.query end if @request_query if query_str query_str += "&#{Message.create_query_part_str(@request_query)}" else query_str = Message.create_query_part_str(@request_query) end end query_str end private def request_line path = create_query_uri() if @request_absolute_uri path = "#{ @request_uri.scheme }://#{ @request_uri.host }:#{ @request_uri.port }#{ path }" end "#{ @request_method } #{ path } HTTP/#{ @http_version }#{ CRLF }" end def response_status_line if defined?(Apache) "HTTP/#{ @http_version } #{ @status_code } #{ @reason_phrase }#{ CRLF }" else "Status: #{ @status_code } #{ @reason_phrase }#{ CRLF }" end end def set_header if @is_request set_request_header else set_response_header end end def set_request_header return if @dumped @dumped = true keep_alive = Message.keep_alive_enabled?(@http_version) if !keep_alive and @request_method != 'CONNECT' set('Connection', 'close') end if @chunked set('Transfer-Encoding', 'chunked') elsif @body_size and (keep_alive or @body_size != 0) set('Content-Length', @body_size.to_s) end if @http_version >= '1.1' and get('Host').empty? if @request_uri.port == @request_uri.default_port # GFE/1.3 dislikes default port number (returns 404) set('Host', "#{@request_uri.hostname}") else set('Host', "#{@request_uri.hostname}:#{@request_uri.port}") end end end def set_response_header return if @dumped @dumped = true if defined?(Apache) && self['Date'].empty? set_date_header end keep_alive = Message.keep_alive_enabled?(@http_version) if @chunked set('Transfer-Encoding', 'chunked') else if keep_alive or @body_size != 0 set('Content-Length', @body_size.to_s) end end if @body_date set('Last-Modified', @body_date.httpdate) end if self['Content-Type'].empty? set('Content-Type', "#{ @body_type || 'text/html' }; charset=#{ charset_label }") end end def charset_label # TODO: should handle response encoding for 1.9 correctly. if RUBY_VERSION > "1.9" CHARSET_MAP[@body_charset] || 'us-ascii' else CHARSET_MAP[@body_charset || $KCODE] || 'us-ascii' end end end # Represents HTTP message body. class Body # Size of body. nil when size is unknown (e.g. chunked response). attr_reader :size # maxbytes of IO#read for streaming request. See DEFAULT_CHUNK_SIZE. attr_accessor :chunk_size # Hash that keeps IO positions attr_accessor :positions # Default value for chunk_size DEFAULT_CHUNK_SIZE = 1024 * 16 # Creates a Message::Body. Use init_request or init_response # for acutual initialize. def initialize @body = nil @size = nil @positions = nil @chunk_size = nil end # Initialize this instance as a request. def init_request(body = nil, boundary = nil) @boundary = boundary @positions = {} set_content(body, boundary) @chunk_size = DEFAULT_CHUNK_SIZE self end # Initialize this instance as a response. def init_response(body = nil) @body = body if @body.respond_to?(:bytesize) @size = @body.bytesize elsif @body.respond_to?(:size) @size = @body.size else @size = nil end self end # Dumps message body to given dev. # dev needs to respond to <<. # # Message header must be given as the first argument for performance # reason. (header is dumped to dev, too) # If no dev (the second argument) given, this method returns a dumped # String. # # assert: @size is not nil def dump(header = '', dev = '') if @body.is_a?(Parts) dev << header @body.parts.each do |part| if Message.file?(part) reset_pos(part) dump_file(part, dev, @body.sizes[part]) else dev << part end end elsif Message.file?(@body) dev << header reset_pos(@body) dump_file(@body, dev, @size) elsif @body dev << header + @body else dev << header end dev end # Dumps message body with chunked encoding to given dev. # dev needs to respond to <<. # # Message header must be given as the first argument for performance # reason. (header is dumped to dev, too) # If no dev (the second argument) given, this method returns a dumped # String. def dump_chunked(header = '', dev = '') dev << header if @body.is_a?(Parts) @body.parts.each do |part| if Message.file?(part) reset_pos(part) dump_chunks(part, dev) else dev << dump_chunk(part) end end dev << (dump_last_chunk + CRLF) elsif @body reset_pos(@body) dump_chunks(@body, dev) dev << (dump_last_chunk + CRLF) end dev end # Returns a message body itself. def content @body end private def set_content(body, boundary = nil) if Message.file?(body) # uses Transfer-Encoding: chunked if body does not respond to :size. # bear in mind that server may not support it. at least ruby's CGI doesn't. @body = body remember_pos(@body) @size = body.respond_to?(:size) ? body.size - body.pos : nil elsif boundary and Message.multiparam_query?(body) @body = build_query_multipart_str(body, boundary) @size = @body.size else @body = Message.create_query_part_str(body) @size = @body.bytesize end end def remember_pos(io) # IO may not support it (ex. IO.pipe) @positions[io] = io.pos if io.respond_to?(:pos) end def reset_pos(io) io.pos = @positions[io] if @positions.key?(io) end def dump_file(io, dev, sz) buf = '' rest = sz while rest > 0 n = io.read([rest, @chunk_size].min, buf) raise ArgumentError.new("Illegal size value: #size returns #{sz} but cannot read") if n.nil? dev << buf rest -= n.bytesize end end def dump_chunks(io, dev) buf = '' while !io.read(@chunk_size, buf).nil? dev << dump_chunk(buf) end end def dump_chunk(str) dump_chunk_size(str.bytesize) + (str + CRLF) end def dump_last_chunk dump_chunk_size(0) end def dump_chunk_size(size) sprintf("%x", size) + CRLF end class Parts attr_reader :size attr_reader :sizes def initialize @body = [] @sizes = {} @size = 0 # total @as_stream = false end def add(part) if Message.file?(part) @as_stream = true @body << part if part.respond_to?(:lstat) sz = part.lstat.size add_size(part, sz) elsif part.respond_to?(:size) if sz = part.size add_size(part, sz) else @sizes.clear @size = nil end else # use chunked upload @sizes.clear @size = nil end elsif @body[-1].is_a?(String) @body[-1] += part.to_s @size += part.to_s.bytesize if @size else @body << part.to_s @size += part.to_s.bytesize if @size end end def parts if @as_stream @body else [@body.join] end end private def add_size(part, sz) if @size @sizes[part] = sz @size += sz end end end def build_query_multipart_str(query, boundary) parts = Parts.new query.each do |attr, value| headers = ["--#{boundary}"] if Message.file?(value) remember_pos(value) param_str = params_from_file(value).collect { |k, v| "#{k}=\"#{v}\"" }.join("; ") if value.respond_to?(:mime_type) content_type = value.mime_type elsif value.respond_to?(:content_type) content_type = value.content_type else path = value.respond_to?(:path) ? value.path : nil content_type = Message.mime_type(path) end headers << %{Content-Disposition: form-data; name="#{attr}"; #{param_str}} headers << %{Content-Type: #{content_type}} elsif attr.is_a?(Hash) h = attr value = h[:content] h.each do |h_key, h_val| headers << %{#{h_key}: #{h_val}} if h_key != :content end remember_pos(value) if Message.file?(value) else headers << %{Content-Disposition: form-data; name="#{attr}"} value = value.to_s end parts.add(headers.join(CRLF) + CRLF + CRLF) parts.add(value) parts.add(CRLF) end parts.add("--#{boundary}--" + CRLF + CRLF) # empty epilogue parts end def params_from_file(value) params = {} original_filename = value.respond_to?(:original_filename) ? value.original_filename : nil path = value.respond_to?(:path) ? value.path : nil params['filename'] = original_filename || File.basename(path || '') # Creation time is not available from File::Stat if value.respond_to?(:mtime) params['modification-date'] = value.mtime.rfc822 end if value.respond_to?(:atime) params['read-date'] = value.atime.rfc822 end params end end class << self private :new # Creates a Message instance of 'CONNECT' request. # 'CONNECT' request does not have Body. # uri:: an URI that need to connect. Only uri.host and uri.port are used. def new_connect_request(uri) m = new m.http_header.init_connect_request(uri) m.http_header.body_size = nil m end # Creates a Message instance of general request. # method:: HTTP method String. # uri:: an URI object which represents an URL of web resource. # query:: a Hash or an Array of query part of URL. # e.g. { "a" => "b" } => 'http://host/part?a=b' # Give an array to pass multiple value like # [["a", "b"], ["a", "c"]] => 'http://host/part?a=b&a=c' # body:: a Hash or an Array of body part. # e.g. { "a" => "b" } => 'a=b'. # Give an array to pass multiple value like # [["a", "b"], ["a", "c"]] => 'a=b&a=c'. # boundary:: When the boundary given, it is sent as # a multipart/form-data using this boundary String. def new_request(method, uri, query = nil, body = nil, boundary = nil) m = new m.http_header.init_request(method, uri, query) m.http_body = Body.new m.http_body.init_request(body || '', boundary) if body m.http_header.body_size = m.http_body.size m.http_header.chunked = true if m.http_body.size.nil? else m.http_header.body_size = nil end m end # Creates a Message instance of response. # body:: a String or an IO of response message body. def new_response(body, req = nil) m = new m.http_header.init_response(Status::OK, req) m.http_body = Body.new m.http_body.init_response(body) m.http_header.body_size = m.http_body.size || 0 m end @@mime_type_handler = nil # Sets MIME type handler. # # handler must respond to :call with a single argument :path and returns # a MIME type String e.g. 'text/html'. # When the handler returns nil or an empty String, # 'application/octet-stream' is used. # # When you set nil to the handler, internal_mime_type is used instead. # The handler is nil by default. def mime_type_handler=(handler) @@mime_type_handler = handler end # Returns MIME type handler. def mime_type_handler @@mime_type_handler end # For backward compatibility. alias set_mime_type_func mime_type_handler= alias get_mime_type_func mime_type_handler def mime_type(path) # :nodoc: if @@mime_type_handler res = @@mime_type_handler.call(path) if !res || res.to_s == '' return 'application/octet-stream' else return res end else internal_mime_type(path) end end # Default MIME type handler. # See mime_type_handler=. def internal_mime_type(path) case path when /\.txt$/i 'text/plain' when /\.xml$/i 'text/xml' when /\.(htm|html)$/i 'text/html' when /\.doc$/i 'application/msword' when /\.png$/i 'image/png' when /\.gif$/i 'image/gif' when /\.(jpg|jpeg)$/i 'image/jpeg' else 'application/octet-stream' end end # Returns true if the given HTTP version allows keep alive connection. # version:: String def keep_alive_enabled?(version) version >= '1.1' end # Returns true if the given query (or body) has a multiple parameter. def multiparam_query?(query) query.is_a?(Array) or query.is_a?(Hash) end # Returns true if the given object is a File. In HTTPClient, a file is; # * must respond to :read for retrieving String chunks. # * must respond to :pos and :pos= to rewind for reading. # Rewinding is only needed for following HTTP redirect. Some IO impl # defines :pos= but raises an Exception for pos= such as StringIO # but there's no problem as far as using it for non-following methods # (get/post/etc.) def file?(obj) obj.respond_to?(:read) and obj.respond_to?(:pos) and obj.respond_to?(:pos=) end def create_query_part_str(query) # :nodoc: if multiparam_query?(query) escape_query(query) elsif query.respond_to?(:read) query = query.read else query.to_s end end def Array.try_convert(value) return value if value.instance_of?(Array) return nil if !value.respond_to?(:to_ary) converted = value.to_ary return converted if converted.instance_of?(Array) cname = value.class.name raise TypeError, "can't convert %s to %s (%s#%s gives %s)" % [cname, Array.name, cname, :to_ary, converted.class.name] end unless Array.respond_to?(:try_convert) def escape_query(query) # :nodoc: pairs = [] query.each { |attr, value| left = escape(attr.to_s) << '=' if values = Array.try_convert(value) values.each { |v| if v.respond_to?(:read) v = v.read end pairs.push(left + escape(v.to_s)) } else if value.respond_to?(:read) value = value.read end pairs.push(left << escape(value.to_s)) end } pairs.join('&') end # from CGI.escape if defined?(Encoding::ASCII_8BIT) def escape(str) # :nodoc: str.dup.force_encoding(Encoding::ASCII_8BIT).gsub(/([^ a-zA-Z0-9_.-]+)/) { '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase }.tr(' ', '+') end else def escape(str) # :nodoc: str.gsub(/([^ a-zA-Z0-9_.-]+)/n) { '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase }.tr(' ', '+') end end # from CGI.parse def parse(query) params = Hash.new([].freeze) query.split(/[&;]/n).each do |pairs| key, value = pairs.split('=',2).collect{|v| unescape(v) } if params.has_key?(key) params[key].push(value) else params[key] = [value] end end params end # from CGI.unescape def unescape(string) string.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n) do [$1.delete('%')].pack('H*') end end end # HTTP::Message::Headers:: message header. attr_accessor :http_header # HTTP::Message::Body:: message body. attr_reader :http_body # OpenSSL::X509::Certificate:: response only. server certificate which is # used for retrieving the response. attr_accessor :peer_cert # The other Message object when this Message is generated instead of # the Message because of redirection, negotiation, or format conversion. attr_accessor :previous # Creates a Message. This method should be used internally. # Use Message.new_connect_request, Message.new_request or # Message.new_response instead. def initialize # :nodoc: @http_header = Headers.new @http_body = @peer_cert = nil @previous = nil end # Dumps message (header and body) to given dev. # dev needs to respond to <<. def dump(dev = '') str = @http_header.dump + CRLF if @http_header.chunked dev = @http_body.dump_chunked(str, dev) elsif @http_body dev = @http_body.dump(str, dev) else dev << str end dev end # Sets a new body. header.body_size is updated with new body.size. def http_body=(body) @http_body = body @http_header.body_size = @http_body.size if @http_header end alias body= http_body= # Returns HTTP version in a HTTP header. String. def http_version @http_header.http_version end # Sets HTTP version in a HTTP header. String. def http_version=(http_version) @http_header.http_version = http_version end VERSION_WARNING = 'Message#version (Float) is deprecated. Use Message#http_version (String) instead.' def version warning(VERSION_WARNING) @http_header.http_version.to_f end def version=(version) warning(VERSION_WARNING) @http_header.http_version = version end # Returns HTTP status code in response. Integer. def status @http_header.status_code end alias code status alias status_code status # Sets HTTP status code of response. Integer. # Reason phrase is updated, too. def status=(status) @http_header.status_code = status end # Returns HTTP status reason phrase in response. String. def reason @http_header.reason_phrase end # Sets HTTP status reason phrase of response. String. def reason=(reason) @http_header.reason_phrase = reason end # Returns 'Content-Type' header value. def content_type @http_header.content_type end # Sets 'Content-Type' header value. Overrides if already exists. def content_type=(content_type) @http_header.content_type = content_type end alias contenttype content_type alias contenttype= content_type= # Returns content encoding def body_encoding @http_header.body_encoding end # Returns a content of message body. A String or an IO. def content @http_body.content end alias header http_header alias body content # Returns Hash of header. key and value are both String. Each key has a # single value so you can't extract exact value when a message has multiple # headers like 'Set-Cookie'. Use header['Set-Cookie'] for that purpose. # (It returns an Array always) def headers Hash[*http_header.all.flatten] end # Extracts cookies from 'Set-Cookie' header. # Supports 'Set-Cookie' in response header only. # Do we need 'Cookie' support in request header? def cookies set_cookies = http_header['set-cookie'] unless set_cookies.empty? uri = http_header.request_uri set_cookies.map { |str| WebAgent::Cookie.parse(str, uri) }.flatten end end # Convenience method to return boolean of whether we had a successful request def ok? HTTP::Status.successful?(status) end def redirect? HTTP::Status.redirect?(status) end # SEE_OTHER is a redirect, but it should sent as GET def see_other? status == HTTP::Status::SEE_OTHER end end end
28.974146
105
0.572899
1d5e400fee626e628b53f223d29c2130ce703210
687
cask 'cyberduck' do version '7.4.0.32960' sha256 'def0daced06d0f60e83bbb0862d71d7283c130bbc15d4e641d5769ff9de6d2e8' url "https://update.cyberduck.io/Cyberduck-#{version}.zip" appcast 'https://version.cyberduck.io/changelog.rss' name 'Cyberduck' homepage 'https://cyberduck.io/' auto_updates true app 'Cyberduck.app' zap trash: [ '~/Library/Application Support/Cyberduck', '~/Library/Caches/ch.sudo.cyberduck', '~/Library/Group Containers/G69SCX94XU.duck', '~/Library/Preferences/ch.sudo.cyberduck.plist', '~/Library/Saved Application State/ch.sudo.cyberduck.savedState', ] end
31.227273
80
0.660844
abf73bfa1352efaeaca7ea36b42fd05e9382ba6f
115
class AddTitleToBooks < ActiveRecord::Migration[5.2] def change add_column :books, :title, :string end end
19.166667
52
0.730435
281bee4a1c1b44b213b95c460962c4684e037b7d
634
Given(/^I have specs that describe a single subject$/) do spec_runner_helper.spec_classes = %w[info.javaspec.example.rb.TightropeSpecs] end Given(/^I have specs that describe 2 or more subjects$/) do spec_runner_helper.spec_classes = %w[info.javaspec.example.rb.AnvilSpecs info.javaspec.example.rb.TightropeSpecs] end Given(/^I have specs that describe context-specific behavior$/) do spec_runner_helper.spec_classes = %w[info.javaspec.example.rb.SpringOperatedBoxingGloveSpecs] end Given(/^I have specs where 1 or more of them fail$/) do spec_runner_helper.spec_classes = %w[info.javaspec.example.rb.CoyoteAnvilSpecs] end
39.625
115
0.793375
b982d796189a91aa1e16a28f390b684174759544
397
# apt-get install nginx package "nginx" # define as a service service "nginx" do supports :status => true, :restart => true, :reload => true action [:enable, :start] end template "/etc/nginx/nginx.conf" do # source "nginx.conf.erb" notifies :reload, "service[nginx]" end # This tells chef to not install a version which is newer than 1.0.3 # package "nginx" do # version "1.0.3" # end
19.85
68
0.685139
8774daf965d7bb322948e356896773af8de582eb
1,404
# frozen_string_literal: true # Base class for objects that take part in physics class Sprite attr_accessor :img, :zorder, :pos, :rot, :collider_radius, :velocity, :rot_velocity, :active def initialize(img, zorder) @img = img @zorder = zorder # Vector 2 position @pos = Vector[0.0, 0.0] # Rotation in radians @rot = 0.0 @collider_radius = [@img.width, @img.height].max / 2.0 @velocity = Vector[0.0, 0.0] @rot_velocity = 0.0 @active = true end def update(dt) @pos += @velocity * dt / 1000 @rot += @rot_velocity * dt / 1000 end def draw return unless @active @img.draw_rot( @pos[0], @pos[1], @zorder, @rot.radians_to_gosu ) end # Collision detection def collide?(other_sprite) # Relative distance x_dist = (other_sprite.pos[0] - @pos[0]).abs y_dist = (other_sprite.pos[1] - @pos[1]).abs # Min collision distance collide_dist = @collider_radius + other_sprite.collider_radius # Preliminary check if x, y distance is more than collide. # This is much efficient to run than below. return false if x_dist >= collide_dist || y_dist >= collide_dist # Here we compare by power of 2 because square root is expensive. square_dist = x_dist**2 + y_dist**2 square_collision_dist = collide_dist**2 square_dist < square_collision_dist end end
25.071429
71
0.643162
380a0148fffd0a2ec57eadc38bd76cfc4bb9a4ce
336
class CreateFlags < ActiveRecord::Migration[6.1] def change create_table :flags do |t| t.belongs_to :message, null: false, foreign_key: true t.string :reason, null: false t.string :resolve_token, null: false t.string :discord_webhook_id t.timestamp :resolved_at t.timestamps end end end
24
59
0.675595
1cb538a6cf68168abea5c3ed2f1971a37e565b67
13,942
RSpec.describe PostScraper do it "should add view to url" do scraper = PostScraper.new('http://wild-pegasus-appeared.dreamwidth.org/403.html') expect(scraper.url).to include('view=flat') end it "should not change url if view is present" do url = 'http://wild-pegasus-appeared.dreamwidth.org/403.html?view=flat' scraper = PostScraper.new(url) expect(scraper.url.sub('view=flat', '')).not_to include('view=flat') expect(scraper.url.gsub("&style=site", "").length).to eq(url.length) end it "should add site style to the url" do url = 'http://wild-pegasus-appeared.dreamwidth.org/403.html?view=flat' scraper = PostScraper.new(url) expect(scraper.url).to include('&style=site') end it "should not change url if site style is present" do url = 'http://wild-pegasus-appeared.dreamwidth.org/403.html?view=flat&style=site' scraper = PostScraper.new(url) expect(scraper.url.length).to eq(url.length) end it "should scrape properly when nothing is created" do url = 'http://wild-pegasus-appeared.dreamwidth.org/403.html?style=site&view=flat' stub_fixture(url, 'scrape_single_page') user = create(:user, username: "Marri") board = create(:board, creator: user) scraper = PostScraper.new(url, board.id) allow(scraper).to receive(:prompt_for_user) { user } allow(scraper).to receive(:set_from_icon).and_return(nil) expect(scraper.send(:logger)).to receive(:info).with("Importing thread 'linear b'") scraper.scrape! expect(Post.count).to eq(1) expect(Reply.count).to eq(46) expect(User.count).to eq(1) expect(Icon.count).to eq(0) expect(Character.count).to eq(2) expect(Character.where(screenname: 'wild_pegasus_appeared').first).not_to be_nil expect(Character.where(screenname: 'undercover_talent').first).not_to be_nil end it "should scrape multiple pages" do url = 'http://wild-pegasus-appeared.dreamwidth.org/403.html?style=site&view=flat' url_page_2 = 'http://wild-pegasus-appeared.dreamwidth.org/403.html?style=site&view=flat&page=2' stub_fixture(url, 'scrape_multi_page') stub_fixture(url_page_2, 'scrape_single_page') user = create(:user, username: "Marri") board = create(:board, creator: user) scraper = PostScraper.new(url, board.id) allow(scraper).to receive(:prompt_for_user) { user } allow(scraper).to receive(:set_from_icon).and_return(nil) expect(scraper.send(:logger)).to receive(:info).with("Importing thread 'linear b'") scraper.scrape! expect(Post.count).to eq(1) expect(Reply.count).to eq(92) expect(User.count).to eq(1) expect(Icon.count).to eq(0) expect(Character.count).to eq(2) expect(Character.where(screenname: 'wild_pegasus_appeared').first).not_to be_nil expect(Character.where(screenname: 'undercover_talent').first).not_to be_nil end it "should detect all threaded pages" do url = 'http://alicornutopia.dreamwidth.org/9596.html?thread=4077436&style=site#cmt4077436' stub_fixture(url, 'scrape_threaded') scraper = PostScraper.new(url, nil, nil, nil, true) scraper.instance_variable_set('@html_doc', scraper.send(:doc_from_url, url)) expect(scraper.send(:page_links).size).to eq(2) end it "should detect all threaded pages even if there's a single broken-depth comment" do url = 'https://alicornutopia.dreamwidth.org/22671.html?thread=14698127&style=site#cmt14698127' stub_fixture(url, 'scrape_threaded_broken_depth') scraper = PostScraper.new(url, nil, nil, nil, true) scraper.instance_variable_set('@html_doc', scraper.send(:doc_from_url, url)) expect(scraper.send(:page_links)).to eq([ 'https://alicornutopia.dreamwidth.org/22671.html?thread=14705039&style=site#cmt14705039', 'https://alicornutopia.dreamwidth.org/22671.html?thread=14711695&style=site#cmt14711695', ]) end it "should detect all threaded pages even if there's a broken-depth comment at the 25-per-page boundary" do url = 'https://alicornutopia.dreamwidth.org/22671.html?thread=14691983#cmt14691983' stub_fixture(url, 'scrape_threaded_broken_boundary_depth') scraper = PostScraper.new(url, nil, nil, nil, true) scraper.instance_variable_set('@html_doc', scraper.send(:doc_from_url, url)) expect(scraper.send(:page_links)).to eq([ 'https://alicornutopia.dreamwidth.org/22671.html?thread=14698383&style=site#cmt14698383', 'https://alicornutopia.dreamwidth.org/22671.html?thread=14698639&style=site#cmt14698639', 'https://alicornutopia.dreamwidth.org/22671.html?thread=14705551&style=site#cmt14705551', ]) end it "should raise an error when an unexpected character is found" do url = 'http://wild-pegasus-appeared.dreamwidth.org/403.html?style=site&view=flat' stub_fixture(url, 'scrape_no_replies') scraper = PostScraper.new(url) expect(scraper.send(:logger)).to receive(:info).with("Importing thread 'linear b'") expect { scraper.scrape! }.to raise_error(UnrecognizedUsernameError) end it "should raise an error when post is already imported" do board = create(:board) create(:character, screenname: 'wild_pegasus_appeared', user: board.creator) url = 'http://wild-pegasus-appeared.dreamwidth.org/403.html?style=site&view=flat' stub_fixture(url, 'scrape_no_replies') scraper = PostScraper.new(url, board.id) allow(scraper.send(:logger)).to receive(:info).with("Importing thread 'linear b'") expect { scraper.scrape! }.to change { Post.count }.by(1) expect { scraper.scrape! }.to raise_error(AlreadyImportedError) expect(Post.count).to eq(1) end it "should raise an error when post is already imported with given subject" do new_title = 'other name' board = create(:board) create(:post, board: board, subject: new_title) # post url = 'http://wild-pegasus-appeared.dreamwidth.org/403.html?style=site&view=flat' stub_fixture(url, 'scrape_no_replies') scraper = PostScraper.new(url, board.id, nil, nil, false, false, new_title) allow(scraper.send(:logger)).to receive(:info).with("Importing thread '#{new_title}'") expect { scraper.scrape! }.to raise_error(AlreadyImportedError) expect(Post.count).to eq(1) end it "should scrape character, user and icon properly" do url = 'http://wild-pegasus-appeared.dreamwidth.org/403.html?style=site&view=flat' stub_fixture(url, 'scrape_no_replies') user = create(:user, username: "Marri") board = create(:board, creator: user) scraper = PostScraper.new(url, board.id, nil, nil, false, true) allow(STDIN).to receive(:gets).and_return(user.username) expect(scraper.send(:logger)).to receive(:info).with("Importing thread 'linear b'") expect(scraper).to receive(:print).with("User ID or username for wild_pegasus_appeared? ") scraper.scrape! expect(Post.count).to eq(1) expect(Reply.count).to eq(0) expect(User.count).to eq(1) expect(Icon.count).to eq(1) expect(Character.count).to eq(1) expect(Character.where(screenname: 'wild_pegasus_appeared').first).not_to be_nil end it "should only scrape specified threads if given" do stubs = { 'https://mind-game.dreamwidth.org/1073.html?style=site' => 'scrape_specific_threads', 'https://mind-game.dreamwidth.org/1073.html?thread=6961&style=site#cmt6961' => 'scrape_specific_threads_thread1', 'https://mind-game.dreamwidth.org/1073.html?thread=16689&style=site#cmt16689' => 'scrape_specific_threads_thread2_1', 'https://mind-game.dreamwidth.org/1073.html?thread=48177&style=site#cmt48177' => 'scrape_specific_threads_thread2_2', } stubs.each { |url, file| stub_fixture(url, file) } urls = stubs.keys threads = urls[1..2] alicorn = create(:user, username: 'Alicorn') kappa = create(:user, username: 'Kappa') board = create(:board, creator: alicorn, writers: [kappa]) characters = [ { screenname: 'mind_game', name: 'Jane', user: alicorn }, { screenname: 'luminous_regnant', name: 'Isabella Marie Swan Cullen ☼ "Golden"', user: alicorn }, { screenname: 'manofmyword', name: 'here\'s my card', user: kappa }, { screenname: 'temporal_affairs', name: 'Nathan Corlett | Minister of Temporal Affairs', user: alicorn }, { screenname: 'pina_colada', name: 'Kerron Corlett', user: alicorn }, { screenname: 'pumpkin_pie', name: 'Aedyt Corlett', user: kappa }, { screenname: 'lifes_sake', name: 'Campbell Mark Swan ҂ "Cam"', user: alicorn }, { screenname: 'withmypowers', name: 'Matilda Wormwood Honey', user: kappa }, ] characters.each { |data| create(:character, data) } scraper = PostScraper.new(urls.first, board.id, nil, nil, true, false) expect(scraper.send(:logger)).to receive(:info).with("Importing thread 'repealing'") scraper.scrape_threads!(threads) expect(Post.count).to eq(1) expect(Post.first.subject).to eq('repealing') expect(Post.first.authors_locked).to eq(true) expect(Reply.count).to eq(55) expect(User.count).to eq(2) expect(Icon.count).to eq(30) expect(Character.count).to eq(8) end it "doesn't recreate characters and icons if they exist" do url = 'http://wild-pegasus-appeared.dreamwidth.org/403.html?style=site&view=flat' stub_fixture(url, 'scrape_no_replies') user = create(:user, username: "Marri") board = create(:board, creator: user) nita = create(:character, user: user, screenname: 'wild_pegasus_appeared', name: 'Juanita') icon = create(:icon, keyword: 'sad', url: 'http://v.dreamwidth.org/8517100/2343677', user: user) gallery = create(:gallery, user: user) gallery.icons << icon nita.galleries << gallery expect(User.count).to eq(1) expect(Icon.count).to eq(1) expect(Character.count).to eq(1) scraper = PostScraper.new(url, board.id) expect(scraper).not_to receive(:print).with("User ID or username for wild_pegasus_appeared? ") expect(scraper.send(:logger)).to receive(:info).with("Importing thread 'linear b'") # just to quiet it scraper.scrape! expect(User.count).to eq(1) expect(Icon.count).to eq(1) expect(Character.count).to eq(1) end it "doesn't recreate icons if they already exist for that character with new urls" do url = 'http://wild-pegasus-appeared.dreamwidth.org/403.html?style=site&view=flat' stub_fixture(url, 'scrape_no_replies') user = create(:user, username: "Marri") board = create(:board, creator: user) nita = create(:character, user: user, screenname: 'wild_pegasus_appeared', name: 'Juanita') icon = create(:icon, keyword: 'sad', url: 'http://glowfic.com/uploaded/icon.png', user: user) gallery = create(:gallery, user: user) gallery.icons << icon nita.galleries << gallery expect(User.count).to eq(1) expect(Icon.count).to eq(1) expect(Character.count).to eq(1) scraper = PostScraper.new(url, board.id) expect(scraper).not_to receive(:print).with("User ID or username for wild_pegasus_appeared? ") expect(scraper.send(:logger)).to receive(:info).with("Importing thread 'linear b'") # just to quiet it scraper.scrape! expect(User.count).to eq(1) expect(Icon.count).to eq(1) expect(Character.count).to eq(1) end it "handles Kappa icons" do kappa = create(:user, id: 3) char = create(:character, user: kappa) gallery = create(:gallery, user: kappa) char.galleries << gallery icon = create(:icon, user: kappa, keyword: '⑮ mountains') gallery.icons << icon tag = build(:reply, user: kappa, character: char) expect(tag.icon_id).to be_nil scraper = PostScraper.new('') scraper.send(:set_from_icon, tag, 'http://irrelevanturl.com', 'f.1 mountains') expect(Icon.count).to eq(1) expect(tag.icon_id).to eq(icon.id) end it "handles icons with descriptions" do user = create(:user) char = create(:character, user: user) gallery = create(:gallery, user: user) char.galleries << gallery icon = create(:icon, user: user, keyword: 'keyword blah') gallery.icons << icon tag = build(:reply, user: user, character: char) expect(tag.icon_id).to be_nil scraper = PostScraper.new('') scraper.send(:set_from_icon, tag, 'http://irrelevanturl.com', 'keyword blah (Accessbility description.)') expect(Icon.count).to eq(1) expect(tag.icon_id).to eq(icon.id) end it "handles kappa icons with descriptions" do kappa = create(:user, id: 3) char = create(:character, user: kappa) gallery = create(:gallery, user: kappa) char.galleries << gallery icon = create(:icon, user: kappa, keyword: '⑮ keyword blah') gallery.icons << icon tag = build(:reply, user: kappa, character: char) expect(tag.icon_id).to be_nil scraper = PostScraper.new('') scraper.send(:set_from_icon, tag, 'http://irrelevanturl.com', 'f.1 keyword blah (Accessbility description.)') expect(Icon.count).to eq(1) expect(tag.icon_id).to eq(icon.id) end it "can fail a download" do url = 'http://wild-pegasus-appeared.dreamwidth.org/403.html?style=site&view=flat' scraper = PostScraper.new(url) expect(HTTParty).to receive(:get).with(url).exactly(3).times.and_raise(Net::OpenTimeout, 'example failure') expect { scraper.send(:doc_from_url, url) }.to raise_error(Net::OpenTimeout, 'example failure') end it "handles retrying of downloads" do url = 'http://wild-pegasus-appeared.dreamwidth.org/403.html?style=site&view=flat' scraper = PostScraper.new(url) html = "<!DOCTYPE html>\n<html></html>\n" stub_with_body = double expect(stub_with_body).to receive(:body).and_return(html) allow(HTTParty).to receive(:get).with(url).once.and_raise(Net::OpenTimeout, 'example failure') allow(HTTParty).to receive(:get).with(url).and_return(stub_with_body) expect(scraper.send(:doc_from_url, url).to_s).to eq(html) end end
44.120253
123
0.697246
ed77ed6a0e96b4d4b0851b7a27e60332fbf7008a
1,317
module Elpresidente module Skills # Main skill that tries to find skill to execute class Start < Base ERROR_RESPONSES = [ 'Ojć', 'Nosz kurdefele', 'Co się janie pawle odpernicza', 'No i ch*j, no i cześć', 'fuuuuuuuuuuuuck', 'I co panie zrobisz, nic panie nie zrobisz...', 'Jaaaaaaaa', 'Shittt', 'Na odyna!', 'Zdaża się najlepszym', 'Coś zjebałeś', 'Na posejdona dobrze że nie jest to js' ].freeze def execute sequence [ Orwell, Badges::AwardAMedal, Badges::Show, Reactions::Apply, Reactions::Manage, Admin::Start, Meme::ShowTvp, Meme::Suchar, Gentlemen::Help, Gentlemen::Time, Gentlemen::Offend, Gentlemen::AskWhatYouWant ] rescue => e Async.logger.error "[#{e.class}] #{e} Failed to process #{data}" Async.logger.error e.backtrace.join("\n") react!('boom') reply = ERROR_RESPONSES.sample reply!(reply) do |block| block.section do |section| section.mrkdwn(text: "*#{reply}:*\n```#{e.class} #{e}```\n```#{e.backtrace.join("\n")}```") end end end end end end
26.34
103
0.515566
f7e2ec5c3cbe8c000f83b3918c67257559bed72a
1,904
require 'google/apis/cloudtrace_v1' module Cloudtracer class TraceContext < Base MIDDLEWARE_SPAN = 'Cloudtracer::Middleware'.freeze attr_accessor :traces attr_reader :parent_span_id attr_accessor :span_id, :trace_id attr_accessor :trace def initialize(ctx) parse_header(ctx) @span_id = parent_span_id + 1 @trace = Google::Apis::CloudtraceV1::Trace.new( trace_id: trace_id, project_id: config.project_id, spans: [] ) @traces = Google::Apis::CloudtraceV1::Traces.new(traces: [trace]) end def with_trace(&_block) t1 = Time.now Cloudtracer.with_context(self) do begin yield if block_given? ensure t2 = Time.now span = Google::Apis::CloudtraceV1::TraceSpan.new( name: MIDDLEWARE_SPAN, span_id: next_span_id, parent_span_id: parent_span_id, start_time: t1, end_time: t2, labels: {} ) trace.spans << span logger.info("Trace completed, pushing to queue: #{trace_id} with #{trace.spans.length} spans") trace_queue.push(traces) end end end def update(span) span.parent_span_id = parent_span_id span.span_id = next_span_id trace.spans << span end private def parse_header(ctx) m = %r{(\w+)/(\d+);*(.*)}.match(ctx) raise Error, "Invalid Trace Context: #{ctx}" unless m @trace_id = m[1] @parent_span_id = Integer(m[2]) @trace_options = m.length > 2 ? m[3] : '' end def trace_queue self.class.trace_queue end def next_span_id self.span_id += 1 end class << self def trace_queue @trace_queue ||= Cloudtracer.config.queue_adapter ? Cloudtracer.config.queue_adapter.new : TraceQueue.new end end end end
23.506173
113
0.597164
211ea4a594bf2d4a2b3d6604609fbd869f21ad76
2,433
# frozen_string_literal: true module Stupidedi include Refinements module Builder class LoopState < AbstractState # @return [Reader::Separators] attr_reader :separators # @return [Reader::SegmentDict] attr_reader :segment_dict # @return [InstructionTable] attr_reader :instructions # @return [Zipper::AbstractCursor] attr_reader :zipper # @return [Array<AbstractState>] attr_reader :children def initialize(separators, segment_dict, instructions, zipper, children) @separators, @segment_dict, @instructions, @zipper, @children = separators, segment_dict, instructions, zipper, children end # @return [LoopState] def copy(changes = {}) LoopState.new \ changes.fetch(:separators, @separators), changes.fetch(:segment_dict, @segment_dict), changes.fetch(:instructions, @instructions), changes.fetch(:zipper, @zipper), changes.fetch(:children, @children) end end class << LoopState # @group Constructors ######################################################################### # @return [Zipper::AbstractCursor] def push(zipper, parent, segment_tok, segment_use, config) loop_def = segment_use.parent loop_val = loop_def.empty segment_val = mksegment(segment_tok, segment_use) zipper.append_child new( parent.separators, parent.segment_dict, parent.instructions.push(instructions(loop_def)), parent.zipper.append(loop_val).append_child(segment_val), []) end # @endgroup ######################################################################### private # @return [Array<Instruction>] def instructions(loop_def) @__instructions ||= Hash.new @__instructions[loop_def] ||= begin # puts "LoopDef.instructions(#{loop_def.object_id})" # @todo: Explain this optimization is = if loop_def.header_segment_uses.head.repeatable? sequence(loop_def.header_segment_uses) else sequence(loop_def.header_segment_uses.tail) end is.concat(lsequence(loop_def.loop_defs, is.length)) is.concat(sequence(loop_def.trailer_segment_uses, is.length)) end end end end end
28.964286
79
0.588574
03335c9826fbf58ecf7aa54867afc88f7813c854
341
# frozen_string_literal: true module Ibrain # frozen_string_literal: true module Auth VERSION = '0.2.2' def self.ibrain_auth_version VERSION end def self.previous_ibrain_auth_minor_version '0.2.1' end def self.ibrain_auth_gem_version Gem::Version.new(ibrain_auth_version) end end end
15.5
47
0.692082
79e6e4f0897da9a2a05f71cb1848be4eb47509e8
2,094
# frozen_string_literal: true module Grumlin class Steps CONFIGURATION_STEPS = Action::CONFIGURATION_STEPS ALL_STEPS = Action::ALL_STEPS def self.from(action) raise ArgumentError, "expected: #{Action}, given: #{action.class}" unless action.is_a?(Action) shortcuts = action.shortcuts actions = [] until action.nil? actions.unshift(action) action = action.previous_step end new(shortcuts).tap do |chain| actions.each do |act| chain.add(act.name, args: act.args, params: act.params) end end end attr_reader :configuration_steps, :steps, :shortcuts def initialize(shortcuts, configuration_steps: [], steps: []) @shortcuts = shortcuts @configuration_steps = configuration_steps @steps = steps end def add(name, args: [], params: {}) return add_configuration_step(name, args: args, params: params) if CONFIGURATION_STEPS.include?(name) StepData.new(name, args: cast_arguments(args), params: params).tap do |step| @steps << step end end def uses_shortcuts? shortcuts?(@configuration_steps) || shortcuts?(@steps) end def ==(other) self.class == other.class && @shortcuts == other.shortcuts && @configuration_steps == other.configuration_steps && @steps == other.steps end # TODO: add #bytecode, to_s, inspect private def shortcuts?(steps_ary) steps_ary.any? do |step| @shortcuts.include?(step.name) || step.args.any? do |arg| arg.is_a?(Steps) ? arg.uses_shortcuts? : false end end end def add_configuration_step(name, args: [], params: {}) raise ArgumentError, "cannot use configuration steps after start step was used" unless @steps.empty? StepData.new(name, args: cast_arguments(args), params: params).tap do |step| @configuration_steps << step end end def cast_arguments(arguments) arguments.map { |arg| arg.is_a?(Action) ? Steps.from(arg) : arg } end end end
26.846154
107
0.637058
7a4cc2fa1526fe730cbf806a5321626e4c184683
109
require '..\..\..\..\..\ext\packages\ext-theme-base\sass\utils.rb' require '..\..\..\..\..\sass\config.rb'
36.333333
67
0.550459
6178c4fec3a2b5d68319ef558b39cdac89be8640
6,737
# encoding: utf-8 require File.expand_path("../../../test_helper", __FILE__) require 'yaml' #ArcServer::SOAP::MapServer.logger = $stdout class ArcServer::SOAP::MapServerTest < Test::Unit::TestCase should "be able to use map services at two different locations" do service1 = ArcServer::SOAP::MapServer.new('http://sampleserver1.arcgisonline.com/ArcGIS/services/Portland/ESRI_LandBase_WebMercator/MapServer') service2 = ArcServer::SOAP::MapServer.new('http://sampleserver1.arcgisonline.com/ArcGIS/services/Demographics/ESRI_Census_USA/MapServer') name1 = service1.get_default_map_name name2 = service2.get_default_map_name assert_equal "Portland", name1 assert_equal "Layers", name2 end context "using ESRI's sample Portland Landbase service" do setup do @service = ArcServer::SOAP::MapServer.new('http://sampleserver1.arcgisonline.com/ArcGIS/services/Portland/ESRI_LandBase_WebMercator/MapServer') end should "get the default map name" do assert_equal "Portland", @service.get_default_map_name end should "get the legend info (returning image data)" do legend_info = @service.get_legend_info(:map_name => 'Portland') legend_info.each do |item| layer_assertion = "assert_legend_info_result_layer_#{item[:layer_id]}".to_sym if respond_to?(layer_assertion) send(layer_assertion, item, :image_data) else raise "no assertions set for legend info with layer_id=#{item[:layer_id]}" end end end should "get the legend info (returning image urls)" do legend_info = @service.get_legend_info(:map_name => 'Portland', :image_return_url => true) legend_info.each do |item| layer_assertion = "assert_legend_info_result_layer_#{item[:layer_id]}".to_sym if respond_to?(layer_assertion) send(layer_assertion, item, :image_url) else raise "no assertions set for legend info with layer_id=#{item[:layer_id]}" end end end should "use the default map name when getting the legend info" do legend_info = @service.get_legend_info legend_info.each do |item| layer_assertion = "assert_legend_info_result_layer_#{item[:layer_id]}".to_sym if respond_to?(layer_assertion) send(layer_assertion, item) else raise "no assertions set for legend info with layer_id=#{item[:layer_id]}" end end end end # legend info assertion helpers def assert_legend_info_result_layer_1(item, image_return_type = :image_data) expected = { :layer_id => 1, :name => 'Zoomed in', :legend_groups => [{ :legend_classes => [{ :symbol_image => { :image_return_type => image_return_type } }] }] } assert_legend_info_result_layer(expected, item) end def assert_legend_info_result_layer_2(item, image_return_type = :image_data) expected = { :layer_id => 2, :name => 'Zoomed out', :legend_groups => [{ :legend_classes => [{ :symbol_image => { :image_return_type => image_return_type } }] }] } assert_legend_info_result_layer(expected, item) end def assert_legend_info_result_layer_3(item, image_return_type = :image_data) expected = { :layer_id => 3, :name => 'Buildings', :legend_groups => [{ :legend_classes => [{ :symbol_image => { :image_return_type => image_return_type } }] }] } assert_legend_info_result_layer(expected, item) end def assert_legend_info_result_layer_4(item, image_return_type = :image_data) expected = { :layer_id => 4, :name => 'Zoning', :legend_groups => [{ :legend_classes => [{ :label => 'Commercial', :symbol_image => { :image_return_type => image_return_type } }, { :label => 'Industrial', :symbol_image => { :image_return_type => image_return_type } }, { :label => 'Residential', :symbol_image => { :image_return_type => image_return_type } }, { :label => 'Mixed use', :symbol_image => { :image_return_type => image_return_type } }, { :label => 'Parks and open space', :symbol_image => { :image_return_type => image_return_type } }, { :label => 'Rural', :symbol_image => { :image_return_type => image_return_type } }] }] } assert_legend_info_result_layer(expected, item) end def assert_legend_info_result_layer(expected, actual) assert_equal expected[:layer_id], actual[:layer_id] assert_equal expected[:name], actual[:name] # check the legend groups assert_equal expected[:legend_groups].length, actual[:legend_groups].length actual[:legend_groups].each do |legend_group| assert_legend_group expected[:legend_groups].shift, legend_group end end def assert_legend_group(expected, actual) assert_equal expected[:heading], actual[:heading] # check the legend classes assert_equal expected[:legend_classes].length, actual[:legend_classes].length actual[:legend_classes].each do |legend_class| assert_legend_class expected[:legend_classes].shift, legend_class end end def assert_legend_class(expected, actual) assert_equal expected[:label], actual[:label] assert_equal expected[:description], actual[:description] assert_symbol_image(expected[:symbol_image] || {}, actual[:symbol_image]) assert_transparent_color(expected[:transparent_color] || {}, actual[:transparent_color]) end def assert_symbol_image(expected, actual) assert_not_nil actual[expected[:image_return_type]] assert_equal expected[:image_height] || 16, actual[:image_height] assert_equal expected[:image_width] || 20, actual[:image_width] assert_equal expected[:image_dpi] || 96, actual[:image_dpi] end def assert_transparent_color(expected, actual) assert_equal expected[:use_windows_dithering] || true, actual[:use_windows_dithering] assert_equal expected[:alpha_value] || 255, actual[:alpha_value] assert_equal expected[:red] || 254, actual[:red] assert_equal expected[:green] || 255, actual[:green] assert_equal expected[:blue] || 255, actual[:blue] end end
34.726804
149
0.635149
bfccc2e60278a5f2ab5ef85b10c33f12c7ab8092
682
Rails.application.routes.draw do devise_for :users root to: 'pages#home' get 'about', to: 'pages#about' get 'terms', to: 'pages#terms' get 'privacy', to: 'pages#privacy' resources :contacts, only: :create resources :podcasts resources :books do resources :chapters end resources :chapters do resources :questions end resources :questions do resources :comments, module: :questions end resources :users do resource :profile resources :comments end get 'contact-us', to: 'contacts#new', as: 'new_contact' get 'podcast', to: 'pages#podcast' resources :essays do resources :comments, module: :essays, shallow: true end end
23.517241
57
0.693548
1a10077277298148271a2b747b2ca9b26f7e2bbd
1,009
module JSONAPIonify::Api module Resource::Definitions::Hooks def self.extended(klass) klass.class_eval do define_callbacks( :request, :exception, :response, :list, :commit_list, :create, :commit_create, :read, :commit_read, :update, :commit_update, :delete, :commit_delete, :show, :commit_show, :add, :commit_add, :remove, :commit_remove, :replace, :commit_replace ) class << klass alias_method :on_exception, :before_exception remove_method :before_exception remove_method :after_exception end end end %i{before after}.each do |cb| define_method(cb) do |*action_names, &block| return send(:"#{cb}_request", &block) if action_names.blank? action_names.each do |action_name| send("#{cb}_#{action_name}", &block) end end end end end
27.27027
68
0.558969
ed5e2d09740ee9529755eb7bf0e96022e27141ca
290
module ApplicationHelper def update_user_attribution object, create, update = false, delete = false, user = nil user = user || current_user object.created_by = user if create object.updated_by = (update or delete) ? user : nil object.deleted_by = user if delete end end
32.222222
88
0.72069
083875b736714435b938aaa9e76aeca4cc73aa4f
162
class Departament < ApplicationRecord has_many :tickets, dependent: :delete_all validates :name, presence: true has_many :users, dependent: :delete_all end
27
43
0.783951
28bcc778bc7736fc8fcb2fac3def5ccf7e4b199b
2,929
# # Cookbook Name:: openstack_model_t # Recipe:: neutron # # Copyright (c) 2015 The Authors, All Rights Reserved. bash "create the neutron database" do user "root" cwd "/root" creates "/root/model-t-setup/neutron-dbcreated" code <<-EOH STATUS=0 mysql -u root -p#{node[:openstack_model_t][:mariadb_pass]} -e "create database neutron;" mysql -u root -p#{node[:openstack_model_t][:mariadb_pass]} -e "GRANT ALL PRIVILEGES ON neutron.* TO 'neutron'@'localhost' IDENTIFIED BY '#{node[:openstack_model_t]['NEUTRON_DBPASS']}';" || STATUS=1 mysql -u root -p#{node[:openstack_model_t][:mariadb_pass]} -e "GRANT ALL PRIVILEGES ON neutron.* TO 'neutron'@'%' IDENTIFIED BY '#{node[:openstack_model_t][:NEUTRON_DBPASS]}';" || STATUS=1 touch /root/model-t-setup/neutron-dbcreated exit $STATUS EOH end bash "create neutron user" do user "root" cwd "/root" creates "/root/model-t-setup/created-neutron-user" code <<-EOH STATUS=0 source passwords2dostuff || STATUS=1 openstack user create --password #{node[:openstack_model_t][:NEUTRON_PASS]} neutron || STATUS=1 openstack role add --project service --user neutron admin || STATUS=1 touch /root/model-t-setup/created-neutron-user || STATUS=1 exit $STATUS EOH end bash "create neutron service and api endpoint" do user "root" cwd "/root" creates "/root/model-t-setup/created-neutron-service-and-api" code <<-EOH STATUS=0 source passwords2dostuff || STATUS=1 openstack service create --name neutron --description "OpenStack Networking service" network openstack endpoint create --publicurl http://#{node[:openstack_model_t][:controller_ip]}:9696 --internalurl http://#{node[:openstack_model_t][:controller_ip]}:9696 --adminurl http://#{node[:openstack_model_t][:controller_ip]}:9696 --region RegionOne network touch /root/model-t-setup/created-neutron-service-and-api exit $STATUS EOH end %w{neutron-server neutron-plugin-ml2 python-neutronclient}.each do |pkg| package pkg do action [:install] end end template "/etc/neutron/neutron.conf" do source "neutron-controller.conf.erb" owner "neutron" group "neutron" mode "0644" end template "/etc/neutron/plugins/ml2/ml2_conf.ini" do source "ml2_conf-controller-node.ini.erb" owner "neutron" group "neutron" mode "0644" end bash "run neutron-mange db sync" do user "root" cwd "/tmp" creates "/root/model-t-setup/created-neutron-dbs" notifies :restart, 'service[nova-api]', :immediately notifies :restart, 'service[neutron-server]', :immediately code <<-EOH STATUS=0 /bin/sh -c "neutron-db-manage --config-file /etc/neutron/neutron.conf --config-file /etc/neutron/plugins/ml2/ml2_conf.ini upgrade head" neutron || STATUS=1 touch /root/model-t-setup/created-neutron-dbs exit $STATUS EOH end service 'neutron-server' do supports :restart => true, :reload => true action :enable end
33.666667
261
0.712188
1c63d35db2b725984c5d5104539c25c65ee22c57
1,080
# frozen_string_literal: true RSpec.describe Crunchbase::Models::CategoryGroup do context 'category_group' do it 'returns category_group as endpoint' do expect(described_class::RESOURCE_LIST).to eq('category_groups') end it 'returns all fields' do category_group = described_class.new expect(category_group.field_ids.size).to eq(8) expect(category_group.field_ids).to eq( %w[ categories created_at entity_def_id identifier rank updated_at uuid name ] ) end it 'returns basis fields' do category_group = described_class.new expect(category_group.basis_fields.size).to eq(2) expect(category_group.basis_fields).to eq( %w[ uuid name ] ) end it 'returns full cards' do category_group = described_class.new expect(category_group.full_cards.size).to eq(0) expect(category_group.full_cards).to eq( %w[ ] ) end end end
21.6
69
0.60463
914c7cc79d7756c0b75a3e44f7a9699567a52546
8,205
#!/usr/bin/env ruby # Copyright 2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # interop_server is a Testing app that runs a gRPC interop testing server. # # It helps validate interoperation b/w gRPC in different environments # # Helps validate interoperation b/w different gRPC implementations. # # Usage: $ path/to/interop_server.rb --port this_dir = File.expand_path(File.dirname(__FILE__)) lib_dir = File.join(File.dirname(File.dirname(this_dir)), 'lib') pb_dir = File.dirname(this_dir) $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir) $LOAD_PATH.unshift(pb_dir) unless $LOAD_PATH.include?(pb_dir) $LOAD_PATH.unshift(this_dir) unless $LOAD_PATH.include?(this_dir) require 'forwardable' require 'logger' require 'optparse' require 'grpc' require 'test/proto/empty' require 'test/proto/messages' require 'test/proto/test_services' # DebugIsTruncated extends the default Logger to truncate debug messages class DebugIsTruncated < Logger def debug(s) super(truncate(s, 1024)) end # Truncates a given +text+ after a given <tt>length</tt> if +text+ is longer than <tt>length</tt>: # # 'Once upon a time in a world far far away'.truncate(27) # # => "Once upon a time in a wo..." # # Pass a string or regexp <tt>:separator</tt> to truncate +text+ at a natural break: # # 'Once upon a time in a world far far away'.truncate(27, separator: ' ') # # => "Once upon a time in a..." # # 'Once upon a time in a world far far away'.truncate(27, separator: /\s/) # # => "Once upon a time in a..." # # The last characters will be replaced with the <tt>:omission</tt> string (defaults to "...") # for a total length not exceeding <tt>length</tt>: # # 'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)') # # => "And they f... (continued)" def truncate(s, truncate_at, options = {}) return s unless s.length > truncate_at omission = options[:omission] || '...' with_extra_room = truncate_at - omission.length stop = \ if options[:separator] rindex(options[:separator], with_extra_room) || with_extra_room else with_extra_room end "#{s[0, stop]}#{omission}" end end # RubyLogger defines a logger for gRPC based on the standard ruby logger. module RubyLogger def logger LOGGER end LOGGER = DebugIsTruncated.new(STDOUT) LOGGER.level = Logger::WARN end # GRPC is the general RPC module module GRPC # Inject the noop #logger if no module-level logger method has been injected. extend RubyLogger end # loads the certificates by the test server. def load_test_certs this_dir = File.expand_path(File.dirname(__FILE__)) data_dir = File.join(File.dirname(File.dirname(this_dir)), 'spec/testdata') files = ['ca.pem', 'server1.key', 'server1.pem'] files.map { |f| File.open(File.join(data_dir, f)).read } end # creates a ServerCredentials from the test certificates. def test_server_creds certs = load_test_certs GRPC::Core::ServerCredentials.new( nil, [{private_key: certs[1], cert_chain: certs[2]}], false) end # produces a string of null chars (\0) of length l. def nulls(l) fail 'requires #{l} to be +ve' if l < 0 [].pack('x' * l).force_encoding('ascii-8bit') end # A EnumeratorQueue wraps a Queue yielding the items added to it via each_item. class EnumeratorQueue extend Forwardable def_delegators :@q, :push def initialize(sentinel) @q = Queue.new @sentinel = sentinel end def each_item return enum_for(:each_item) unless block_given? loop do r = @q.pop break if r.equal?(@sentinel) fail r if r.is_a? Exception yield r end end end # A runnable implementation of the schema-specified testing service, with each # service method implemented as required by the interop testing spec. class TestTarget < Grpc::Testing::TestService::Service include Grpc::Testing include Grpc::Testing::PayloadType def empty_call(_empty, _call) Empty.new end def unary_call(simple_req, _call) req_size = simple_req.response_size SimpleResponse.new(payload: Payload.new(type: :COMPRESSABLE, body: nulls(req_size))) end def streaming_input_call(call) sizes = call.each_remote_read.map { |x| x.payload.body.length } sum = sizes.inject(0) { |s, x| s + x } StreamingInputCallResponse.new(aggregated_payload_size: sum) end def streaming_output_call(req, _call) cls = StreamingOutputCallResponse req.response_parameters.map do |p| cls.new(payload: Payload.new(type: req.response_type, body: nulls(p.size))) end end def full_duplex_call(reqs) # reqs is a lazy Enumerator of the requests sent by the client. q = EnumeratorQueue.new(self) cls = StreamingOutputCallResponse Thread.new do begin GRPC.logger.info('interop-server: started receiving') reqs.each do |req| resp_size = req.response_parameters[0].size GRPC.logger.info("read a req, response size is #{resp_size}") resp = cls.new(payload: Payload.new(type: req.response_type, body: nulls(resp_size))) q.push(resp) end GRPC.logger.info('interop-server: finished receiving') q.push(self) rescue StandardError => e GRPC.logger.info('interop-server: failed') GRPC.logger.warn(e) q.push(e) # share the exception with the enumerator end end q.each_item end def half_duplex_call(reqs) # TODO: update with unique behaviour of the half_duplex_call if that's # ever required by any of the tests. full_duplex_call(reqs) end end # validates the the command line options, returning them as a Hash. def parse_options options = { 'port' => nil, 'secure' => false } OptionParser.new do |opts| opts.banner = 'Usage: --port port' opts.on('--port PORT', 'server port') do |v| options['port'] = v end opts.on('--use_tls USE_TLS', ['false', 'true'], 'require a secure connection?') do |v| options['secure'] = v == 'true' end end.parse! if options['port'].nil? fail(OptionParser::MissingArgument, 'please specify --port') end options end def main opts = parse_options host = "0.0.0.0:#{opts['port']}" s = GRPC::RpcServer.new if opts['secure'] s.add_http2_port(host, test_server_creds) GRPC.logger.info("... running securely on #{host}") else s.add_http2_port(host, :this_port_is_insecure) GRPC.logger.info("... running insecurely on #{host}") end s.handle(TestTarget) s.run_till_terminated end main
32.30315
103
0.692626
f83d51cbb2d5667e82f4d60763386319105e04d8
171
module Box module Version MAJOR = 0 MINOR = 1 PATCH = 1 def self.to_s [MAJOR, MINOR, PATCH].join('.') end end VERSION = Version.to_s end
12.214286
37
0.567251
6257b1b9f2d23c01268a74bf62715ee65059342b
5,260
require 'rails_helper' RSpec.describe Order, type: :model do let(:order) { create(:order) } let(:u) { create(:user) } let(:order_with_user_and_assignee) { create(:order_with_user_and_assignee) } let(:order_with_items) { create(:order_with_items) } before(:each) do populate_roles @u = create(:user) end it "should have user" do expect(order_with_user_and_assignee.users.first).to be_a(User) end it "should have assigned user" do expect(order_with_user_and_assignee.assignees.first).to be_a(User) end it "should have items" do expect(order_with_items.items.first).to be_a(Item) end it "should have notes" do note_content = "There's a great big beautiful tomorrow" order.notes.build(content: note_content) order.save expect(order.notes.first.content).to eq(note_content) end it "provides an array of associated item ids" do items = order.items expect(order.item_ids).to eq(items.map { |i| i.id }) end it "can recall version of user data from time of request" do o = create(:order_with_user_and_assignee) p = o.users.first o.paper_trail.save_with_version sleep 1 p.update_attributes(first_name: 'Donna') o.reload v = o.paper_trail.previous_version expect(o.users.first.first_name).to eq('Donna') expect(v.version_users.first.first_name).to eq('Don') end it "can recall items associated with previous version" do o = order_with_items.clone first_item_id = o.items.first.id o.paper_trail.save_with_version o.item_orders.first.destroy o.reload current_item_ids = o.item_ids previous_item_ids = o.paper_trail.previous_version.version.association_data[:item_ids] expect(current_item_ids.include?(first_item_id)).to be false expect(previous_item_ids.include?(first_item_id)).to be true end it "can be reassigned" do o = create(:order_with_user_and_assignee) old_assignee = o.assignees.first new_assignee = create(:user, first_name: 'Alfred', last_name: 'Apaka') o.reassign_to(new_assignee.id) o.reload expect(o.assignee_ids.include?(new_assignee.id)).to be true expect(o.assignee_ids.include?(old_assignee.id)).to be false end it "maintains previous assignments in version" do o = create(:order_with_user_and_assignee) old_assignee = o.assignees.first new_assignee = create(:user, first_name: 'Alfred', last_name: 'Apaka') o.reassign_to(new_assignee.id) vo = o.paper_trail.previous_version expect(vo.version_assignees.include?(new_assignee)).to be false expect(vo.version_assignees.include?(old_assignee)).to be true end it "will not add duplicate items" do o = create(:order) i = create(:item) add1 = o.add_item(i) add2 = o.add_item(i) expect(add1).to be_a(ItemOrder) expect(add2).to eq(add1) end it "returns user that created the order" do o = create(:order_with_user_and_assignee) o.versions.each { |v| v.update_attributes(whodunnit: @u.id) } u1 = o.created_by_user expect(u1).to be_a(User) u2 = o.last_updated_by_user expect(u2).to be_a(User) end describe "order fees" do let(:order_type) { create(:order_type, name: 'reproduction') } let(:order_sub_type) { create(:order_sub_type, order_type_id: order_type.id) } let(:other_order_sub_type) { create(:order_sub_type) } let(:o) { create(:order, order_sub_type_id: order_sub_type.id) } let(:io) { create(:item_order, order_id: o.id) } let(:dio) { create(:digital_collections_order, order_id: o.id) } let!(:reproduction_spec) { create(:reproduction_spec, item_order_id: io.id, pages: 3) } # $1 x 3 pages + $1 per order = $4 let!(:fee1) { create(:order_fee, record_type: 'ItemOrder', record_id: io.id, ) } # $1 x 3 files + $1 per order = $4 let!(:fee2) { create(:order_fee, record_type: 'DigitalCollectionsOrder', record_id: dio.id) } # $1 per order = $1 let!(:fee3) { create(:order_fee, record_type: 'Order', record_id: o.id) } it "aggregates fees for reproduction" do order_fees = o.order_fees expect(order_fees).to be_a(Array) expect(order_fees.length).to eq(3) expect(order_fees.first).to be_a(OrderFee) end it "calculates total fees" do total = o.order_fees_total expect(total).to eq(9.00) end it "doesn't fail if total called without associated fees" do o = build(:order) expect { o.order_fees }.not_to raise_error expect { o.order_fees_total }.not_to raise_error expect(o.order_fees_total).to eq(0) end describe "cleanup_reproduction_associations" do it "will not remove associations for reproduction orders" do o.cleanup_reproduction_associations expect(o.order_fees.length).to eq(3) expect(o.digital_collections_orders.length).to eq(1) end it "will remove associations for non-reproduction orders" do order = o.clone order.update_attributes(order_sub_type_id: other_order_sub_type.id) order.cleanup_reproduction_associations order.reload expect(order.order_fees.length).to eq(0) expect(order.digital_collections_orders.length).to eq(0) end end end end
30.760234
97
0.696768
e9f162cb440ca7ceface4f753fb2173889f7200e
24,770
# frozen_string_literal: true module Unxls::Biff8::Constants RECORD_IDS = { 6 => :Formula, # section 2.4.127 9 => :BOF, # 0x0009 used in BIFF2 streams 10 => :EOF, # section 2.4.103 12 => :CalcCount, # section 2.4.31 13 => :CalcMode, # section 2.4.34 14 => :CalcPrecision, # section 2.4.35 15 => :CalcRefMode, # section 2.4.36 16 => :CalcDelta, # section 2.4.32 17 => :CalcIter, # section 2.4.33 18 => :Protect, # section 2.4.207 19 => :Password, # section 2.4.191 20 => :Header, # section 2.4.136 21 => :Footer, # section 2.4.124 23 => :ExternSheet, # section 2.4.106 24 => :Lbl, # section 2.4.150 25 => :WinProtect, # section 2.4.347 26 => :VerticalPageBreaks, # section 2.4.343 27 => :HorizontalPageBreaks, # section 2.4.142 28 => :Note, # section 2.4.179 29 => :Selection, # section 2.4.248 34 => :Date1904, # section 2.4.77 35 => :ExternName, # section 2.4.105 38 => :LeftMargin, # section 2.4.151 39 => :RightMargin, # section 2.4.219 40 => :TopMargin, # section 2.4.328 41 => :BottomMargin, # section 2.4.27 42 => :PrintRowCol, # section 2.4.203 43 => :PrintGrid, # section 2.4.202 47 => :FilePass, # section 2.4.117 49 => :Font, # section 2.4.122 51 => :PrintSize, # section 2.4.204 60 => :Continue, # section 2.4.58 61 => :Window1, # section 2.4.345 64 => :Backup, # section 2.4.14 65 => :Pane, # section 2.4.189 66 => :CodePage, # section 2.4.52 77 => :Pls, # section 2.4.199 80 => :DCon, # section 2.4.82 81 => :DConRef, # section 2.4.86 82 => :DConName, # section 2.4.85 85 => :DefColWidth, # section 2.4.89 89 => :XCT, # section 2.4.352 90 => :CRN, # section 2.4.65 91 => :FileSharing, # section 2.4.118 92 => :WriteAccess, # section 2.4.349 93 => :Obj, # section 2.4.181 94 => :Uncalced, # section 2.4.331 95 => :CalcSaveRecalc, # section 2.4.37 96 => :Template, # section 2.4.323 97 => :Intl, # section 2.4.147 99 => :ObjProtect, # section 2.4.183 125 => :ColInfo, # section 2.4.53 128 => :Guts, # section 2.4.134 129 => :WsBool, # section 2.4.351 130 => :GridSet, # section 2.4.132 131 => :HCenter, # section 2.4.135 132 => :VCenter, # section 2.4.342 133 => :BoundSheet8, # section 2.4.28 134 => :WriteProtect, # section 2.4.350 140 => :Country, # section 2.4.63 141 => :HideObj, # section 2.4.139 144 => :Sort, # section 2.4.263 146 => :Palette, # section 2.4.188 151 => :Sync, # section 2.4.318 152 => :LPr, # section 2.4.158 153 => :DxGCol, # section 2.4.98 154 => :FnGroupName, # section 2.4.120 155 => :FilterMode, # section 2.4.119 156 => :BuiltInFnGroupCount, # section 2.4.30 157 => :AutoFilterInfo, # section 2.4.8 158 => :AutoFilter, # section 2.4.6 160 => :Scl, # section 2.4.247 161 => :Setup, # section 2.4.257 174 => :ScenMan, # section 2.4.246 175 => :SCENARIO, # section 2.4.244 176 => :SxView, # section 2.4.313 177 => :Sxvd, # section 2.4.309 178 => :SXVI, # section 2.4.312 180 => :SxIvd, # section 2.4.292 181 => :SXLI, # section 2.4.293 182 => :SXPI, # section 2.4.298 184 => :DocRoute, # section 2.4.91 185 => :RecipName, # section 2.4.216 189 => :MulRk, # section 2.4.175 190 => :MulBlank, # section 2.4.174 193 => :Mms, # section 2.4.169 197 => :SXDI, # section 2.4.278 198 => :SXDB, # section 2.4.275 199 => :SXFDB, # section 2.4.283 200 => :SXDBB, # section 2.4.276 201 => :SXNum, # section 2.4.296 202 => :SxBool, # section 2.4.274 203 => :SxErr, # section 2.4.281 204 => :SXInt, # section 2.4.289 205 => :SXString, # section 2.4.304 206 => :SXDtr, # section 2.4.279 207 => :SxNil, # section 2.4.295 208 => :SXTbl, # section 2.4.305 209 => :SXTBRGIITM, # section 2.4.307 210 => :SxTbpg, # section 2.4.306 211 => :ObProj, # section 2.4.185 213 => :SXStreamID, # section 2.4.303 215 => :DBCell, # section 2.4.78 216 => :SXRng, # section 2.4.300 217 => :SxIsxoper, # section 2.4.290 218 => :BookBool, # section 2.4.22 220 => :DbOrParamQry, # section 2.4.79 221 => :ScenarioProtect, # section 2.4.245 222 => :OleObjectSize, # section 2.4.187 224 => :XF, # section 2.4.353 225 => :InterfaceHdr, # section 2.4.146 226 => :InterfaceEnd, # section 2.4.145 227 => :SXVS, # section 2.4.317 229 => :MergeCells, # section 2.4.168 233 => :BkHim, # section 2.4.19 235 => :MsoDrawingGroup, # section 2.4.171 236 => :MsoDrawing, # section 2.4.170 237 => :MsoDrawingSelection, # section 2.4.172 239 => :PhoneticInfo, # section 2.4.192 240 => :SxRule, # section 2.4.301 241 => :SXEx, # section 2.4.282 242 => :SxFilt, # section 2.4.285 244 => :SxDXF, # section 2.4.280 245 => :SxItm, # section 2.4.291 246 => :SxName, # section 2.4.294 247 => :SxSelect, # section 2.4.302 248 => :SXPair, # section 2.4.297 249 => :SxFmla, # section 2.4.286 251 => :SxFormat, # section 2.4.287 252 => :SST, # section 2.4.265 253 => :LabelSst, # section 2.4.149 255 => :ExtSST, # section 2.4.107 256 => :SXVDEx, # section 2.4.310 259 => :SXFormula, # section 2.4.288 290 => :SXDBEx, # section 2.4.277 311 => :RRDInsDel, # section 2.4.228 312 => :RRDHead, # section 2.4.226 315 => :RRDChgCell, # section 2.4.223 317 => :RRTabId, # section 2.4.241 318 => :RRDRenSheet, # section 2.4.234 319 => :RRSort, # section 2.4.240 320 => :RRDMove, # section 2.4.231 330 => :RRFormat, # section 2.4.238 331 => :RRAutoFmt, # section 2.4.222 333 => :RRInsertSh, # section 2.4.239 334 => :RRDMoveBegin, # section 2.4.232 335 => :RRDMoveEnd, # section 2.4.233 336 => :RRDInsDelBegin, # section 2.4.229 337 => :RRDInsDelEnd, # section 2.4.230 338 => :RRDConflict, # section 2.4.224 339 => :RRDDefName, # section 2.4.225 340 => :RRDRstEtxp, # section 2.4.235 351 => :LRng, # section 2.4.159 352 => :UsesELFs, # section 2.4.337 353 => :DSF, # section 2.4.94 401 => :CUsr, # section 2.4.72 402 => :CbUsr, # section 2.4.40 403 => :UsrInfo, # section 2.4.340 404 => :UsrExcl, # section 2.4.339 405 => :FileLock, # section 2.4.116 406 => :RRDInfo, # section 2.4.227 407 => :BCUsrs, # section 2.4.16 408 => :UsrChk, # section 2.4.338 425 => :UserBView, # section 2.4.333 426 => :UserSViewBegin, # section 2.4.334 # 426 => :UserSViewBegin_Chart, # section 2.4.335 427 => :UserSViewEnd, # section 2.4.336 428 => :RRDUserView, # section 2.4.237 429 => :Qsi, # section 2.4.208 430 => :SupBook, # section 2.4.271 431 => :Prot4Rev, # section 2.4.205 432 => :CondFmt, # section 2.4.56 433 => :CF, # section 2.4.42 434 => :DVal, # section 2.4.96 437 => :DConBin, # section 2.4.83 438 => :TxO, # section 2.4.329 439 => :RefreshAll, # section 2.4.217 440 => :HLink, # section 2.4.140 441 => :Lel, # section 2.4.154 442 => :CodeName, # section 2.4.51 443 => :SXFDBType, # section 2.4.284 444 => :Prot4RevPass, # section 2.4.206 445 => :ObNoMacros, # section 2.4.184 446 => :Dv, # section 2.4.95 448 => :Excel9File, # section 2.4.104 449 => :RecalcId, # section 2.4.215 450 => :EntExU2, # section 2.4.102 512 => :Dimensions, # section 2.4.90 513 => :Blank, # section 2.4.20 515 => :Number, # section 2.4.180 516 => :Label, # section 2.4.148 517 => :BoolErr, # section 2.4.24 519 => :String, # section 2.4.268 520 => :Row, # section 2.4.221 521 => :BOF, # 0x0209 used in BIFF3 streams 523 => :Index, # section 2.4.144 545 => :Array, # section 2.4.4 549 => :DefaultRowHeight, # section 2.4.87 566 => :Table, # section 2.4.319 574 => :Window2, # section 2.4.346 638 => :RK, # section 2.4.220 659 => :Style, # section 2.4.269 1033 => :BOF, # 0x0409 used in BIFF4 streams 1048 => :BigName, # section 2.4.18 1054 => :Format, # section 2.4.126 1084 => :ContinueBigName, # section 2.4.59 1212 => :ShrFmla, # section 2.4.260 2048 => :HLinkTooltip, # section 2.4.141 2049 => :WebPub, # section 2.4.344 2050 => :QsiSXTag, # section 2.4.211 2051 => :DBQueryExt, # section 2.4.81 2052 => :ExtString, # section 2.4.108 2053 => :TxtQry, # section 2.4.330 2054 => :Qsir, # section 2.4.210 2055 => :Qsif, # section 2.4.209 2056 => :RRDTQSIF, # section 2.4.236 2057 => :BOF, # section 2.4.21; 0x0809 used in BIFF5/7/8 streams 2058 => :OleDbConn, # section 2.4.186 2059 => :WOpt, # section 2.4.348 2060 => :SXViewEx, # section 2.4.314 2061 => :SXTH, # section 2.4.308 2062 => :SXPIEx, # section 2.4.299 2063 => :SXVDTEx, # section 2.4.311 2064 => :SXViewEx9, # section 2.4.315 2066 => :ContinueFrt, # section 2.4.60 2067 => :RealTimeData, # section 2.4.214 2128 => :ChartFrtInfo, # section 2.4.49 2129 => :FrtWrapper, # section 2.4.130 2130 => :StartBlock, # section 2.4.266 2131 => :EndBlock, # section 2.4.100 2132 => :StartObject, # section 2.4.267 2133 => :EndObject, # section 2.4.101 2134 => :CatLab, # section 2.4.38 2135 => :YMult, # section 2.4.356 2136 => :SXViewLink, # section 2.4.316 2137 => :PivotChartBits, # section 2.4.196 2138 => :FrtFontList, # section 2.4.129 2146 => :SheetExt, # section 2.4.259 2147 => :BookExt, # section 2.4.23 2148 => :SXAddl, # section 2.4.273.2 2149 => :CrErr, # section 2.4.64 2150 => :HFPicture, # section 2.4.138 2151 => :FeatHdr, # section 2.4.112 2152 => :Feat, # section 2.4.111 2154 => :DataLabExt, # section 2.4.75 2155 => :DataLabExtContents, # section 2.4.76 2156 => :CellWatch, # section 2.4.41 2161 => :FeatHdr11, # section 2.4.113 2162 => :Feature11, # section 2.4.114 2164 => :DropDownObjIds, # section 2.4.93 2165 => :ContinueFrt11, # section 2.4.61 2166 => :DConn, # section 2.4.84 2167 => :List12, # section 2.4.157 2168 => :Feature12, # section 2.4.115 2169 => :CondFmt12, # section 2.4.57 2170 => :CF12, # section 2.4.43 2171 => :CFEx, # section 2.4.44 2172 => :XFCRC, # section 2.4.354 2173 => :XFExt, # section 2.4.355 2174 => :AutoFilter12, # section 2.4.7 2175 => :ContinueFrt12, # section 2.4.62 2180 => :MDTInfo, # section 2.4.162 2181 => :MDXStr, # section 2.4.166 2182 => :MDXTuple, # section 2.4.167 2183 => :MDXSet, # section 2.4.165 2184 => :MDXProp, # section 2.4.164 2185 => :MDXKPI, # section 2.4.163 2186 => :MDB, # section 2.4.161 2187 => :PLV, # section 2.4.200 2188 => :Compat12, # section 2.4.54 2189 => :DXF, # section 2.4.97 2190 => :TableStyles, # section 2.4.322 2191 => :TableStyle, # section 2.4.320 2192 => :TableStyleElement, # section 2.4.321 2194 => :StyleExt, # section 2.4.270 2195 => :NamePublish, # section 2.4.178 2196 => :NameCmt, # section 2.4.176 2197 => :SortData, # section 2.4.264 2198 => :Theme, # section 2.4.326 2199 => :GUIDTypeLib, # section 2.4.133 2200 => :FnGrp12, # section 2.4.121 2201 => :NameFnGrp12, # section 2.4.177 2202 => :MTRSettings, # section 2.4.173 2203 => :CompressPictures, # section 2.4.55 2204 => :HeaderFooter, # section 2.4.137 2205 => :CrtLayout12, # section 2.4.66 2206 => :CrtMlFrt, # section 2.4.70 2207 => :CrtMlFrtContinue, # section 2.4.71 2211 => :ForceFullCalculation, # section 2.4.125 2212 => :ShapePropsStream, # section 2.4.258 2213 => :TextPropsStream, # section 2.4.325 2214 => :RichTextStream, # section 2.4.218 2215 => :CrtLayout12A, # section 2.4.67 4097 => :Units, # section 2.4.332 4098 => :Chart, # section 2.4.45 4099 => :Series, # section 2.4.252 4102 => :DataFormat, # section 2.4.74 4103 => :LineFormat, # section 2.4.156 4105 => :MarkerFormat, # section 2.4.160 4106 => :AreaFormat, # section 2.4.3 4107 => :PieFormat, # section 2.4.195 4108 => :AttachedLabel, # section 2.4.5 4109 => :SeriesText, # section 2.4.254 4116 => :ChartFormat, # section 2.4.48 4117 => :Legend, # section 2.4.152 4118 => :SeriesList, # section 2.4.253 4119 => :Bar, # section 2.4.15 4120 => :Line, # section 2.4.155 4121 => :Pie, # section 2.4.194 4122 => :Area, # section 2.4.2 4123 => :Scatter, # section 2.4.243 4124 => :CrtLine, # section 2.4.68 4125 => :Axis, # section 2.4.11 4126 => :Tick, # section 2.4.327 4127 => :ValueRange, # section 2.4.341 4128 => :CatSerRange, # section 2.4.39 4129 => :AxisLine, # section 2.4.12 4130 => :CrtLink, # section 2.4.69 4132 => :DefaultText, # section 2.4.88 4133 => :Text, # section 2.4.324 4134 => :FontX, # section 2.4.123 4135 => :ObjectLink, # section 2.4.182 4146 => :Frame, # section 2.4.128 4147 => :Begin, # section 2.4.17 4148 => :End, # section 2.4.99 4149 => :PlotArea, # section 2.4.197 4154 => :Chart3d, # section 2.4.46 4156 => :PicF, # section 2.4.193 4157 => :DropBar, # section 2.4.92 4158 => :Radar, # section 2.4.212 4159 => :Surf, # section 2.4.272 4160 => :RadarArea, # section 2.4.213 4161 => :AxisParent, # section 2.4.13 4163 => :LegendException, # section 2.4.153 4164 => :ShtProps, # section 2.4.261 4165 => :SerToCrt, # section 2.4.256 4166 => :AxesUsed, # section 2.4.10 4168 => :SBaseRef, # section 2.4.242 4170 => :SerParent, # section 2.4.255 4171 => :SerAuxTrend, # section 2.4.250 4174 => :IFmtRecord, # section 2.4.143 4175 => :Pos, # section 2.4.201 4176 => :AlRuns, # section 2.4.1 4177 => :BRAI, # section 2.4.29 4187 => :SerAuxErrBar, # section 2.4.249 4188 => :ClrtClient, # section 2.4.50 4189 => :SerFmt, # section 2.4.251 4191 => :Chart3DBarShape, # section 2.4.47 4192 => :Fbi, # section 2.4.109 4193 => :BopPop, # section 2.4.25 4194 => :AxcExt, # section 2.4.9 4195 => :Dat, # section 2.4.73 4196 => :PlotGrowth, # section 2.4.198 4197 => :SIIndex, # section 2.4.262 4198 => :GelFrame, # section 2.4.131 4199 => :BopPopCustom, # section 2.4.26 4200 => :Fbi2, # section 2.4.110 }.freeze CONTINUE_RECORDS = [ :Continue, :ContinueFrt, :ContinueFrt11, :ContinueFrt12, :ContinueBigName, :CrtMlFrtContinue, ].freeze # See "5.17 CODEPAGE" of OpenOffice's doc, p.145 # @todo Move to BIFF submodules for versions <8 as BIFF8 CodePage is always UTF-16LE CODEPAGES = { 0x016F => :ASCII, # 367 0x01B5 => :CP437, # IBM PC CP-437 (US), 437 0x02D0 => :CP720, # IBM PC CP-720 (OEM Arabic), 720 0x02E1 => :CP737, # IBM PC CP-737 (Greek), 737 0x0307 => :CP775, # IBM PC CP-775 (Baltic), 775 0x0352 => :CP850, # IBM PC CP-850 (Latin I), 850 0x0354 => :CP852, # IBM PC CP-852 (Latin II (Central European)), 852 0x0357 => :CP855, # IBM PC CP-855 (Cyrillic), 855 0x0359 => :CP857, # IBM PC CP-857 (Turkish), 857 0x035A => :CP858, # IBM PC CP-858 (Multilingual Latin I with Euro), 858 0x035C => :CP860, # IBM PC CP-860 (Portuguese), 860 0x035D => :CP861, # IBM PC CP-861 (Icelandic), 861 0x035E => :CP862, # IBM PC CP-862 (Hebrew), 862 0x035F => :CP863, # IBM PC CP-863 (Canadian (French)), 863 0x0360 => :CP864, # IBM PC CP-864 (Arabic), 864 0x0361 => :CP865, # IBM PC CP-865 (Nordic), 865 0x0362 => :CP866, # IBM PC CP-866 (Cyrillic (Russian)), 866 0x0365 => :CP869, # IBM PC CP-869 (Greek (Modern)), 869 0x036A => :CP874, # Windows CP-874 (Thai), 874 0x03A4 => :'Windows-932', # (Japanese Shift-JIS), 932 0x03A8 => :'Windows-936', # (Chinese Simplified GBK), 936 0x03B5 => :'Windows-949', # (Korean (Wansung)), 949 0x03B6 => :'Windows-950', # (Chinese Traditional BIG5), 950 0x04B0 => :'UTF-16LE', # (BIFF8), 1200 0x04E2 => :'Windows-1250', # (Latin II) (Central European), 1250 0x04E3 => :'Windows-1251', # (Cyrillic), 1251 0x04E4 => :'Windows-1252', # (Latin I) (BIFF4-BIFF5), 1252 0x04E5 => :'Windows-1253', # (Greek), 1253 0x04E6 => :'Windows-1254', # (Turkish), 1254 0x04E7 => :'Windows-1255', # (Hebrew), 1255 0x04E8 => :'Windows-1256', # (Arabic), 1256 0x04E9 => :'Windows-1257', # (Baltic), 1257 0x04EA => :'Windows-1258', # (Vietnamese), 1258 0x0551 => :'Windows-1361', # (Korean (Johab)), 1361 0x2710 => :MacRoman, # Apple Roman, 10000 0x8000 => :MacRoman, # Apple Roman, 32768 0x8001 => :'Windows-1252' # (Latin I) (BIFF2-BIFF3), 32769 }.freeze CHARSETS = { 0x00 => :ANSI, # ANSI Latin 0x01 => :Default, # System default 0x02 => :Symbol, # Symbol 0x4D => :Mac, # Apple Roman 0x80 => :ShiftJIS, # ANSI Japanese Shift-JIS 0x81 => :Jangul, # ANSI Korean (Hangul) 0x82 => :Johab, # ANSI Korean (Johab) 0x86 => :GB2312, # ANSI Chinese Simplified GBK 0x88 => :ChineseBIG5, # ANSI Chinese Traditional BIG5 0xA1 => :Greek, # ANSI Greek 0xA2 => :Turkish, # ANSI Turkish 0xA3 => :Vietnamese, # ANSI Vietnamese 0xB1 => :Hebrew, # ANSI Hebrew 0xB2 => :Arabic, # ANSI Arabic 0xBA => :Baltic, # ANSI Baltic 0xCC => :Russian, # ANSI Cyrillic 0xDD => :Thai, # ANSI Thai 0xEE => :EastEurope, # ANSI Latin II (Central European) 0xFF => :OEM # OEM Latin I }.freeze COUNTRIES = { 1 => :'United States', 2 => :Canada, 3 => :'Latin America except Brazil', 7 => :Russia, 20 => :Egypt, 30 => :Greece, 31 => :Netherlands, 32 => :Belgium, 33 => :France, 34 => :Spain, 36 => :Hungary, 39 => :Italy, 41 => :Switzerland, 43 => :Austria, 44 => :'United Kingdom', 45 => :Denmark, 46 => :Sweden, 47 => :Norway, 48 => :Poland, 49 => :Germany, 52 => :Mexico, 55 => :Brazil, 61 => :Australia, 64 => :'New Zealand', 66 => :Thailand, 81 => :Japan, 82 => :Korea, 84 => :'Viet Nam', 86 => :"People's Republic of China", 90 => :Turkey, 213 => :Algeria, 216 => :Morocco, 218 => :Libya, 351 => :Portugal, 354 => :Iceland, 358 => :Finland, 420 => :'Czech Republic', 886 => :Taiwan, 961 => :Lebanon, 962 => :Jordan, 963 => :Syria, 964 => :Iraq, 965 => :Kuwait, 966 => :'Saudi Arabia', 971 => :'United Arab Emirates', 972 => :Israel, 974 => :Qatar, 981 => :Iran }.freeze # See G.2 Built-in Cell Styles (p. 4456), Ecma Office Open XML Part 1 - Fundamentals And Markup Language Reference.pdf BUILTIN_STYLES = { 0 => :'Normal', 1 => :'RowLevel_', 2 => :'ColLevel_', 3 => :'Comma', 4 => :'Currency', 5 => :'Percent', 6 => :'Comma [0]', 7 => :'Currency [0]', 8 => :'Hyperlink', 9 => :'Followed Hyperlink', 10 => :'Note', 11 => :'Warning Text', # 12 => :'Emphasis 1', # not in the specification # 13 => :'Emphasis 2', # not in the specification # 14 => :'Emphasis 3', # not in the specification 15 => :'Title', 16 => :'Heading 1', 17 => :'Heading 2', 18 => :'Heading 3', 19 => :'Heading 4', 20 => :'Input', 21 => :'Output', 22 => :'Calculation', 23 => :'Check Cell', 24 => :'Linked Cell', 25 => :'Total', 26 => :'Good', 27 => :'Bad', 28 => :'Neutral', 29 => :'Accent1', 30 => :'20% - Accent1', 31 => :'40% - Accent1', 32 => :'60% - Accent1', 33 => :'Accent2', 34 => :'20% - Accent2', 35 => :'40% - Accent2', 36 => :'60% - Accent2', 37 => :'Accent3', 38 => :'20% - Accent3', 39 => :'40% - Accent3', 40 => :'60% - Accent3', 41 => :'Accent4', 42 => :'20% - Accent4', 43 => :'40% - Accent4', 44 => :'60% - Accent4', 45 => :'Accent5', 46 => :'20% - Accent5', 47 => :'40% - Accent5', 48 => :'60% - Accent5', 49 => :'Accent6', 50 => :'20% - Accent6', 51 => :'40% - Accent6', 52 => :'60% - Accent6', 53 => :'Explanatory Text', }.freeze # See p. 699 ICV_COLOR_TABLE = { # Built-in 0x0000 => { name: :Black, rgb: :'000000' }, 0x0001 => { name: :White, rgb: :'FFFFFF' }, 0x0002 => { name: :Red, rgb: :'FF0000' }, 0x0003 => { name: :Green, rgb: :'00FF00' }, 0x0004 => { name: :Blue, rgb: :'0000FF' }, 0x0005 => { name: :Yellow, rgb: :'FFFF00' }, 0x0006 => { name: :Magenta, rgb: :'FF00FF' }, 0x0007 => { name: :Cyan, rgb: :'00FFFF' }, # Default palette 0x0008 => { name: :rgColor0, rgb: :'000000' }, 0x0009 => { name: :rgColor1, rgb: :'FFFFFF' }, 0x000A => { name: :rgColor2, rgb: :'FF0000' }, 0x000B => { name: :rgColor3, rgb: :'00FF00' }, 0x000C => { name: :rgColor4, rgb: :'0000FF' }, 0x000D => { name: :rgColor5, rgb: :'FFFF00' }, 0x000E => { name: :rgColor6, rgb: :'FF00FF' }, 0x000F => { name: :rgColor7, rgb: :'00FFFF' }, 0x0010 => { name: :rgColor8, rgb: :'800000' }, 0x0011 => { name: :rgColor9, rgb: :'008000' }, 0x0012 => { name: :rgColor10, rgb: :'000080' }, 0x0013 => { name: :rgColor11, rgb: :'808000' }, 0x0014 => { name: :rgColor12, rgb: :'800080' }, 0x0015 => { name: :rgColor13, rgb: :'008080' }, 0x0016 => { name: :rgColor14, rgb: :'C0C0C0' }, 0x0017 => { name: :rgColor15, rgb: :'808080' }, 0x0018 => { name: :rgColor16, rgb: :'9999FF' }, 0x0019 => { name: :rgColor17, rgb: :'993366' }, 0x001A => { name: :rgColor18, rgb: :'FFFFCC' }, 0x001B => { name: :rgColor19, rgb: :'CCFFFF' }, 0x001C => { name: :rgColor20, rgb: :'660066' }, 0x001D => { name: :rgColor21, rgb: :'FF8080' }, 0x001E => { name: :rgColor22, rgb: :'0066CC' }, 0x001F => { name: :rgColor23, rgb: :'CCCCFF' }, 0x0020 => { name: :rgColor24, rgb: :'000080' }, 0x0021 => { name: :rgColor25, rgb: :'FF00FF' }, 0x0022 => { name: :rgColor26, rgb: :'FFFF00' }, 0x0023 => { name: :rgColor27, rgb: :'00FFFF' }, 0x0024 => { name: :rgColor28, rgb: :'800080' }, 0x0025 => { name: :rgColor29, rgb: :'800000' }, 0x0026 => { name: :rgColor30, rgb: :'008080' }, 0x0027 => { name: :rgColor31, rgb: :'0000FF' }, 0x0028 => { name: :rgColor32, rgb: :'00CCFF' }, 0x0029 => { name: :rgColor33, rgb: :'CCFFFF' }, 0x002A => { name: :rgColor34, rgb: :'CCFFCC' }, 0x002B => { name: :rgColor35, rgb: :'FFFF99' }, 0x002C => { name: :rgColor36, rgb: :'99CCFF' }, 0x002D => { name: :rgColor37, rgb: :'FF99CC' }, 0x002E => { name: :rgColor38, rgb: :'CC99FF' }, 0x002F => { name: :rgColor39, rgb: :'FFCC99' }, 0x0030 => { name: :rgColor40, rgb: :'3366FF' }, 0x0031 => { name: :rgColor41, rgb: :'33CCCC' }, 0x0032 => { name: :rgColor42, rgb: :'99CC00' }, 0x0033 => { name: :rgColor43, rgb: :'FFCC00' }, 0x0034 => { name: :rgColor44, rgb: :'FF9900' }, 0x0035 => { name: :rgColor45, rgb: :'FF6600' }, 0x0036 => { name: :rgColor46, rgb: :'666699' }, 0x0037 => { name: :rgColor47, rgb: :'969696' }, 0x0038 => { name: :rgColor48, rgb: :'003366' }, 0x0039 => { name: :rgColor49, rgb: :'339966' }, 0x003A => { name: :rgColor50, rgb: :'003300' }, 0x003B => { name: :rgColor51, rgb: :'333300' }, 0x003C => { name: :rgColor52, rgb: :'993300' }, 0x003D => { name: :rgColor53, rgb: :'993366' }, 0x003E => { name: :rgColor54, rgb: :'333399' }, 0x003F => { name: :rgColor55, rgb: :'333333' }, 0x0040 => { name: :default_foreground }, # Default foreground color. This is the window text color in the sheet display. 0x0041 => { name: :default_background }, # Default background color. This is the window background color in the sheet display and is the default background color for a cell. 0x004D => { name: :default_chart_foreground }, # Default chart foreground color. This is the window text color in the chart display. 0x004E => { name: :default_chart_background }, # Default chart background color. This is the window background color in the chart display. 0x004F => { name: :chart_neutral }, # Chart neutral color which is black, an RGB value of (0,0,0). 0x0051 => { name: :tooltip_text }, # ToolTip text color. This is the automatic font color for comments. 0x7FFF => { name: :font_automatic }, # Font automatic color. This is the window text color. }.freeze end
39.695513
177
0.558054
4a0e304546b012643f4f7bfa88a26006c7a4fdd6
133
# frozen_string_literal: true require 'db/vk_informer_link' FactoryBot.define do factory :cwlink, class: Vk::Cwlink do end end
14.777778
39
0.766917
d5e879a1f5e9f8d0fe097e7d2c61ddeb7ab04fda
658
require_relative 'boot' require 'rails/all' require 'carrierwave' require 'carrierwave/orm/activerecord' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module RailsBlog class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.1 # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. end end
29.909091
82
0.772036
bb18aef2ef392d31b5c8b0fc41ba1bf989855ec4
1,864
# frozen_string_literal: true require 'integration/integration_spec_helper' require 'integration/admin/shared_examples_for_admin_page' describe 'Admin API token edit page', type: :feature do let!(:token) { create :api_token, app_name: 'Test Application', admin_email: '[email protected]' } context 'when the current user is an admin' do before do authenticate_admin_user visit rails_admin.edit_path(model_name: :api_token, id: token.id) end describe 'visiting the form to edit an API Token' do it_behaves_like 'a page with the admin layout' it 'show the correct content' do expect(page).to have_content 'Edit API token' end it "does not allow the token's value to be set" do expect(page).not_to have_field 'Token' end it "does not allow the token's total requests to be set" do expect(page).not_to have_field 'Total requests' end end describe 'submitting the form to update an API Token' do before do fill_in 'App name', with: 'Updated' fill_in 'Admin email', with: '[email protected]' click_button 'Save' end it 'saves the new API Token data' do t = token.reload expect(t.token).not_to be_blank expect(t.app_name).to eq 'Updated' expect(t.admin_email).to eq '[email protected]' expect(t.total_requests).to eq 0 end end end context 'when the current user is not an admin' do before { authenticate_user } it 'redirects back to the home page with an error message' do visit rails_admin.edit_path(model_name: :api_token, id: token.id) expect(page).to have_current_path root_path, ignore_query: true expect(page).to have_content I18n.t('admin.authorization.not_authorized') end end end
31.066667
79
0.66309
f8b9a0ae570a20bc909b1bd8d501c2dda42256b1
9,137
require 'spec_helper' describe "User pages" do subject { page } describe "index" do let(:user) { FactoryGirl.create(:user) } before(:each) do sign_in user visit users_path end it { should have_title('All users') } it { should have_content('All users') } describe "pagination" do before(:all) { 30.times { FactoryGirl.create(:user) } } after(:all) { User.delete_all } it { should have_link('Next') } its(:html) { should match('>2</a>') } it { should have_selector('.pagination') } it "should list each user" do User.page(1).each do |user| expect(page).to have_selector('li', text: user.name) end end let(:first_page) { User.page(1) } let(:second_page) { User.page(2) } it "should list the first page of users" do first_page.each do |user| expect(page).to have_selector('li', text: user.name) end end it "should not list the second page of users" do second_page.each do |user| expect(page).not_to have_selector('li', text: user.name) end end describe "showing the second page" do before { visit users_path(page: 2) } it "should list the second page of users" do second_page.each do |user| expect(page).to have_selector('li', text: user.name) end end end end describe "delete links" do it { should_not have_link('delete') } describe "as an admin user" do let(:admin) { FactoryGirl.create(:admin) } before do sign_in admin visit users_path end it { should have_link('delete', href: user_path(User.first)) } it "should be able to delete another user" do expect do click_link('delete', match: :first) end.to change(User, :count).by(-1) end it { should_not have_link('delete', href: user_path(admin)) } end end describe "set clear admin links" do it { is_expected.not_to have_link('set admin') } describe "as an admin user" do let(:admin) { FactoryGirl.create(:admin) } before do sign_in admin visit users_path end it { is_expected.to have_link('set admin', href: update_admin_user_path(User.first,set_admin:true)) } it { is_expected.not_to have_link('remove admin', href: update_admin_user_path(User.first,set_admin:false)) } it "should be change" do click_link('set admin', match: :first) expect(User.first.admin).to eq(true) expect(page).to have_link('remove admin') click_link('remove admin', match: :first) expect(User.first.admin).to eq(false) end end end describe "show emails" do describe "as an normal user" do before do @other_user = create(:user) @user = create(:user) sign_in @user visit users_path end it { is_expected.not_to have_content(@other_user.email)} end describe "as an admin user" do before do @other_user = create(:user) @admin = create(:admin) sign_in @admin visit users_path end it { is_expected.to have_content(@other_user.email)} end end end describe "profile page" do let(:user) { create(:user) } let!(:m1) { create(:idea, user: user, content: "Foo") } let!(:m2) { create(:idea, user: user, content: "Bar") } before { visit user_path(user) } it { should have_content(user.name) } it { should have_title(user.name) } describe "ideas" do it { should have_content(m1.content) } it { should have_content(m2.content) } it { should have_content(user.ideas.count) } end describe "follow/unfollow buttons" do let(:other_user) { FactoryGirl.create(:user) } before { sign_in user } describe "following a user" do before { visit user_path(other_user) } it "should increment the followed user count" do expect do click_button "Follow" end.to change(user.followed_users, :count).by(1) end it "should increment the other user's followers count" do expect do click_button "Follow" end.to change(other_user.followers, :count).by(1) end describe "toggling the button" do before { click_button "Follow" } it { should have_xpath("//input[@value='Unfollow']") } end end describe "unfollowing a user" do before do user.follow!(other_user) visit user_path(other_user) end it "should decrement the followed user count" do expect do click_button "Unfollow" end.to change(user.followed_users, :count).by(-1) end it "should decrement the other user's followers count" do expect do click_button "Unfollow" end.to change(other_user.followers, :count).by(-1) end describe "toggling the button" do before { click_button "Unfollow" } it { should have_xpath("//input[@value='Follow']") } end end end end describe "signup page" do before { visit signup_path } it { should have_content('Sign up') } it { should have_title(full_title('Sign up')) } end describe "signup" do before { visit signup_path } let(:submit) { "Sign up" } describe "with invalid information" do it "should not create a user" do expect { click_button submit }.not_to change(User, :count) end describe "error messages" do before { click_button submit } it { should have_title('Sign up') } it { should have_content('error') } end end describe "with valid information" do before do fill_in "Name", with: "Example User" fill_in "Email", with: "[email protected]" fill_in "Password", with: "foobar" fill_in "Confirmation", with: "foobar" end it "should create a user" do expect { click_button submit }.to change(User, :count).by(1) end describe "after saving the user" do before { click_button submit } let(:user) { User.find_by(email: '[email protected]') } it { is_expected.to have_link('Sign out') } it { is_expected.to have_link('Post new idea') } it { is_expected.to have_title('Pressfrwrd') } it { should have_selector('div.alert.alert-success', text: 'Welcome') } end end end describe "edit" do let(:user) { FactoryGirl.create(:user) } before do sign_in user visit edit_user_path(user) end describe "page" do it { should have_content("Update your profile") } it { should have_title("Edit user") } it { should have_link('change', href: 'http://gravatar.com/emails') } end describe "with invalid information" do before { click_button "Save changes" } it { should have_content('error') } end describe "with valid information" do let(:new_name) { "New Name" } let(:new_email) { "[email protected]" } before do fill_in "Name", with: new_name fill_in "Email", with: new_email fill_in "Password", with: user.password fill_in "Confirm", with: user.password click_button "Save changes" end it { should have_title(new_name) } it { should have_selector('div.alert.alert-success') } it { should have_link('Sign out', href: signout_path) } specify { expect(user.reload.name).to eq new_name } specify { expect(user.reload.email).to eq new_email } end describe "forbidden attributes" do let(:params) do { user: { admin: true, password: user.password, password_confirmation: user.password } } end before do sign_in user, no_capybara: true patch user_path(user), params end specify { expect(user.reload).not_to be_admin } end end describe "following/followers" do let(:user) { FactoryGirl.create(:user) } let(:other_user) { FactoryGirl.create(:user) } before { user.follow!(other_user) } describe "followed users" do before do sign_in user visit following_user_path(user) end it { should have_title(full_title('Following')) } it { should have_selector('h3', text: 'Following') } it { should have_link(other_user.name, href: user_path(other_user)) } end describe "followers" do before do sign_in other_user visit followers_user_path(other_user) end it { should have_title(full_title('Followers')) } it { should have_selector('h3', text: 'Followers') } it { should have_link(user.name, href: user_path(user)) } end end end
28.642633
117
0.590675
f85f4c20ec19cc7dad76ab38bf29245e6ade3d24
698
=begin * Created by PSU Beeminder Capstone Team on 3/12/2017. * Copyright (c) 2017 PSU Beeminder Capstone Team * This code is available under the "MIT License". * Please see the file LICENSE in this distribution for license terms. =end class RtmAdapter < BaseAdapter class << self def required_keys %i(token) end def auth_type :oauth end def website_link "https://www.rememberthemilk.com/" end def title "Remember The Milk" end end def client client = Milkman::Client.new api_key: Rails.application.secrets.rtm_provider_key, shared_secret: Rails.application.secrets.rtm_provider_secret, auth_token: access_token end end
23.266667
172
0.707736
d5dbba8aa3ccecdc8836d82f39c4ea8d7bcc786f
334
#!/usr/bin/env ruby require 'deluge' arg_host = ARGV[0] arg_port = ARGV[1] arg_login = ARGV[2] arg_password = ARGV[3] # Initialize client client = Deluge::Rpc::Client.new( host: arg_host, port: arg_port, login: arg_login, password: arg_password ) client.connect puts client.core.test_listen_port() # Closing client.close
15.904762
44
0.724551
1d7b22bee2048bec5b97da2cd18aa822c9a9617d
338
module Omniship module DHLGM module Track class Shipment < Omniship::Base def packages [Package.new(@root)] # DHLGM only supports one package per shipment end # There is no delivery time for DHLGM def scheduled_delivery nil end end end end end
18.777778
77
0.576923
edbdf62257c5b6d997a4d1479f44dc5c6e03f901
827
# frozen_string_literal: true # == Schema Information # # Table name: volunteer_trainings # # id :integer not null, primary key # volunteer_id :integer # radio :boolean default(FALSE) # ops_basics :boolean default(FALSE) # first_contact :boolean default(FALSE) # communications :boolean default(FALSE) # dispatch :boolean default(FALSE) # wandering_host :boolean default(FALSE) # xo :boolean default(FALSE) # ops_subhead :boolean default(FALSE) # ops_head :boolean default(FALSE) # created_at :datetime # updated_at :datetime # require 'test_helper' class VolunteerTrainingTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
28.517241
57
0.607013
089005f15dc3f7f1de8bfdf2955477fec57b72e7
3,227
# # Fluentd # # 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 'fluent/engine' require 'fluent/system_config' require 'fluent/config' module Fluent module Test def self.setup Fluent.__send__(:remove_const, :Engine) engine = Fluent.const_set(:Engine, EngineClass.new).init(SystemConfig.new) engine.define_singleton_method(:now=) {|n| @now = n } engine.define_singleton_method(:now) { @now || super() } ::Test::Unit::Assertions.module_eval { def assert_equal_event_time(a, b) assert_equal(a.sec, b.sec) assert_equal(a.nsec, b.nsec) end } nil end class TestDriver include ::Test::Unit::Assertions def initialize(klass, &block) if klass.is_a?(Class) if block # Create new class for test w/ overwritten methods # klass.dup is worse because its ancestors does NOT include original class name klass = Class.new(klass) klass.module_eval(&block) end @instance = klass.new else @instance = klass end @instance.router = Engine.root_agent.event_router @instance.log = TestLogger.new Engine.root_agent.instance_variable_set(:@log, @instance.log) @config = Config.new end attr_reader :instance, :config def configure(str, use_v1 = false) if str.is_a?(Fluent::Config::Element) @config = str else @config = Config.parse(str, "(test)", "(test_dir)", use_v1) end if label_name = @config['@label'] Engine.root_agent.add_label(label_name) end @instance.configure(@config) self end # num_waits is for checking thread status. This will be removed after improved plugin API def run(num_waits = 10, &block) @instance.start begin # wait until thread starts num_waits.times { sleep 0.05 } return yield ensure @instance.shutdown end end end class DummyLogDevice attr_reader :logs def initialize @logs = [] end def tty? false end def puts(*args) args.each{ |arg| write(arg + "\n") } end def write(message) @logs.push message end def flush true end def close true end end class TestLogger < Fluent::PluginLogger def initialize @logdev = DummyLogDevice.new super(Fluent::Log.new(@logdev)) end def logs @logdev.logs end end end end
24.08209
95
0.59374
61f9e5346d19d378e055477382ef918483d63eb5
471
# frozen_string_literal: true require 'spec_helper' describe Gitlab::Client do describe '.version' do before do stub_get('/version', 'version') end let!(:version) { Gitlab.version } it 'gets the correct resource' do expect(a_get('/version')).to have_been_made end it 'returns information about gitlab server' do expect(version.version).to eq('8.13.0-pre') expect(version.revision).to eq('4e963fe') end end end
20.478261
51
0.66242
acadda0e508df6ec51bcb3e08a0f465f0fb504ea
2,230
=begin Copyright 2016 SourceClear 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. =end require_relative "#{Rails.root}/lib/github_api" class ProjectsController < ApplicationController def index @projects = Projects end def edit @project = Projects[id: params[:id].to_i] end def create params = create_project_params begin if params[:name].include?('/') @project = import_project(params[:name], params[:rule_sets]) else @project = import_user(params[:name], params[:rule_sets]) end redirect_to action: 'index' rescue Sequel::ValidationFailed render 'new' rescue Sequel::DatabaseError => e render 'new' end end def update @project = Projects[id: params[:id].to_i] begin @project.update(update_project_params) redirect_to action: 'index' rescue Sequel::ValidationFailed render 'edit' rescue Sequel::DatabaseError => e render 'edit' end end def destroy @project = Projects[id: params[:id].to_i] @project.destroy redirect_to projects_path end private def import_user(username, rule_sets) github_token = Configurations.first.github_token gh = GitHubAPI.new(github_token) repo_names = gh.get_repo_names(username) repo_names.each do |repo_name| import_project("#{username}/#{repo_name}", rule_sets) end end def import_project(name, rule_sets) project = Projects.new({ name: name, rule_sets: rule_sets }) project.save project end def create_project_params params.require(:project).permit(:name, :rule_sets) end def update_project_params params.require(:project).permit(:name, :rule_sets, :next_audit, :last_commit_time) end end
25.05618
86
0.709417
21596a1e04986433969a316d0d2e0808daca779a
3,343
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20150629120120) do create_table "followers", force: :cascade do |t| t.integer "user_id" t.integer "follower_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "followers", ["user_id"], name: "index_followers_on_user_id" create_table "follows", id: false, force: :cascade do |t| t.integer "follower_id" t.integer "followee_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "profiles", force: :cascade do |t| t.string "name" t.text "description" t.integer "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "profiles", ["user_id"], name: "index_profiles_on_user_id" create_table "simple_hashtag_hashtaggings", force: :cascade do |t| t.integer "hashtag_id" t.integer "hashtaggable_id" t.string "hashtaggable_type" end add_index "simple_hashtag_hashtaggings", ["hashtag_id"], name: "index_simple_hashtag_hashtaggings_on_hashtag_id" add_index "simple_hashtag_hashtaggings", ["hashtaggable_id", "hashtaggable_type"], name: "index_hashtaggings_hashtaggable_id_hashtaggable_type" create_table "simple_hashtag_hashtags", force: :cascade do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end add_index "simple_hashtag_hashtags", ["name"], name: "index_simple_hashtag_hashtags_on_name" create_table "tweets", force: :cascade do |t| t.integer "user_id" t.text "body" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "tweets", ["user_id"], name: "index_tweets_on_user_id" create_table "users", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "username" end add_index "users", ["email"], name: "index_users_on_email", unique: true add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true end
37.988636
145
0.707748
5dfe4fbad9f395837f1c8bc103c42b83e1de66f7
286
require 'generators/cells/view_generator' module Slim module Generators class CellGenerator < ::Cells::Generators::ViewGenerator source_root File.expand_path('../../templates', __FILE__) private def handler :slim end end end end
15.888889
63
0.643357
8777bf34985bb217893979748e9c85fd8aece510
1,435
module LightService class ExpectedKeysNotInContextError < StandardError; end class PromisedKeysNotInContextError < StandardError; end class Context class KeyVerifier class << self def verify_expected_keys_are_in_context(context, action) verify_keys_are_in_context(context, action.expected_keys) do |not_found_keys| error_message = "expected #{format_keys(not_found_keys)} to be in the context during #{action}" Configuration.logger.error error_message fail ExpectedKeysNotInContextError, error_message end end def verify_promised_keys_are_in_context(context, action) return context if context.failure? verify_keys_are_in_context(context, action.promised_keys) do |not_found_keys| error_message = "promised #{format_keys(not_found_keys)} to be in the context during #{action}" Configuration.logger.error error_message fail PromisedKeysNotInContextError, error_message end end private def verify_keys_are_in_context(context, keys) keys ||= context.keys not_found_keys = keys - context.keys unless not_found_keys.empty? yield not_found_keys end context end def format_keys(keys) keys.map { |k| ":#{k}"}.join(', ') end end end end end
29.895833
107
0.656446
62bb0d450a05df9c5555ed258e2b820034025200
4,400
# == Schema Information # # Table name: accounts # # id :integer not null, primary key # auto_resolve_duration :integer # domain :string(100) # feature_flags :integer default(0), not null # locale :integer default("en") # name :string not null # settings_flags :integer default(0), not null # support_email :string(100) # created_at :datetime not null # updated_at :datetime not null # class Account < ApplicationRecord # used for single column multi flags include FlagShihTzu include Reportable include Featurable DEFAULT_QUERY_SETTING = { flag_query_mode: :bit_operator }.freeze ACCOUNT_SETTINGS_FLAGS = { 1 => :custom_email_domain_enabled }.freeze validates :name, presence: true validates :auto_resolve_duration, numericality: { greater_than_or_equal_to: 1, allow_nil: true } has_many :account_users, dependent: :destroy has_many :agent_bot_inboxes, dependent: :destroy has_many :agent_bots, dependent: :destroy has_many :csat_survey_responses, dependent: :destroy has_many :data_imports, dependent: :destroy has_many :users, through: :account_users has_many :inboxes, dependent: :destroy has_many :notes, dependent: :destroy has_many :campaigns, dependent: :destroy has_many :conversations, dependent: :destroy has_many :messages, dependent: :destroy has_many :contacts, dependent: :destroy has_many :facebook_pages, dependent: :destroy, class_name: '::Channel::FacebookPage' has_many :telegram_bots, dependent: :destroy has_many :twilio_sms, dependent: :destroy, class_name: '::Channel::TwilioSms' has_many :twitter_profiles, dependent: :destroy, class_name: '::Channel::TwitterProfile' has_many :web_widgets, dependent: :destroy, class_name: '::Channel::WebWidget' has_many :email_channels, dependent: :destroy, class_name: '::Channel::Email' has_many :api_channels, dependent: :destroy, class_name: '::Channel::Api' has_many :canned_responses, dependent: :destroy has_many :webhooks, dependent: :destroy has_many :labels, dependent: :destroy has_many :notification_settings, dependent: :destroy has_many :hooks, dependent: :destroy, class_name: 'Integrations::Hook' has_many :working_hours, dependent: :destroy has_many :kbase_portals, dependent: :destroy, class_name: '::Kbase::Portal' has_many :kbase_categories, dependent: :destroy, class_name: '::Kbase::Category' has_many :kbase_articles, dependent: :destroy, class_name: '::Kbase::Article' has_many :teams, dependent: :destroy has_many :custom_filters, dependent: :destroy has_many :custom_attribute_definitions, dependent: :destroy has_flags ACCOUNT_SETTINGS_FLAGS.merge(column: 'settings_flags').merge(DEFAULT_QUERY_SETTING) enum locale: LANGUAGES_CONFIG.map { |key, val| [val[:iso_639_1_code], key] }.to_h after_create_commit :notify_creation def agents users.where(account_users: { role: :agent }) end def administrators users.where(account_users: { role: :administrator }) end def all_conversation_tags # returns array of tags conversation_ids = conversations.pluck(:id) ActsAsTaggableOn::Tagging.includes(:tag) .where(context: 'labels', taggable_type: 'Conversation', taggable_id: conversation_ids) .map { |_| _.tag.name } end def webhook_data { id: id, name: name } end def inbound_email_domain domain || GlobalConfig.get('MAILER_INBOUND_EMAIL_DOMAIN')['MAILER_INBOUND_EMAIL_DOMAIN'] || ENV.fetch('MAILER_INBOUND_EMAIL_DOMAIN', false) end def support_email super || GlobalConfig.get('MAILER_SUPPORT_EMAIL')['MAILER_SUPPORT_EMAIL'] || ENV.fetch('MAILER_SENDER_EMAIL', 'Chatwoot <[email protected]>') end private def notify_creation Rails.configuration.dispatcher.dispatch(ACCOUNT_CREATED, Time.zone.now, account: self) end trigger.after(:insert).for_each(:row) do "execute format('create sequence IF NOT EXISTS conv_dpid_seq_%s', NEW.id);" end trigger.name('camp_dpid_before_insert').after(:insert).for_each(:row) do "execute format('create sequence IF NOT EXISTS camp_dpid_seq_%s', NEW.id);" end end
36.97479
149
0.699091
182b6310236bbe4ae41c338e2d61a23f031c34ae
1,363
# # Cookbook Name:: chef-client # Recipe:: windows_service # # Author:: Julian Dunn (<[email protected]>) # # Copyright 2013, Opscode, 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. # class ::Chef::Recipe include ::Opscode::ChefClient::Helpers end # Fall back to winsw on older Chef Clients without the service manager if Gem::Requirement.new('< 11.5').satisfied_by?(Gem::Version.new(::Chef::VERSION)) include_recipe 'chef-client::winsw_service' else # libraries/helpers.rb method to DRY directory creation resources create_directories # Will also avoid touching any winsw service if it exists execute 'register-chef-service' do command 'chef-service-manager -a install' only_if { WMI::Win32_Service.find(:first, :conditions => { :name => 'chef-client' }).nil? } end service 'chef-client' do action [:enable, :start] end end
31.697674
95
0.735143
e91bd0710db8f4fa76d340bc715f7e27e14e9a4e
1,519
class SongsController < ApplicationController before_action :set_song, only: [:show, :edit, :update, :destroy] before_action :login_user, except: [:show, :index] before_action :verify_song_user, only: [:edit, :update, :destroy] def new @song = Song.new @chords = Chord.all end def index @songs = Song.all end def create # raise params @song = Song.new(song_params) @song.user = current_user if @song.save redirect_to song_path(@song) else redirect_to root_path end end def show @user = User.find_by(id: params[:id]) end def edit @chords = Chord.all end def update # raise params.inspect if @song.update(song_params) redirect_to song_path(@song) elsif @song.song_chords.update redirect_to song_path(@song) else redirect to edit_song_path end end def destroy @song.destroy respond_to do |format| format.html { redirect_to user_path(current_user), notice: 'song was successfully destroyed.' } end end private def song_params params.require(:song).permit( :title, :artist, :key, :tuning, :difficulty, :capo, :lyrics, :user_id, chord_ids:[], chords_attributes:[:name, :img] ) end def verify_song_user redirect_to user_path(current_user) if @song.user != current_user end def verify_song redirect_to user_path(current_user) if @song.user != current_user end end
19.474359
69
0.640553
bb25244fb78b95c63ae0e711aac27d3c00cc46ae
1,068
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Resources::Mgmt::V2019_05_10 module Models # # HTTP message. # class HttpMessage include MsRestAzure # @return HTTP message content. attr_accessor :content # # Mapper for HttpMessage class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'HttpMessage', type: { name: 'Composite', class_name: 'HttpMessage', model_properties: { content: { client_side_validation: true, required: false, serialized_name: 'content', type: { name: 'Object' } } } } } end end end end
22.723404
70
0.530899
61347713513a3f50d2c87d6a68620df17bc87540
1,602
# == Schema Information # # Table name: groups # # id :integer not null, primary key # name :string(255) not null # slug :string(255) not null # bio :string(255) default(""), not null # about :text default(""), not null # avatar_file_name :string(255) # avatar_content_type :string(255) # avatar_file_size :integer # avatar_updated_at :datetime # cover_image_file_name :string(255) # cover_image_content_type :string(255) # cover_image_file_size :integer # cover_image_updated_at :datetime # confirmed_members_count :integer default(0) # created_at :datetime # updated_at :datetime # avatar_processing :boolean # about_formatted :text # require 'test_helper' class GroupTest < ActiveSupport::TestCase should validate_uniqueness_of(:name).case_insensitive should validate_presence_of(:name) test "creating new with admin" do group = Group.new_with_admin({name: 'Sugar Water'}, users(:josh)) assert_equal true, group.valid?, "Group should be valid" assert_equal true, group.save, "Group should save properly" assert_equal users(:josh).id, group.members.first.user.id, "User should be admin" assert_equal false, group.members.first.pending, "Membership should not be pending" end test "admin cannot resign if there are no other admins" do group = groups(:gumi) assert_equal false, group.can_admin_resign? end end
34.826087
87
0.637953
1825d445d864c6f0cb9ea65862829c08d04a8890
5,582
require 'chef/provider/lwrp_base' require 'shellwords' require_relative 'helpers' extend Opscode::Mysql::Helpers class Chef class Provider class MysqlService class Suse < Chef::Provider::MysqlService use_inline_resources if defined?(use_inline_resources) def whyrun_supported? true end action :create do converge_by 'suse pattern' do package 'mysql' do action :install end file '/etc/mysqlaccess.conf' do action :delete end file '/etc/mysql/default_plugins.cnf' do action :delete end file '/etc/mysql/secure_file_priv.conf' do action :delete end directory '/etc/mysql/conf.d' do owner 'mysql' group 'mysql' mode '0750' recursive true action :create end directory '/var/run/mysql' do owner 'mysql' group 'mysql' mode '0755' recursive true action :create end directory new_resource.data_dir do owner 'mysql' group 'mysql' mode '0755' recursive true action :create end template '/etc/my.cnf' do if new_resource.template_source.nil? source "#{new_resource.version}/my.cnf.erb" cookbook 'mysql' else source new_resource.template_source end owner 'mysql' group 'mysql' mode '0600' variables( :data_dir => new_resource.data_dir, :include_dir => '/etc/mysql/conf.d', :pid_file => '/var/run/mysql/mysql.pid', :port => new_resource.port, :socket_file => '/var/lib/mysql/mysql.sock' ) action :create notifies :run, 'bash[move mysql data to datadir]' notifies :restart, 'service[mysql]' end execute 'initialize mysql database' do cwd new_resource.data_dir command '/usr/bin/mysql_install_db --user=mysql' creates "#{new_resource.data_dir}/mysql/user.frm" action :run end service 'mysql' do supports :restart => true, :reload => true action [:start, :enable] notifies :run, 'execute[wait for mysql]', :immediately end execute 'wait for mysql' do command 'until [ -S /var/lib/mysql/mysql.sock ] ; do sleep 1 ; done' timeout 10 action :nothing end template '/etc/mysql_grants.sql' do cookbook 'mysql' source 'grants/grants.sql.erb' owner 'root' group 'root' mode '0600' variables(:config => new_resource) action :create notifies :run, 'execute[install-grants]' end if new_resource.server_root_password.empty? pass_string = '' else pass_string = '-p' + Shellwords.escape(new_resource.server_root_password) end pass_string = '-p' + ::File.open('/etc/.mysql_root').read.chomp if ::File.exist?('/etc/.mysql_root') execute 'install-grants' do cmd = '/usr/bin/mysql' cmd << ' -u root ' cmd << "#{pass_string} < /etc/mysql_grants.sql" command cmd action :nothing notifies :run, 'execute[create root marker]' end bash 'move mysql data to datadir' do user 'root' code <<-EOH service mysql stop \ && for i in `ls /var/lib/mysql | grep -v mysql.sock` ; do mv /var/lib/mysql/$i #{new_resource.data_dir} ; done EOH action :nothing creates "#{new_resource.data_dir}/ibdata1" creates "#{new_resource.data_dir}/ib_logfile0" creates "#{new_resource.data_dir}/ib_logfile1" end execute 'assign-root-password' do cmd = '/usr/bin/mysqladmin' cmd << ' -u root password ' cmd << Shellwords.escape(new_resource.server_root_password) command cmd action :run only_if "/usr/bin/mysql -u root -e 'show databases;'" end execute 'create root marker' do cmd = '/bin/echo' cmd << " '#{Shellwords.escape(new_resource.server_root_password)}'" cmd << ' > /etc/.mysql_root' cmd << ' ;/bin/chmod 0600 /etc/.mysql_root' command cmd action :nothing end end end end action :restart do converge_by 'suse pattern' do service 'mysql' do supports :restart => true action :restart end end end action :reload do converge_by 'suse pattern' do service 'mysql' do supports :reload => true action :reload end end end end end end Chef::Platform.set :platform => :suse, :resource => :mysql_service, :provider => Chef::Provider::MysqlService::Suse
30.502732
124
0.49588
7a8d5e99b5b95b0bf3bf78ff6a4986b6caed9f05
2,912
require 'action_cable_client' require 'dotenv/load' Dotenv.load('/home/pi/pi_client/.env') PI = ENV['PLATFORM'] == 'PI' require 'rpi_gpio' if PI # cron job reboots pi nightly # cron job checks most recent ping every minute, pkill job and relaunch EventMachine.run do Dotenv.load('/home/pi/pi_client/.env') latest_ping_timestamp = 0 RPi::GPIO.set_numbering :board if PI # Use pin number printed on board THIS_DEVICE_GUID = ENV['DEVICE_GUID'] PIN_NUM = 11 puts "Device GUID: #{THIS_DEVICE_GUID}, Pin: #{PIN_NUM}, PI: #{PI}" base_url = "#{ENV['HTTP_AUTH_USER']}:#{ENV['HTTP_AUTH_PASS']}@#{ENV['CONTROLLER_URL']}" status_url = "http://#{base_url}/api/v1/event_logs/1" websocket_url = "wss://#{base_url}/cable/" puts "URL: #{websocket_url}" RPi::GPIO.setup PIN_NUM, as: :output if PI RPi::GPIO.set_low PIN_NUM if PI client = ActionCableClient.new(websocket_url, 'EventChannel') client.connected { puts 'successfully connected.' } # Required to trigger subscription # called whenever a message is received from the server client.received(false) do | message | if message['type'] && message['type'] == 'ping' # puts "#{Time.current} PING" latest_ping_timestamp = message['message'] File.write('/ramdisk/ping', latest_ping_timestamp) if PI # an external job watches this file, and if the ping gets old it kills this script and reruns it else puts message device_guid = message['message']['device_guid'] event_code = message['message']['event_code'] state_code = message['message']['state_code'] event_log_id = message['message']['event_log_id'] if THIS_DEVICE_GUID == device_guid && state_code == 'ON' puts "Power ON" RPi::GPIO.set_high PIN_NUM if PI sleep(0.5) RPi::GPIO.set_low PIN_NUM if PI response_dt = Time.current client.perform('response', { response_dt: response_dt, response: "OK", event_log_id: event_log_id, device_guid: THIS_DEVICE_GUID }) end end end client.subscribed do puts "#{Time.current} Subscribed" end client.disconnected do puts "#{Time.current} DISCONNECTED" RPi::GPIO.clean_up if PI end client.errored do | message | puts "#{Time.current} ERROR" puts message RPi::GPIO.clean_up if PI end EM.add_periodic_timer(10) do if (Time.current.to_i - latest_ping_timestamp > 10) || !client.subscribed? puts "#{Time.current} No recent pings" RPi::GPIO.clean_up if PI abort("Disconnected, exiting...") # Ideally we would reconnect to the websocket, but I couldn't figure that out client.instance_variable_set("@_websocket_client", EventMachine::WebSocketClient.connect(client._uri)) client.connected { puts "Attempting to reconnect..." } client.subscribed { puts "Subscribed" } end RPi::GPIO.set_low PIN_NUM if PI # Ensure pin never gets stuck HIGH end end
37.818182
159
0.690247
e26ebbacb9c42f31785b49a9928f4289bccff3f0
9,573
# typed: false # frozen_string_literal: true describe "globally-scoped helper methods" do let(:dir) { mktmpdir } def esc(code) /(\e\[\d+m)*\e\[#{code}m/ end describe "#ofail" do it "sets Homebrew.failed to true" do expect { ofail "foo" }.to output("Error: foo\n").to_stderr expect(Homebrew).to have_failed end end describe "#odie" do it "exits with 1" do expect(self).to receive(:exit).and_return(1) expect { odie "foo" }.to output("Error: foo\n").to_stderr end end describe "#pretty_installed" do subject(:pretty_installed_output) { pretty_installed("foo") } context "when $stdout is a TTY" do before { allow($stdout).to receive(:tty?).and_return(true) } context "with HOMEBREW_NO_EMOJI unset" do it "returns a string with a colored checkmark" do expect(pretty_installed_output) .to match(/#{esc 1}foo #{esc 32}✔#{esc 0}/) end end context "with HOMEBREW_NO_EMOJI set" do before { ENV["HOMEBREW_NO_EMOJI"] = "1" } it "returns a string with colored info" do expect(pretty_installed_output) .to match(/#{esc 1}foo \(installed\)#{esc 0}/) end end end context "when $stdout is not a TTY" do before { allow($stdout).to receive(:tty?).and_return(false) } it "returns plain text" do expect(pretty_installed_output).to eq("foo") end end end describe "#pretty_uninstalled" do subject(:pretty_uninstalled_output) { pretty_uninstalled("foo") } context "when $stdout is a TTY" do before { allow($stdout).to receive(:tty?).and_return(true) } context "with HOMEBREW_NO_EMOJI unset" do it "returns a string with a colored checkmark" do expect(pretty_uninstalled_output) .to match(/#{esc 1}foo #{esc 31}✘#{esc 0}/) end end context "with HOMEBREW_NO_EMOJI set" do before { ENV["HOMEBREW_NO_EMOJI"] = "1" } it "returns a string with colored info" do expect(pretty_uninstalled_output) .to match(/#{esc 1}foo \(uninstalled\)#{esc 0}/) end end end context "when $stdout is not a TTY" do before { allow($stdout).to receive(:tty?).and_return(false) } it "returns plain text" do expect(pretty_uninstalled_output).to eq("foo") end end end describe "#interactive_shell" do let(:shell) { dir/"myshell" } it "starts an interactive shell session" do File.write shell, <<~SH #!/bin/sh echo called > "#{dir}/called" SH FileUtils.chmod 0755, shell ENV["SHELL"] = shell expect { interactive_shell }.not_to raise_error expect(dir/"called").to exist end end describe "#with_custom_locale" do it "temporarily overrides the system locale" do ENV["LC_ALL"] = "en_US.UTF-8" with_custom_locale("C") do expect(ENV.fetch("LC_ALL")).to eq("C") end expect(ENV.fetch("LC_ALL")).to eq("en_US.UTF-8") end end describe "#which" do let(:cmd) { dir/"foo" } before { FileUtils.touch cmd } it "returns the first executable that is found" do cmd.chmod 0744 expect(which(File.basename(cmd), File.dirname(cmd))).to eq(cmd) end it "skips non-executables" do expect(which(File.basename(cmd), File.dirname(cmd))).to be_nil end it "skips malformed path and doesn't fail" do # 'which' should not fail if a path is malformed # see https://github.com/Homebrew/legacy-homebrew/issues/32789 for an example cmd.chmod 0744 # ~~ will fail because ~foo resolves to foo's home and there is no '~' user path = ["~~", File.dirname(cmd)].join(File::PATH_SEPARATOR) expect(which(File.basename(cmd), path)).to eq(cmd) end end describe "#which_all" do let(:cmd1) { dir/"foo" } let(:cmd2) { dir/"bar/foo" } let(:cmd3) { dir/"bar/baz/foo" } before do (dir/"bar/baz").mkpath FileUtils.touch cmd2 [cmd1, cmd3].each do |cmd| FileUtils.touch cmd cmd.chmod 0744 end end it "returns an array of all executables that are found" do path = [ "#{dir}/bar/baz", "#{dir}/baz:#{dir}", "~baduserpath", ].join(File::PATH_SEPARATOR) expect(which_all("foo", path)).to eq([cmd3, cmd1]) end end specify "#which_editor" do ENV["HOMEBREW_EDITOR"] = "vemate -w" ENV["HOMEBREW_PATH"] = dir editor = "#{dir}/vemate" FileUtils.touch editor FileUtils.chmod 0755, editor expect(which_editor).to eq("vemate -w") end specify "#gzip" do mktmpdir do |path| somefile = path/"somefile" FileUtils.touch somefile expect(gzip(somefile)[0].to_s).to eq("#{somefile}.gz") expect(Pathname.new("#{somefile}.gz")).to exist end end specify "#capture_stderr" do err = capture_stderr do $stderr.print "test" end expect(err).to eq("test") end describe "#pretty_duration" do it "converts seconds to a human-readable string" do expect(pretty_duration(1)).to eq("1 second") expect(pretty_duration(2.5)).to eq("2 seconds") expect(pretty_duration(42)).to eq("42 seconds") expect(pretty_duration(240)).to eq("4 minutes") expect(pretty_duration(252.45)).to eq("4 minutes 12 seconds") end end specify "#parse_author!" do parse_error_msg = /Unable to parse name and email/ expect(parse_author!("John Doe <[email protected]>")) .to eq({ name: "John Doe", email: "[email protected]" }) expect { parse_author!("") } .to raise_error(parse_error_msg) expect { parse_author!("John Doe") } .to raise_error(parse_error_msg) expect { parse_author!("<[email protected]>") } .to raise_error(parse_error_msg) end specify "#disk_usage_readable" do expect(disk_usage_readable(1)).to eq("1B") expect(disk_usage_readable(1000)).to eq("1000B") expect(disk_usage_readable(1024)).to eq("1KB") expect(disk_usage_readable(1025)).to eq("1KB") expect(disk_usage_readable(4_404_020)).to eq("4.2MB") expect(disk_usage_readable(4_509_715_660)).to eq("4.2GB") end describe "#number_readable" do it "returns a string with thousands separators" do expect(number_readable(1)).to eq("1") expect(number_readable(1_000)).to eq("1,000") expect(number_readable(1_000_000)).to eq("1,000,000") end end specify "#truncate_text_to_approximate_size" do glue = "\n[...snip...]\n" # hard-coded copy from truncate_text_to_approximate_size n = 20 long_s = "x" * 40 s = truncate_text_to_approximate_size(long_s, n) expect(s.length).to eq(n) expect(s).to match(/^x+#{Regexp.escape(glue)}x+$/) s = truncate_text_to_approximate_size(long_s, n, front_weight: 0.0) expect(s).to eq(glue + ("x" * (n - glue.length))) s = truncate_text_to_approximate_size(long_s, n, front_weight: 1.0) expect(s).to eq(("x" * (n - glue.length)) + glue) end describe "#odeprecated" do it "raises a MethodDeprecatedError when `disable` is true" do ENV.delete("HOMEBREW_DEVELOPER") expect { odeprecated( "method", "replacement", caller: ["#{HOMEBREW_LIBRARY}/Taps/homebrew/homebrew-core/"], disable: true ) }.to raise_error( MethodDeprecatedError, %r{method.*replacement.*homebrew/core.*/Taps/homebrew/homebrew-core/}m, ) end end describe "#with_env" do it "sets environment variables within the block" do expect(ENV.fetch("PATH")).not_to eq("/bin") with_env(PATH: "/bin") do expect(ENV.fetch("PATH", nil)).to eq("/bin") end end it "restores ENV after the block" do with_env(PATH: "/bin") do expect(ENV.fetch("PATH", nil)).to eq("/bin") end path = ENV.fetch("PATH", nil) expect(path).not_to be_nil expect(path).not_to eq("/bin") end it "restores ENV if an exception is raised" do expect { with_env(PATH: "/bin") do raise StandardError, "boom" end }.to raise_error(StandardError) path = ENV.fetch("PATH", nil) expect(path).not_to be_nil expect(path).not_to eq("/bin") end end describe "#tap_and_name_comparison" do describe "both strings are only names" do it "alphabetizes the strings" do expect(%w[a b].sort(&tap_and_name_comparison)).to eq(%w[a b]) expect(%w[b a].sort(&tap_and_name_comparison)).to eq(%w[a b]) end end describe "both strings include tap" do it "alphabetizes the strings" do expect(%w[a/z/z b/z/z].sort(&tap_and_name_comparison)).to eq(%w[a/z/z b/z/z]) expect(%w[b/z/z a/z/z].sort(&tap_and_name_comparison)).to eq(%w[a/z/z b/z/z]) expect(%w[z/a/z z/b/z].sort(&tap_and_name_comparison)).to eq(%w[z/a/z z/b/z]) expect(%w[z/b/z z/a/z].sort(&tap_and_name_comparison)).to eq(%w[z/a/z z/b/z]) expect(%w[z/z/a z/z/b].sort(&tap_and_name_comparison)).to eq(%w[z/z/a z/z/b]) expect(%w[z/z/b z/z/a].sort(&tap_and_name_comparison)).to eq(%w[z/z/a z/z/b]) end end describe "only one string includes tap" do it "prefers the string without tap" do expect(%w[a/z/z z].sort(&tap_and_name_comparison)).to eq(%w[z a/z/z]) expect(%w[z a/z/z].sort(&tap_and_name_comparison)).to eq(%w[z a/z/z]) end end end end
28.661677
86
0.617257
794c02b174f76c7c57f278f9ece8bee39a222e2a
435
Rails.application.routes.draw do # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html root 'home#index' namespace :api do resources :games, only: [:index, :show, :create, :update] resources :ends, only: [:index, :create, :update] resources :shots, except: [:new, :show] resources :stats, only: [:show] resources :teams, only: [:index, :create] end end
29
102
0.671264
bff8ed55f3365cbf9d093a170354a8b413455044
873
class Hexedit < Formula desc "View and edit files in hexadecimal or ASCII" homepage "http://rigaux.org/hexedit.html" url "http://rigaux.org/hexedit-1.2.13.src.tgz" sha256 "6a126da30a77f5c0b08038aa7a881d910e3b65d13767fb54c58c983963b88dd7" bottle do cellar :any sha256 "4fd961580544c94e94e0d8099a429d94b278cf29832c8959f1f6d6eedbe59cbf" => :yosemite sha256 "2c1122682c502ffb24957f6a76da4d616b72e592ae1b4f8eedf3079f143c81a9" => :mavericks sha256 "f6627519d855ecb6cbe3dac2b4b770ee191c4f12e001534162b3c5f2ca188ba4" => :mountain_lion end def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--mandir=#{man}" system "make", "install" end test do shell_output("#{bin}/hexedit -h 2>&1", 1) end end
33.576923
95
0.681558
e25ce025614d4550aab2d329a2c956b49da5659e
6,405
module ProfilesControllerConcern extend ActiveSupport::Concern include ProfilePathConcern include SearchConcern include LoginConcern included do before_action :set_profile, only: [:show, :edit, :update, :destroy] end def new @profile = Profile.new profile_set_flag(@profile) if is_new_user? @profile.email = current_user_email end render 'profiles/new' end def edit render 'profiles/edit' end def create @profile = Profile.new(profile_params) profile_set_flag(@profile) if is_new_user? @profile.email = current_user_email end @profile.hidden_tags = ['NEW PROFILE', 'FOR REVIEW', Date.today.to_s] if @profile.save # if is a new user, re-login to force his new level. # Otherwise the user can create new profiles ad-nauseam if is_new_user? login_user(current_user) end redirect_to profile_path(@profile), notice: "#{profile_resource_name} was succesfully created" else render 'profiles/new' end end def update @profile.assign_attributes(profile_params) @profile.append_hidden_tags_value 'SELF UPDATED' if !is_user_level_fellow? @profile.append_hidden_tags_value 'PROMOTED' if @profile.flags_changed? and @profile.is_volunteer? if @profile.save redirect_to detect_profile_path(@profile), notice: "#{profile_resource_name} was succesfully updated" else render 'profiles/edit' end end def destroy @profile.destroy redirect_to profiles_path, notice: "#{profile_resource_name} was succesfully deleted" end def index @profile_search_presenter = ProfileSearchPresenter.new @profiles = profiles_scope.order(:full_name).paginate(page: params[:page]) render 'profiles/index' end def show @memberships = @profile.memberships.includes(:project).paginate(page: params[:memberships_page]) if @profile.has_email?(current_user_email) @status_reports = @profile.status_reports.paginate(page: params[:status_reports_page]) render 'profiles/me' else render 'profiles/show' end end def search @profile_search_presenter = ProfileSearchPresenter.new search_params if @profile_search_presenter.blank? redirect_to profiles_path return end profiles = profiles_scope profiles = chain_where_like(profiles, 'full_name', @profile_search_presenter.full_name); profiles = chain_where_like(profiles, 'email', @profile_search_presenter.email); profiles = chain_where_like(profiles, 'location', @profile_search_presenter.location); unless @profile_search_presenter.attrs.blank? # attrs is a mixed value: tags, skills and title # two of them are arrays, one is string. Enjoy # transform attrs into tags (split, upercase, no spaces) tags = @profile_search_presenter.attrs.split(/\,|;/).map {|x| x.strip.upcase} # positive vs. negative pos_tags, neg_tags = split_tags_pos_neg(tags) tags_sql, tags_opts = define_where_fragment_array_pos_neg("tags", pos_tags, neg_tags) hidden_tags_sql, hidden_tags_opts = define_where_fragment_array_pos_neg("hidden_tags", pos_tags, neg_tags) skills_sql, skills_opts = define_where_fragment_array_pos_neg("skills", pos_tags, neg_tags) # for title we not consider negative tags as it would qualify everything title_sql, title_opts = define_where_fragment_like_pos_neg('title', pos_tags, []) sql = "(#{tags_sql}) OR (#{hidden_tags_sql}) OR (#{skills_sql})" opts = tags_opts.concat(hidden_tags_opts).concat(skills_opts) unless title_opts.blank? sql += " OR (#{title_sql})" opts = opts.concat(title_opts) end profiles = profiles.where(sql, *opts) end @profiles = profiles.order(:full_name) render 'profiles/search' end private def search_params params.fetch(:profile_search_presenter, {}).permit( :full_name, :email, :location, :attrs) end def set_profile @profile = profiles_scope.find params[:id] end def profile_params permitted = [ :full_name, :nick_name, :photo, :tags_string, :skills_string, :contacts_string, :location, :title, :workplace, :email, :description, :urls_string] if is_user_level_fellow? permitted << :flags permitted << :status permitted << :hidden_tags_string end params.fetch(:profile, {}).permit permitted end def authorization_required_or_self redirect_to login_path if !is_user_logged_in? or ( !is_user_level_authorized?(LoginConcern::USER_LEVEL_FELLOW) and [email protected]_email?(current_user_email)) end def authorization_required_or_new_user redirect_to login_path if !is_user_logged_in? or ( !is_user_level_authorized?(LoginConcern::USER_LEVEL_FELLOW) and !is_new_user?) end module ClassMethods def profile_controller(controller, resource_name) controller_path = "#{controller}_path" controller_edit_path = "edit_#{controller}_path" controller_new_path = "new_#{controller}_path" controllers_search_path = "search_#{controller}s_path" controllers_path = "#{controller}s_path" controller_scope = "#{controller}s" profile_flag = "Profile::PROFILE_FLAG_#{controller.upcase}".constantize # Define the route helpers as aliases of the current type helper_method :profile_path, :profiles_path, :edit_profile_path, :new_profile_path, :search_profiles_path define_method 'profile_path' do |profile| send(controller_path, profile) end define_method 'profiles_path' do send(controllers_path) end define_method 'new_profile_path' do send(controller_new_path) end define_method 'edit_profile_path' do |profile| send(controller_edit_path, profile) end define_method 'search_profiles_path' do send(controllers_search_path) end helper_method :profile_resource_name define_method 'profile_resource_name' do resource_name end define_method 'profiles_scope' do Profile.send(controller_scope) end define_method 'profile_set_flag' do |profile| profile.flags = profile_flag end end end end
29.113636
112
0.697112
1d399a49202c59f8b68b531cd9c631af76246401
522
Rails::Engine.class_eval do rake_tasks do next if self.is_a?(Rails::Application) next unless has_data_migrations? namespace railtie_name do namespace :install do desc "Copy data_migrations from #{railtie_name} to application" task :data_migrations do ENV["FROM"] = railtie_name Rake::Task["railties:install:data_migrations"].invoke end end end end protected def has_data_migrations? paths["db/data_migrations"].existent.any? end end
22.695652
71
0.676245
d5083dca7457e35d2113a34dde8f470237c30634
1,001
Pod::Spec.new do |s| s.version = "2.3.1" s.source = { :http => "https://download.avoscloud.com/sdk/iOS/release-v#{s.version}/AVOSCloud.framework.zip"} s.platform = :ios, '5.0' s.name = "AVOSCloud" s.summary = "AVOS Cloud iOS SDK for mobile backend." s.homepage = "http://avoscloud.com" s.license = { :type => 'Commercial', :text => '© Copyright 2013 AVOS Systems, Inc. See https://cn.avoscloud.com/terms.html' } s.author = { "AVOS Cloud" => "[email protected]" } s.documentation_url = 'https://cn.avoscloud.com/docs/api/iOS/index.html' s.requires_arc = true s.preserve_paths = "iOS/release-v#{s.version}/*" s.vendored_frameworks = "iOS/release-v#{s.version}/AVOSCloud.framework" s.public_header_files = "iOS/release-v#{s.version}/**/*.h" s.frameworks = 'CFNetwork', 'SystemConfiguration', 'MobileCoreServices', 'CoreTelephony', 'CoreLocation', 'CoreGraphics', 'Security', 'QuartzCore' end
41.708333
149
0.632368