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
b96c30ee91f284acf238e6eac175a273255445be
1,741
class Xmrig < Formula desc "Monero (XMR) CPU miner" homepage "https://github.com/xmrig/xmrig" url "https://github.com/xmrig/xmrig/archive/v6.7.1.tar.gz" sha256 "72202ba211a7554b9a45bb1f633dcf132656fcdb83a778f1754d08d6988ec672" license "GPL-3.0-or-later" head "https://github.com/xmrig/xmrig.git" livecheck do url :stable strategy :github_latest end bottle do sha256 "a412718e6cd444149d1c3085cd2bb9954f3423043a747bdf3fc204d83a911319" => :big_sur sha256 "b1a9fb58c8e4d71a89bef45bd1c92427b437066ead44f66a9b692ec6425bc722" => :arm64_big_sur sha256 "0dbd6d5c3ca86dfd17c4fc221162ca95b31ce60947808f602a4bebfb5c439fdb" => :catalina sha256 "906bff824a7b0bb4bfed5120a0972074bcd487c0e76c349e9d59f38c26e07524" => :mojave end depends_on "cmake" => :build depends_on "hwloc" depends_on "libmicrohttpd" depends_on "libuv" depends_on "[email protected]" def install mkdir "build" do system "cmake", "..", "-DWITH_CN_GPU=OFF", *std_cmake_args system "make" bin.install "xmrig" end pkgshare.install "src/config.json" end test do assert_match version.to_s, shell_output("#{bin}/xmrig -V") test_server="donotexist.localhost:65535" timeout=10 begin read, write = IO.pipe pid = fork do exec "#{bin}/xmrig", "--no-color", "--max-cpu-usage=1", "--print-time=1", "--threads=1", "--retries=1", "--url=#{test_server}", out: write end start_time=Time.now loop do assert (Time.now - start_time <= timeout), "No server connect after timeout" break if read.gets.include? "#{test_server} DNS error: \"unknown node or service\"" end ensure Process.kill("SIGINT", pid) end end end
31.089286
95
0.688685
bf70bff4fd20a8fec00ce67c781a1a47ca6ea3e3
10,233
# # Copyright 2012-2014 Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'fileutils' require 'open-uri' require 'ruby-progressbar' module Omnibus class NetFetcher < Fetcher # Use 7-zip to extract 7z/zip for Windows WIN_7Z_EXTENSIONS = %w(.7z .zip) # tar probably has compression scheme linked in, otherwise for tarballs TAR_EXTENSIONS = %w(.tar .tar.gz .tgz .bz2 .tar.xz .txz) # # A fetch is required if the downloaded_file (such as a tarball) does not # exist on disk, or if the checksum of the downloaded file is different # than the given checksum. # # @return [true, false] # def fetch_required? unless File.exist?(downloaded_file) return true end unless digest(downloaded_file, :md5) == checksum return true end if command = verify_command log.info(log_key) { "Verifying `#{downloaded_file}' vs `#{Config.source_dir}'" } if shellout(command).error? return true end end return false end # # The version identifier for this remote location. This is computed using # the name of the software, the version of the software, and the checksum. # # @return [String] # def version_guid "md5:#{checksum}" end # # Clean the project directory by removing the contents from disk. # # @return [true, false] # true if the project directory was removed, false otherwise # def clean if File.exist?(project_dir) log.info(log_key) { "Cleaning project directory `#{project_dir}'" } FileUtils.rm_rf(project_dir) extract true else extract false end end # # Fetch the given software definition. This method **always** fetches the # file, even if it already exists on disk! You should use {#fetch_required?} # to guard against this check in your implementation. # # @return [void] # def fetch log.info(log_key) { "Downloading from `#{download_url}'" } create_required_directories download verify_checksum! extract end # # The version for this item in the cache. The is the md5 of downloaded file # and the URL where it was downloaded from. # # @return [String] # def version_for_cache "download_url:#{source[:url]}|md5:#{source[:md5]}" end # # Returned the resolved version for the manifest. Since this is a # remote URL, there is no resolution, the version is what we said # it is. # # @return [String] # def self.resolve_version(version, source) version end # # The path on disk to the downloaded asset. This method requires the # presence of a +source_uri+. # # @return [String] # def downloaded_file filename = File.basename(source[:url], '?*') File.join(Config.cache_dir, filename) end # # The checksum (+md5+) as defined by the user in the software definition. # # @return [String] # def checksum source[:md5] end private # # The URL from which to download the software - this comes from the # software's +source :url+ value. # # If S3 caching is enabled, this is the download URL for the software from # the S3 bucket as defined in the {Config}. # # @return [String] # def download_url if Config.use_s3_caching "http://#{Config.s3_bucket}.s3.amazonaws.com/#{S3Cache.key_for(self)}" else source[:url] end end # # Download the given file using Ruby's +OpenURI+ implementation. This method # may emit warnings as defined in software definitions using the +:warning+ # key. # # @return [void] # def download log.warn(log_key) { source[:warning] } if source.key?(:warning) options = download_headers if source[:unsafe] log.warn(log_key) { "Permitting unsafe redirects!" } options[:allow_unsafe_redirects] = true end options[:read_timeout] = Omnibus::Config.fetcher_read_timeout fetcher_retries ||= Omnibus::Config.fetcher_retries progress_bar = ProgressBar.create( output: $stdout, format: '%e %B %p%% (%r KB/sec)', rate_scale: ->(rate) { rate / 1024 }, ) options[:content_length_proc] = ->(total) { progress_bar.total = total } options[:progress_proc] = ->(step) { progress_bar.progress = step } file = open(download_url, options) FileUtils.cp(file.path, downloaded_file) file.close rescue SocketError, Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::ENETUNREACH, Timeout::Error, OpenURI::HTTPError => e if fetcher_retries != 0 log.debug(log_key) { "Retrying failed download (#{fetcher_retries})..." } fetcher_retries -= 1 retry else log.error(log_key) { "Download failed - #{e.class}!" } raise end end # # Extract the downloaded file, using the magical logic based off of the # ending file extension. In the rare event the file cannot be extracted, it # is copied over as a raw file. # def extract if command = extract_command log.info(log_key) { "Extracting `#{downloaded_file}' to `#{Config.source_dir}'" } shellout!(command) else log.info(log_key) { "`#{downloaded_file}' is not an archive - copying to `#{project_dir}'" } if File.directory?(project_dir) # If the file itself was a directory, copy the whole thing over. This # seems unlikely, because I do not think it is a possible to download # a folder, but better safe than sorry. FileUtils.cp_r(downloaded_file, project_dir) else # In the more likely case that we got a "regular" file, we want that # file to live **inside** the project directory. FileUtils.mkdir_p(project_dir) FileUtils.cp(downloaded_file, "#{project_dir}/") end end end # # Verify the downloaded file has the correct checksum.# # # @raise [ChecksumMismatch] # if the checksum does not match # def verify_checksum! log.info(log_key) { 'Verifying checksum' } expected = checksum actual = digest(downloaded_file, :md5) if expected != actual raise ChecksumMismatch.new(self, expected, actual) end end # # The command to use for extracting this piece of software. # # @return [String, nil] # def extract_command if Ohai['platform'] == 'windows' && downloaded_file.end_with?(*WIN_7Z_EXTENSIONS) "7z.exe x #{windows_safe_path(downloaded_file)} -o#{Config.source_dir} -r -y" elsif Ohai['platform'] != 'windows' && downloaded_file.end_with?('.7z') "7z x #{windows_safe_path(downloaded_file)} -o#{Config.source_dir} -r -y" elsif Ohai['platform'] != 'windows' && downloaded_file.end_with?('.zip') "unzip #{windows_safe_path(downloaded_file)} -d #{Config.source_dir}" elsif downloaded_file.end_with?(*TAR_EXTENSIONS) tar_command("x") end end def verify_command # Tar is the only one we know to verify right now if downloaded_file.end_with?(*TAR_EXTENSIONS) tar_command("d") end end def tar_command(action_switch) compression_switch = 'z' if downloaded_file.end_with?('gz') compression_switch = 'j' if downloaded_file.end_with?('bz2') compression_switch = 'J' if downloaded_file.end_with?('xz') compression_switch = '' if downloaded_file.end_with?('tar') "#{tar} #{compression_switch}#{action_switch}f #{windows_safe_path(downloaded_file)} -C#{Config.source_dir}" end # # Primitively determine whether we should use gtar or tar to untar a file. # If gtar is present, we will use gtar (AIX). Otherwise, we fallback to tar. # # @return [String] # def tar Omnibus.which('gtar') ? 'gtar' : 'tar' end # # The list of headers to pass to the download. # # @return [Hash] # def download_headers {}.tap do |h| # Alright kids, sit down while grandpa tells you a story. Back when the # Internet was just a series of tubes, and you had to "dial in" using # this thing called a "modem", ancient astronaunt theorists (computer # scientists) invented gzip to compress requests sent over said tubes # and make the Internet faster. # # Fast forward to the year of broadband - ungzipping these files was # tedious and hard, so Ruby and other client libraries decided to do it # for you: # # https://github.com/ruby/ruby/blob/c49ae7/lib/net/http.rb#L1031-L1033 # # Meanwhile, software manufacturers began automatically compressing # their software for distribution as a +.tar.gz+, publishing the # appropriate checksums accordingly. # # But consider... If a software manufacturer is publishing the checksum # for a gzipped tarball, and the client is automatically ungzipping its # responses, then checksums can (read: should) never match! Herein lies # the bug that took many hours away from the lives of a once-happy # developer. # # TL;DR - Do not let Ruby ungzip our file # h['Accept-Encoding'] = 'identity' # Set the cookie if one was given h['Cookie'] = source[:cookie] if source[:cookie] end end end end
30.915408
116
0.62963
6142969f6486d7a238ed81762f46277a320bd512
799
require 'simplecov' SimpleCov.start 'rails' # Configure Rails Environment ENV["RAILS_ENV"] = "test" require File.expand_path("../dummy/config/environment.rb", __FILE__) require "rails/test_help" Rails.backtrace_cleaner.remove_silencers! # Load support files Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } # rails-dom-testing assertions doesn't like the JavaScript we inject into the page. module SilenceRailsDomTesting def assert_select(*) silence_warnings { super } end end ActionController::TestCase.class_eval do include SilenceRailsDomTesting end # Load fixtures from the engine if ActiveSupport::TestCase.method_defined?(:fixture_path=) ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__) end require 'mocha/mini_test'
24.96875
83
0.772215
e945f939d5ff55fa90b9fea58cef68f61578700e
2,457
# frozen_string_literal: true module Doorkeeper module OAuth module Authorization class Token attr_accessor :pre_auth, :resource_owner, :token class << self def build_context(pre_auth_or_oauth_client, grant_type, scopes) oauth_client = if pre_auth_or_oauth_client.respond_to?(:application) pre_auth_or_oauth_client.application elsif pre_auth_or_oauth_client.respond_to?(:client) pre_auth_or_oauth_client.client else pre_auth_or_oauth_client end Doorkeeper::OAuth::Authorization::Context.new( oauth_client, grant_type, scopes ) end def access_token_expires_in(server, context) if (expiration = server.custom_access_token_expires_in.call(context)) expiration else server.access_token_expires_in end end def refresh_token_enabled?(server, context) if server.refresh_token_enabled?.respond_to? :call server.refresh_token_enabled?.call(context) else !!server.refresh_token_enabled? end end end def initialize(pre_auth, resource_owner) @pre_auth = pre_auth @resource_owner = resource_owner end def issue_token context = self.class.build_context( pre_auth.client, Doorkeeper::OAuth::IMPLICIT, pre_auth.scopes ) @token ||= AccessToken.find_or_create_for( pre_auth.client, resource_owner.id, pre_auth.scopes, self.class.access_token_expires_in(configuration, context), false ) end def native_redirect { controller: controller, action: :show, access_token: token.plaintext_token, } end private def configuration Doorkeeper.configuration end def controller @controller ||= begin mapping = Doorkeeper::Rails::Routes.mapping[:token_info] || {} mapping[:controllers] || "doorkeeper/token_info" end end end end end end
28.241379
81
0.543346
b955ad8f9e228445547530a0b057e00d60e2ee81
710
# frozen_string_literal: true module Checkers module AI module Engine class Base attr_reader :tree_depth def initialize(tree_depth = 3) @tree_depth = tree_depth end def next_board(board) if board.jumped Board.generate_boards(board, :ai).first else decision_tree_root = Tree.build(board, tree_depth).root yield(decision_tree_root, tree_depth) decision_tree_root.children.max_by(&:score).board end end protected def max(a, b) a > b ? a : b end def min(a, b) a < b ? a : b end end end end end
18.684211
67
0.53662
0374ecc5460d9713e3557b02f271a4367a3c99b4
11,102
# frozen_string_literal: true RSpec.describe FactoryTrace::Processors::FindUnused do subject(:checker) { described_class.call(FactoryTrace::Preprocessors::ExtractDefined.call, FactoryTrace::Preprocessors::ExtractUsed.call(data)) } describe "check!" do context "when all factories are not used" do let(:data) { {} } specify do expect(checker).to eq([ {code: :used, value: 0}, {code: :unused, value: 12}, {code: :unused, factory_names: ["user"]}, {code: :unused, factory_names: ["user"], trait_name: "with_phone"}, {code: :unused, factory_names: ["user_with_defaults"]}, {code: :unused, factory_names: ["admin"]}, {code: :unused, factory_names: ["admin"], trait_name: "with_email"}, {code: :unused, factory_names: ["admin"], trait_name: "combination"}, {code: :unused, factory_names: ["manager"]}, {code: :unused, factory_names: ["company"]}, {code: :unused, factory_names: ["company"], trait_name: "with_manager"}, {code: :unused, factory_names: ["article", "post"]}, {code: :unused, factory_names: ["comment"]}, {code: :unused, trait_name: "with_address"} ]) end end context "when a factory used through alias" do let(:data) { {"post" => Set.new} } specify do expect(checker).to eq([ {code: :used, value: 1}, {code: :unused, value: 11}, {code: :unused, factory_names: ["user"]}, {code: :unused, factory_names: ["user"], trait_name: "with_phone"}, {code: :unused, factory_names: ["user_with_defaults"]}, {code: :unused, factory_names: ["admin"]}, {code: :unused, factory_names: ["admin"], trait_name: "with_email"}, {code: :unused, factory_names: ["admin"], trait_name: "combination"}, {code: :unused, factory_names: ["manager"]}, {code: :unused, factory_names: ["company"]}, {code: :unused, factory_names: ["company"], trait_name: "with_manager"}, {code: :unused, factory_names: ["comment"]}, {code: :unused, trait_name: "with_address"} ]) end end context "when a factory was used without its traits" do let(:data) { {"user" => Set.new} } specify do expect(checker).to eq([ {code: :used, value: 1}, {code: :unused, value: 11}, {code: :unused, factory_names: ["user"], trait_name: "with_phone"}, {code: :unused, factory_names: ["user_with_defaults"]}, {code: :unused, factory_names: ["admin"]}, {code: :unused, factory_names: ["admin"], trait_name: "with_email"}, {code: :unused, factory_names: ["admin"], trait_name: "combination"}, {code: :unused, factory_names: ["manager"]}, {code: :unused, factory_names: ["company"]}, {code: :unused, factory_names: ["company"], trait_name: "with_manager"}, {code: :unused, factory_names: ["article", "post"]}, {code: :unused, factory_names: ["comment"]}, {code: :unused, trait_name: "with_address"} ]) end end context "when a factory was used with its traits" do let(:data) { {"user" => Set.new(["with_phone"])} } specify do expect(checker).to eq([ {code: :used, value: 2}, {code: :unused, value: 10}, {code: :unused, factory_names: ["user_with_defaults"]}, {code: :unused, factory_names: ["admin"]}, {code: :unused, factory_names: ["admin"], trait_name: "with_email"}, {code: :unused, factory_names: ["admin"], trait_name: "combination"}, {code: :unused, factory_names: ["manager"]}, {code: :unused, factory_names: ["company"]}, {code: :unused, factory_names: ["company"], trait_name: "with_manager"}, {code: :unused, factory_names: ["article", "post"]}, {code: :unused, factory_names: ["comment"]}, {code: :unused, trait_name: "with_address"} ]) end end context "when a child factory was used" do let(:data) { {"admin" => []} } specify do expect(checker).to eq([ {code: :used, value: 2}, {code: :unused, value: 10}, {code: :unused, factory_names: ["user"], trait_name: "with_phone"}, {code: :unused, factory_names: ["user_with_defaults"]}, {code: :unused, factory_names: ["admin"], trait_name: "with_email"}, {code: :unused, factory_names: ["admin"], trait_name: "combination"}, {code: :unused, factory_names: ["manager"]}, {code: :unused, factory_names: ["company"]}, {code: :unused, factory_names: ["company"], trait_name: "with_manager"}, {code: :unused, factory_names: ["article", "post"]}, {code: :unused, factory_names: ["comment"]}, {code: :unused, trait_name: "with_address"} ]) end end context "when a global trait was used" do let(:data) { {"user" => Set.new(["with_address"])} } specify do expect(checker).to eq([ {code: :used, value: 2}, {code: :unused, value: 10}, {code: :unused, factory_names: ["user"], trait_name: "with_phone"}, {code: :unused, factory_names: ["user_with_defaults"]}, {code: :unused, factory_names: ["admin"]}, {code: :unused, factory_names: ["admin"], trait_name: "with_email"}, {code: :unused, factory_names: ["admin"], trait_name: "combination"}, {code: :unused, factory_names: ["manager"]}, {code: :unused, factory_names: ["company"]}, {code: :unused, factory_names: ["company"], trait_name: "with_manager"}, {code: :unused, factory_names: ["article", "post"]}, {code: :unused, factory_names: ["comment"]} ]) end end context "when a parent trait was used" do let(:data) { {"admin" => Set.new(["with_phone"])} } specify do expect(checker).to eq([ {code: :used, value: 3}, {code: :unused, value: 9}, {code: :unused, factory_names: ["user_with_defaults"]}, {code: :unused, factory_names: ["admin"], trait_name: "with_email"}, {code: :unused, factory_names: ["admin"], trait_name: "combination"}, {code: :unused, factory_names: ["manager"]}, {code: :unused, factory_names: ["company"]}, {code: :unused, factory_names: ["company"], trait_name: "with_manager"}, {code: :unused, factory_names: ["article", "post"]}, {code: :unused, factory_names: ["comment"]}, {code: :unused, trait_name: "with_address"} ]) end end context "when everything were used" do let(:data) { {"admin" => Set.new(["with_phone", "with_email", "combination"]), "company" => Set.new(["with_address", "with_manager"]), "article" => Set.new, "comment" => Set.new, "manager" => Set.new, "user_with_defaults" => Set.new} } specify do expect(checker).to eq([ {code: :used, value: 12}, {code: :unused, value: 0} ]) end end context "when trait is used indirectly through another trait" do let(:data) { {"admin" => Set.new(["combination"])} } specify do expect(checker).to eq([ {code: :used, value: 5}, {code: :unused, value: 7}, {code: :unused, factory_names: ["user_with_defaults"]}, {code: :unused, factory_names: ["manager"]}, {code: :unused, factory_names: ["company"]}, {code: :unused, factory_names: ["company"], trait_name: "with_manager"}, {code: :unused, factory_names: ["article", "post"]}, {code: :unused, factory_names: ["comment"]}, {code: :unused, trait_name: "with_address"} ]) end end context "when trait is used indirectly through factory" do let(:data) { {"manager" => Set.new} } specify do expect(checker).to eq([ {code: :used, value: 4}, {code: :unused, value: 8}, {code: :unused, factory_names: ["user_with_defaults"]}, {code: :unused, factory_names: ["admin"], trait_name: "with_email"}, {code: :unused, factory_names: ["admin"], trait_name: "combination"}, {code: :unused, factory_names: ["company"]}, {code: :unused, factory_names: ["company"], trait_name: "with_manager"}, {code: :unused, factory_names: ["article", "post"]}, {code: :unused, factory_names: ["comment"]}, {code: :unused, trait_name: "with_address"} ]) end end context "when factory is used indirectly through factory" do let(:data) { {"comment" => Set.new} } specify do expect(checker).to eq([ {code: :used, value: 2}, {code: :unused, value: 10}, {code: :unused, factory_names: ["user"]}, {code: :unused, factory_names: ["user"], trait_name: "with_phone"}, {code: :unused, factory_names: ["user_with_defaults"]}, {code: :unused, factory_names: ["admin"]}, {code: :unused, factory_names: ["admin"], trait_name: "with_email"}, {code: :unused, factory_names: ["admin"], trait_name: "combination"}, {code: :unused, factory_names: ["manager"]}, {code: :unused, factory_names: ["company"]}, {code: :unused, factory_names: ["company"], trait_name: "with_manager"}, {code: :unused, trait_name: "with_address"} ]) end end context "when factory is used indirectly through trait" do let(:data) { {"company" => Set.new(["with_manager"])} } specify do expect(checker).to eq([ {code: :used, value: 6}, {code: :unused, value: 6}, {code: :unused, factory_names: ["user_with_defaults"]}, {code: :unused, factory_names: ["admin"], trait_name: "with_email"}, {code: :unused, factory_names: ["admin"], trait_name: "combination"}, {code: :unused, factory_names: ["article", "post"]}, {code: :unused, factory_names: ["comment"]}, {code: :unused, trait_name: "with_address"} ]) end end context "when factory with default traits was used" do let(:data) { {"user_with_defaults" => Set.new} } specify do expect(checker).to eq([ {code: :used, value: 4}, {code: :unused, value: 8}, {code: :unused, factory_names: ["admin"]}, {code: :unused, factory_names: ["admin"], trait_name: "with_email"}, {code: :unused, factory_names: ["admin"], trait_name: "combination"}, {code: :unused, factory_names: ["manager"]}, {code: :unused, factory_names: ["company"]}, {code: :unused, factory_names: ["company"], trait_name: "with_manager"}, {code: :unused, factory_names: ["article", "post"]}, {code: :unused, factory_names: ["comment"]} ]) end end end end
42.212928
241
0.562241
d58dcd13ee62f051a109595909291b98560f6d47
4,190
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. # rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength module OCI # This class provides a wrapper around {OCI::Dts::TransferDeviceClient} and offers convenience methods # for operations that would otherwise need to be chained together. For example, instead of performing an action # on a resource (e.g. launching an instance, creating a load balancer) and then using a waiter to wait for the resource # to enter a given state, you can call a single method in this class to accomplish the same functionality class Dts::TransferDeviceClientCompositeOperations # The {OCI::Dts::TransferDeviceClient} used to communicate with the service_client # # @return [OCI::Dts::TransferDeviceClient] attr_reader :service_client # Initializes a new TransferDeviceClientCompositeOperations # # @param [OCI::Dts::TransferDeviceClient] service_client The client used to communicate with the service. # Defaults to a new service client created via {OCI::Dts::TransferDeviceClient#initialize} with no arguments def initialize(service_client = OCI::Dts::TransferDeviceClient.new) @service_client = service_client end # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/ParameterLists, Metrics/PerceivedComplexity # rubocop:disable Layout/EmptyLines # Calls {OCI::Dts::TransferDeviceClient#update_transfer_device} and then waits for the {OCI::Dts::Models::TransferDevice} acted upon # to enter the given state(s). # # @param [String] id ID of the Transfer Job # @param [String] transfer_device_label Label of the Transfer Device # @param [OCI::Dts::Models::UpdateTransferDeviceDetails] update_transfer_device_details fields to update # @param [Array<String>] wait_for_states An array of states to wait on. These should be valid values for {OCI::Dts::Models::TransferDevice#lifecycle_state} # @param [Hash] base_operation_opts Any optional arguments accepted by {OCI::Dts::TransferDeviceClient#update_transfer_device} # @param [Hash] waiter_opts Optional arguments for the waiter. Keys should be symbols, and the following keys are supported: # * max_interval_seconds: The maximum interval between queries, in seconds. # * max_wait_seconds The maximum time to wait, in seconds # # @return [OCI::Response] A {OCI::Response} object with data of type {OCI::Dts::Models::TransferDevice} def update_transfer_device_and_wait_for_state(id, transfer_device_label, update_transfer_device_details, wait_for_states = [], base_operation_opts = {}, waiter_opts = {}) operation_result = @service_client.update_transfer_device(id, transfer_device_label, update_transfer_device_details, base_operation_opts) return operation_result if wait_for_states.empty? lowered_wait_for_states = wait_for_states.map(&:downcase) wait_for_resource_id = operation_result.data.id begin waiter_result = @service_client.get_transfer_device(wait_for_resource_id).wait_until( eval_proc: ->(response) { response.data.respond_to?(:lifecycle_state) && lowered_wait_for_states.include?(response.data.lifecycle_state.downcase) }, max_interval_seconds: waiter_opts.key?(:max_interval_seconds) ? waiter_opts[:max_interval_seconds] : 30, max_wait_seconds: waiter_opts.key?(:max_wait_seconds) ? waiter_opts[:max_wait_seconds] : 1200 ) result_to_return = waiter_result return result_to_return rescue StandardError raise OCI::Errors::CompositeOperationError.new(partial_results: [operation_result]) end end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/ParameterLists, Metrics/PerceivedComplexity # rubocop:enable Layout/EmptyLines end end # rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
62.537313
245
0.765632
d5fd683368d7515d3adbce0dde3a8b53582e8831
1,437
require 'test_helper' class FamilyYearsControllerTest < ActionController::TestCase setup do @family_year = family_years(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:family_years) end test "should get new" do get :new assert_response :success end test "should create family_year" do assert_difference('FamilyYear.count') do post :create, family_year: { community_id: @family_year.community_id, family_id: @family_year.family_id, notes: @family_year.notes, picture: @family_year.picture, school_year: @family_year.school_year } end assert_redirected_to family_year_path(assigns(:family_year)) end test "should show family_year" do get :show, id: @family_year assert_response :success end test "should get edit" do get :edit, id: @family_year assert_response :success end test "should update family_year" do patch :update, id: @family_year, family_year: { community_id: @family_year.community_id, family_id: @family_year.family_id, notes: @family_year.notes, picture: @family_year.picture, school_year: @family_year.school_year } assert_redirected_to family_year_path(assigns(:family_year)) end test "should destroy family_year" do assert_difference('FamilyYear.count', -1) do delete :destroy, id: @family_year end assert_redirected_to family_years_path end end
28.74
225
0.742519
e27c73e34086805c2a77edd48f55b2c4b1784dfa
1,501
require File.dirname(__FILE__) + '/test_helper' class RoutingWithOptionalFormatsTest < Test::Unit::TestCase def setup self.class.send :include, ActionController::UrlWriter ActionController::Base.prune_routes = true end def test_should_not_define_formatted_routes_when_explicitly_disabled assert_named_route( "/articles", :articles_path ) assert_raise( NoMethodError ) do assert_named_route( "/articles.xml", :formatted_articles_path, { :format => :xml } ) end assert_named_route( "/users", :users_path ) assert_named_route( "/users.xml", :formatted_users_path, { :format => :xml } ) end def test_should_be_able_to_define_only_a_subset_of_actions assert_named_route( "/blogs/1", :blog_path, { :id => 1 } ) assert_raise( NoMethodError ) do assert_named_route( "/articles/1/edit", :edit_article_path, { :id => 1 } ) end assert_named_route( "/blogs/popular", :popular_blogs_path ) assert_named_route( "/blogs", :blogs_path ) assert_named_route("/photos/1/vote", :vote_photo_path, { :id => 1 }) assert_named_route( "/photos", :photos_path ) assert_named_route( "/photos/1", :photo_path, { :id => 1 } ) assert_raise( NoMethodError ) do assert_named_route( "/blogs/1/edit", :edit_blog_path, { :id => 1 } ) end end def assert_named_route(expected, route, options = {}) actual = send(route, options) assert_equal expected, actual, "Error on route: #{route}(#{options.inspect})" end end
38.487179
90
0.697535
089326cfd4545696254701b24bcb6eb5f8a050b4
227
module PostUsernameHelper def each_post_username(post) render 'each', post: post if user_signed_in? end def editing(post) render 'editing', post: post if current_user && current_user.id == post.user_id end end
22.7
83
0.731278
8729f95c6f2607a23637d18294d78b8b69379973
1,721
require 'test_helper' class UsersControllerTest < ActionDispatch::IntegrationTest def setup @user = users(:taro) @other_user = users(:jiro) end test "newページの表示" do get signup_path assert_response :success end test "他のユーザのeditへ" do log_in_as(@other_user) get edit_user_path(@user) assert flash.empty? assert_redirected_to root_url end test "他のユーザのupdateへ" do log_in_as(@other_user) patch user_path(@user), params: { user: { name: @user.name, email: @user.email } } assert flash.empty? assert_redirected_to root_url end test "admin属性を変更" do log_in_as(@other_user) assert_not @other_user.admin? patch user_path(@other_user), params: { user: { password: @other_user.password, password_confirmation: @other_user.password_confirmation, admin: true } } assert_not @other_user.reload.admin? end test "ログインせずindexへリダイレクト" do get users_path assert_redirected_to login_url end test "ログインせずdestroyへリダイレクト" do assert_no_difference 'User.count' do delete user_path(@user) end assert_redirected_to login_url end test "admin以外のユーザでdestroyへリダイレクト" do log_in_as(@other_user) assert_no_difference 'User.count' do delete user_path(@user) end assert_redirected_to root_url end test "ログインせずfollowingにリダイレクト" do get following_user_path(@user) assert_redirected_to login_url end test "ログインせずにfollowersへリダイレクト" do get followers_user_path(@user) assert_redirected_to login_url end end
25.308824
101
0.649041
871fed05593cc1c2619ee9d346fb75b34a323b4d
1,368
# frozen_string_literal: true ## # This file is part of WhatWeb and may be subject to # redistribution and commercial restrictions. Please see the WhatWeb # web site for more information on licensing and terms of use. # http://www.morningstarsecurity.com/research/whatweb ## WhatWeb::Plugin.define "Saman-Portal" do @author = "Brendan Coles <[email protected]>" # 2012-03-13 @version = "0.1" @description = "Saman Portal" @website = "http://www.sis-eg.com/" # ShodanHQ results as at 2012-03-13 # # 7 for SAMANPORTALSID # 3 for X-Powered-By: sisRapid Framework # Google results as at 2012-03-13 # # 89 for inurl:sismodule=user # Dorks # @dorks = [ 'inurl:sismodule=user' ] # Matches # @matches = [ # Meta Generator { text: '<meta name="Generator" content="Saman Information Structure" />' }, # Link # Version Detection { version: /<script type="text\/javascript" language="JavaScript" src="\/portlets\/sisRapid\/dream\/libs\/(V[\d\.]+)\/core\/sisValidationAPI\.js">/ }, # JavaScript { regexp: /<script type="text\/javascript" language="JavaScript">[\s]+var sisTHEMEPATH_HTTP = "/ }, # X-Powered-By: sisRapid Framework { search: "headers[server]", regexp: /sisRapid Framework/ }, # Set-Cookie # SAMANPORTALSID { search: "headers[set-cookie]", regexp: /SAMANPORTALSID=[^;]+;/ }, ] end
29.106383
155
0.665205
08afd2c0d83f55411c773fdb6fe9f360287ba048
1,177
require 'rails_helper' describe Cosmoslike::ValidatorDelegationsDecorator do let(:instance) { described_class.new(chain, validator) } let(:chain) { build(:cosmos_chain) } let(:validator) { double(id: 1, owner: 'cosmosowner123', info_field: 1000000) } let(:syncer) { double } let(:delegation) { { 'delegator_address' => 'cosmos2121', 'shares' => 5000 } } let(:unbonding) { { 'delegator_address' => 'cosmos2121', 'entries' => [{ 'balance': 1 }] } } describe '#delegations' do subject { instance.delegations } before do allow(chain).to receive(:syncer).and_return(syncer) expect(syncer).to receive(:get_validator_delegations).with(validator.owner).and_return([delegation]) expect(syncer).to receive(:get_validator_unbonding_delegations).with(validator.owner).and_return([unbonding]) expect(Rails.cache).to receive(:fetch).twice.and_call_original end it 'returns decorated delegations' do expect(subject).to eq [ { account: 'cosmos2121', amount: 0.005, share: 0.5, status: 'bonded', validator: nil }, { account: 'cosmos2121', amount: 0, status: 'unbonding', validator: nil } ] end end end
40.586207
115
0.684792
f8fc3986072923e9718719e8564d8775e54cc3e4
151
class AddEventWillSyncToGpArticleDocs < ActiveRecord::Migration[4.2] def change add_column :gp_article_docs, :event_will_sync, :string end end
25.166667
68
0.794702
11552fb9e778a265d9ecf1afe4dc2a06be0e3eb8
2,645
module ShopifyCli ## # `TransformDataStructure` helps to standardize data structure access. It # traverses nested data structures and can convert # # * all strings used as keys to symbols, # * all strings used as keys from `CamelCase` to `snake_case` and # * associative array containers, e.g. from Hash to OpenStruct. # # Standardizing how a data structure is accessed greatly reduces the risk # of subtle bugs especially when dealing with API responses. # # TransformDataStructure.new( # symbolize_keys: true, # underscore_keys: true, # associative_array_container: OpenStruct # ).call([{"SomeKey" => "value"}]).tap do |result| # result.value # => [#<OpenStruct: some_key: "value">] # end # # Since `TransformDataStructure` is a method object, it can easily be chained: # # require 'open-uri' # ShopifyCli::Result # .call { open("https://jsonplaceholder.typicode.com/todos/1") } # .map(&TransformDataStructure.new(symbolize_keys: true, underscore_keys: true)) # .value # => { id: 1, user_id: 1, ... } # class TransformDataStructure include ShopifyCli::MethodObject class << self private def valid_associative_array_container(klass) klass.respond_to?(:new) && klass.method_defined?(:[]=) end end property! :underscore_keys, accepts: [true, false], default: false, reader: :underscore_keys? property! :symbolize_keys, accepts: [true, false], default: false, reader: :symbolize_keys? property! :associative_array_container, accepts: ->(c) { c.respond_to?(:new) && c.method_defined?(:[]=) }, default: Hash def call(object) case object when Array object.map(&self).map(&:value) when Hash object.each.with_object(associative_array_container.new) do |(key, value), result| result[transform_key(key)] = call(value).value end else ShopifyCli::Result.success(object) end end private def transform_key(key) key .yield_self(&method(:underscore_key)) .yield_self(&method(:symbolize_key)) end def underscore_key(key) return key unless underscore_keys? && key.respond_to?(:to_str) key.to_str.dup.tap do |k| k.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2') k.gsub!(/([a-z\d])([A-Z])/, '\1_\2') k.tr!("-", "_") k.gsub!(/\s/, "_") k.gsub!(/__+/, "_") k.downcase! end end def symbolize_key(key) return key unless symbolize_keys? && key.respond_to?(:to_sym) key.to_sym end end end
30.402299
97
0.622684
bf43f902c76a341f52eeda1063fe281087093fb0
343
class CreateProducts < ActiveRecord::Migration[5.2] def change create_table :products do |t| t.string :name t.boolean :sold_out, default: false t.string :category t.boolean :under_sale, null: false t.integer :price t.integer :sale_price t.string :sale_text t.timestamps end end end
21.4375
51
0.64723
1ac9b6ad5c3dfd71135ed80637696bb2fef79d3a
596
require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module AwsDemos 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
31.368421
82
0.765101
bfff7edb40e6bfc0f59d4e22f62d624646f969c9
623
# frozen_string_literal: true module RelatonIso # Hit. class Hit < RelatonBib::Hit # @return [RelatonIsoBib::IsoBibliographicItem] attr_writer :fetch # Parse page. # @param lang [String, NilClass] # @return [RelatonIso::IsoBibliographicItem] def fetch(lang = nil) @fetch ||= Scrapper.parse_page @hit, lang end # @return [Integer] def sort_weight case hit[:status] # && hit["publicationStatus"]["key"] when "Published" then 0 when "Under development" then 1 when "Withdrawn" then 2 when "Deleted" then 3 else 4 end end end end
22.25
60
0.630819
e804a32b90ebb07de79ba2c6a92ab7723bca6b32
721
positive = [] for i in [1, 3, 4, 5, 1, 2].sort do if i > 0 positive.push(i) end end lowest = 1 if positive.size > 0 i = 0 loop do if (i < positive.size) if i+1 >= positive.size lowest = lowest + 1 break else diff = positive[i+1] - positive[i] if diff == 0 lowest = positive[i+1] elsif diff == 1 lowest = positive[i+1] else lowest = positive[i] end end else break end #p i i = i + 1 end end p lowest
22.53125
60
0.359223
010dc6895abd0d331e06d15eba3f803dd8b93881
3,753
# frozen_string_literal: true module RuboCop module Cop module Style # This cop checks for redundant uses of `self`. # # `self` is only needed when: # # * Sending a message to same object with zero arguments in # presence of a method name clash with an argument or a local # variable. # # Note, with using explicit self you can only send messages # with public or protected scope, you cannot send private # messages this way. # # Example: # # def bar # :baz # end # # def foo(bar) # self.bar # resolves name clash with argument # end # # def foo2 # bar = 1 # self.bar # resolves name clash with local variable # end # # * Calling an attribute writer to prevent an local variable assignment # # attr_writer :bar # # def foo # self.bar= 1 # Make sure above attr writer is called # end # # Special cases: # # We allow uses of `self` with operators because it would be awkward # otherwise. class RedundantSelf < Cop MSG = 'Redundant `self` detected.'.freeze def initialize(config = nil, options = nil) super @allowed_send_nodes = [] @local_variables_scopes = Hash.new { |hash, key| hash[key] = [] } end # Assignment of self.x def on_or_asgn(node) lhs, _rhs = *node allow_self(lhs) end alias on_and_asgn on_or_asgn def on_op_asgn(node) lhs, _op, _rhs = *node allow_self(lhs) end # Using self.x to distinguish from local variable x def on_def(node) add_scope(node) end alias on_defs on_def def on_args(node) node.children.each { |arg| on_argument(arg) } end def on_blockarg(node) on_argument(node) end def on_lvasgn(node) lhs, rhs = *node @local_variables_scopes[rhs] << lhs end def on_send(node) return unless node.self_receiver? && regular_method_call?(node) return if node.parent && node.parent.mlhs_type? return if @allowed_send_nodes.include?(node) || @local_variables_scopes[node].include?(node.method_name) add_offense(node) end def autocorrect(node) lambda do |corrector| corrector.remove(node.receiver.source_range) corrector.remove(node.loc.dot) end end private def add_scope(node) local_variables = [] node.descendants.each do |child_node| @local_variables_scopes[child_node] = local_variables end end def regular_method_call?(node) !(operator?(node.method_name) || keyword?(node.method_name) || node.camel_case_method? || node.setter_method? || node.implicit_call?) end def on_argument(node) name, = *node @local_variables_scopes[node] << name end def keyword?(method_name) %i[alias and begin break case class def defined? do else elsif end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield].include?(method_name) end def allow_self(node) return unless node.send_type? && node.self_receiver? @allowed_send_nodes << node end end end end end
25.882759
77
0.551825
edae98153d990a771ca526a53e9e7b6334a70a8a
8,026
# frozen_string_literal: true require "excon" require "nokogiri" require "dependabot/errors" require "dependabot/nuget/update_checker" require "dependabot/shared_helpers" module Dependabot module Nuget class UpdateChecker class RepositoryFinder DEFAULT_REPOSITORY_URL = "https://api.nuget.org/v3/index.json" def initialize(dependency:, credentials:, config_file: nil) @dependency = dependency @credentials = credentials @config_file = config_file end def dependency_urls find_dependency_urls end private attr_reader :dependency, :credentials, :config_file def find_dependency_urls @find_dependency_urls ||= known_repositories.flat_map do |details| if details.fetch(:url) == DEFAULT_REPOSITORY_URL # Save a request for the default URL, since we already how # it addresses packages next default_repository_details end build_url_for_details(details) end.compact.uniq end def build_url_for_details(repo_details) response = get_repo_metadata(repo_details) check_repo_reponse(response, repo_details) return unless response.status == 200 base_url = base_url_from_v3_metadata(JSON.parse(response.body)) search_url = search_url_from_v3_metadata(JSON.parse(response.body)) details = { repository_url: repo_details.fetch(:url), auth_header: auth_header_for_token(repo_details.fetch(:token)), repository_type: "v3" } if base_url details[:versions_url] = File.join(base_url, dependency.name.downcase, "index.json") end if search_url details[:search_url] = search_url + "?q=#{dependency.name.downcase}&prerelease=true" end details rescue JSON::ParserError build_v2_url(response, repo_details) rescue Excon::Error::Timeout, Excon::Error::Socket handle_timeout(repo_metadata_url: repo_details.fetch(:url)) end def get_repo_metadata(repo_details) Excon.get( repo_details.fetch(:url), headers: auth_header_for_token(repo_details.fetch(:token)), idempotent: true, **SharedHelpers.excon_defaults ) end def base_url_from_v3_metadata(metadata) metadata. fetch("resources", []). find { |r| r.fetch("@type") == "PackageBaseAddress/3.0.0" }&. fetch("@id") end def search_url_from_v3_metadata(metadata) metadata. fetch("resources", []). find { |r| r.fetch("@type") == "SearchQueryService" }&. fetch("@id") end def build_v2_url(response, repo_details) doc = Nokogiri::XML(response.body) doc.remove_namespaces! base_url = doc.at_xpath("service")&.attributes&. fetch("base", nil)&.value return unless base_url { repository_url: base_url, versions_url: File.join( base_url, "FindPackagesById()?id='#{dependency.name}'" ), auth_header: auth_header_for_token(repo_details.fetch(:token)), repository_type: "v2" } end def check_repo_reponse(response, details) return unless [401, 402, 403].include?(response.status) raise if details.fetch(:url) == DEFAULT_REPOSITORY_URL raise PrivateSourceAuthenticationFailure, details.fetch(:url) end def handle_timeout(repo_metadata_url:) raise if repo_metadata_url == DEFAULT_REPOSITORY_URL raise PrivateSourceTimedOut, repo_metadata_url end def known_repositories return @known_repositories if @known_repositories @known_repositories = [] @known_repositories += credential_repositories @known_repositories += config_file_repositories if @known_repositories.empty? @known_repositories << { url: DEFAULT_REPOSITORY_URL, token: nil } end @known_repositories.uniq end def credential_repositories @credential_repositories ||= credentials. select { |cred| cred["type"] == "nuget_feed" }. map { |c| { url: c.fetch("url"), token: c["token"] } } end # rubocop:disable Metrics/AbcSize def config_file_repositories return [] unless config_file doc = Nokogiri::XML(config_file.content) doc.remove_namespaces! sources = doc.css("configuration > packageSources > add").map do |node| { key: node.attribute("key")&.value&.strip || node.at_xpath("./key")&.content&.strip, url: node.attribute("value")&.value&.strip || node.at_xpath("./value")&.content&.strip } end sources.reject! do |s| known_urls = credential_repositories.map { |cr| cr.fetch(:url) } known_urls.include?(s.fetch(:url)) end sources.select! { |s| s.fetch(:url)&.include?("://") } add_config_file_credentials(sources: sources, doc: doc) sources.each { |details| details.delete(:key) } sources end # rubocop:enable Metrics/AbcSize def default_repository_details { repository_url: DEFAULT_REPOSITORY_URL, versions_url: "https://api.nuget.org/v3-flatcontainer/"\ "#{dependency.name.downcase}/index.json", search_url: "https://api-v2v3search-0.nuget.org/query"\ "?q=#{dependency.name.downcase}&prerelease=true", auth_header: {}, repository_type: "v3" } end def add_config_file_credentials(sources:, doc:) sources.each do |source_details| key = source_details.fetch(:key) next source_details[:token] = nil unless key next source_details[:token] = nil if key.match?(/^\d/) tag = key.gsub(" ", "_x0020_") creds_nodes = doc.css("configuration > packageSourceCredentials "\ "> #{tag} > add") username = creds_nodes. find { |n| n.attribute("key")&.value == "Username" }&. attribute("value")&.value password = creds_nodes. find { |n| n.attribute("key")&.value == "ClearTextPassword" }&. attribute("value")&.value # Note: We have to look for plain text passwords, as we have no # way of decrypting encrypted passwords. For the same reason we # don't fetch API keys from the nuget.config at all. next source_details[:token] = nil unless username && password source_details[:token] = "#{username}:#{password}" rescue Nokogiri::XML::XPath::SyntaxError # Any non-ascii characters in the tag with cause a syntax error next source_details[:token] = nil end sources end def auth_header_for_token(token) return {} unless token if token.include?(":") encoded_token = Base64.encode64(token).delete("\n") { "Authorization" => "Basic #{encoded_token}" } elsif Base64.decode64(token).ascii_only? && Base64.decode64(token).include?(":") { "Authorization" => "Basic #{token.delete("\n")}" } else { "Authorization" => "Bearer #{token}" } end end end end end end
33.58159
78
0.566658
f7373b71f4061e18d802e83b2ca0ed8927996b8c
5,539
# This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause # this file to always be loaded, without a need to explicitly require it in any # files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need # it. # # The `.rspec` file also contains a few flags that are not defaults but that # users commonly want. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true # expectations.syntax = [:should , :expect] expectations.syntax = :expect end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # This option will default to `:apply_to_host_groups` in RSpec 4 (and will # have no way to turn it off -- the option exists only for backwards # compatibility in RSpec 3). It causes shared context metadata to be # inherited by the metadata hash of host groups and examples, rather than # triggering implicit auto-inclusion in groups with matching metadata. config.shared_context_metadata_behavior = :apply_to_host_groups # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. =begin # This allows you to limit a spec run to individual examples or groups # you care about by tagging them with `:focus` metadata. When nothing # is tagged with `:focus`, all examples get run. RSpec also provides # aliases for `it`, `describe`, and `context` that include `:focus` # metadata: `fit`, `fdescribe` and `fcontext`, respectively. config.filter_run_when_matching :focus # Allows RSpec to persist some state between runs in order to support # the `--only-failures` and `--next-failure` CLI options. We recommend # you configure your source control system to ignore this file. config.example_status_persistence_file_path = "spec/examples.txt" # Limits the available syntax to the non-monkey patched syntax that is # recommended. For more details, see: # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode config.disable_monkey_patching! # This setting enables warnings. It's recommended, but in some cases may # be too noisy due to issues in dependencies. config.warnings = true # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed =end end APP_ROOT = File.expand_path('../..', __FILE__) # Some helper methods & exception blocks def no_output(&block) original_stdout = $stdout.dup $stdout.reopen('/dev/null') $stdout.sync = true begin yield ensure $stdout.reopen(original_stdout) end end def capture_output(&block) original_stdout = $stdout.dup output_catcher = StringIO.new $stdout = output_catcher begin yield ensure $stdout = original_stdout end end
42.607692
92
0.737317
871d29e474585348c869204e380d456911bddb5a
373
Sequel.migration do up do # Drop logging for multi_labels table. drop_trigger(:multi_labels, :audit_trigger_row) drop_trigger(:multi_labels, :audit_trigger_stm) end down do # Log changes to multi_labels table. Exclude changes to the updated_at column. run "SELECT audit.audit_table('multi_labels', true, true, '{updated_at}'::text[]);" end end
28.692308
87
0.729223
e84dee2d100519c6d0681a633d2194231930a605
1,228
$:.push File.expand_path("lib", __dir__) # Maintain your gem's version: require "stardust/rspec/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |spec| spec.name = "stardust-rspec" spec.version = Stardust::Rspec::VERSION spec.authors = ["Vic Amuso"] spec.email = ["[email protected]"] spec.homepage = "https://github.com/parablesoft/stardust-rspec" spec.summary = "Summary of Stardust::Rspec." spec.description = "Description of Stardust::Rspec." 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.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"] spec.add_dependency "rails", ">= 5.0" spec.add_dependency 'rspec-expectations' spec.add_development_dependency 'rspec' spec.add_development_dependency "sqlite3" end
38.375
96
0.70114
03032f213494fac608604ccd6b7b08543fc35bb3
1,055
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rails3_enum/version' Gem::Specification.new do |spec| spec.name = "rails3_enum" spec.version = Rails3Enum::VERSION spec.authors = ["Tomohisa Kuranari"] spec.email = ["[email protected]"] spec.summary = %q{Provide ActiveRecord::Enum for Rails3} spec.description = %q{Provide ActiveRecord::Enum for Rails3} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency "activerecord", "~> 3.0" spec.add_dependency 'activesupport', '~> 3.0' spec.add_development_dependency "bundler", "~> 1.5" spec.add_development_dependency "rake" spec.add_development_dependency 'rspec', '~> 3.1' spec.add_development_dependency 'sqlite3' end
37.678571
74
0.665403
1d34063b43cb3e4f40b50005aace3f170deb058c
515
require 'spec_helper' describe YmCore::ImageHelper do describe "width_height_from_geo_string" do it "returns [100, 110] if given '100x110'" do width_height_from_geo_string("100x110").should == [100,110] end it "returns [100, 110] if given '100x110#'" do width_height_from_geo_string("100x110#").should == [100,110] end it "returns [100, nil] if given '100x'" do width_height_from_geo_string("100x").should == [100,nil] end end end
24.52381
72
0.63301
6a01b257b23917316fdbafccd15930f74ab790bb
1,176
# frozen_string_literal: true require "spec_helper" RSpec.describe Rubytoolbox::Api::ResponseWrapper do sub = Class.new(Rubytoolbox::Api::ResponseWrapper) do field :key end sample = Class.new(described_class) do field :foo field :bar, &:reverse field :sub do |input| sub.new input end field :subcollection do |inputs| inputs.map do |input| sub.new(input) end end end it "wraps given data as attributes of the class" do expect(sample.new(foo: "foo", bar: "bar")).to have_attributes( foo: "foo", bar: "rab" ) end it "correctly handles false value when given as string key" do expect(sample.new("foo" => false, bar: "123").foo).to be == false end it "can be converted back to a hash" do # rubocop:disable RSpec/ExampleLength object = sample.new( foo: "foo", bar: "bar", sub: { key: "value" }, subcollection: [{ key: "value" }] ) expect(object.to_h).to be == { "foo" => "foo", "bar" => "rab", "sub" => { "key" => "value", }, "subcollection" => [ { "key" => "value" }, ], } end end
21
79
0.568027
f82dbeb39dee3dfebe50e7c61114b32364ff8d35
1,997
namespace :collshift do desc 'Pull call numbers from range' task :call_nums, [:start_num, :end_num] => [:environment] do |task, args| l = LibraryCloud.new library_code = args[:library_code] || 'MUS' collection_code = args[:library_code] || 'GEN' start_num = args[:start_num] || 'ML410.M377 A88 2002' end_num = args[:end_num] || 'ML410.M595 D57 2013' records = l.records_in_range(library_code, start_num, end_num, nil) filtered_records = l.filter_by_library_collection(start_num, end_num, records, 'MUS', 'GEN') puts filtered_records['docs'].map{|doc| l.doc_call_numbers(doc)}.flatten.join("\n") end desc 'Pull records and item info' task :pull_records_and_items, [:library_code, :collection_code, :start_num, :end_num] => [:environment] do |task, args| require 'pp' l = LibraryCloud.new library_code = args[:library_code] || 'MUS' collection_code = args[:library_code] || 'GEN' start_num = args[:start_num] || 'ML410.M377 A88 2002' end_num = args[:end_num] || 'ML410.M595 D57 2013' records = l.records_in_range(library_code, start_num, end_num, nil) filtered_records = l.filter_by_library_collection(start_num, end_num, records, 'MUS', 'GEN') pp filtered_records end desc 'Get number of pages for range' task :pages_in_range, [:library_code, :collection_code, :start_num, :end_num] => [:environment] do |task, args| require 'pp' l = LibraryCloud.new library_code = args[:library_code] || 'MUS' collection_code = args[:library_code] || 'GEN' start_num = args[:start_num] || 'ML410.M377 A88 2002' start_num = args[:start_num] || 'ML410.B244 A5 2009' end_num = args[:end_num] || 'ML410.M595 D57 2013' end_num = args[:end_num] || 'ML410.B4968 A4 2002' result = l.pages_in_range(library_code, collection_code, start_num, end_num) pp result end end
48.707317
123
0.647972
399ba2d01a8aaa7c375d91a4d770d530a127ef0e
1,342
lib = File.expand_path("lib", __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "shortcode/version" Gem::Specification.new do |spec| spec.name = "shortcode" spec.version = Shortcode::VERSION spec.authors = ["Jamie Dyer"] spec.email = ["[email protected]"] spec.description = "Gem for parsing wordpress style shortcodes" spec.summary = "Gem for parsing wordpress style shortcodes in ruby projects" spec.homepage = "https://github.com/kernow/shortcode" spec.license = "MIT" spec.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency "parslet", "~> 1.8.0" spec.add_development_dependency "bundler", "~> 2.0" spec.add_development_dependency "coveralls", "~> 0.8.22" spec.add_development_dependency "haml", "~> 5.0" spec.add_development_dependency "rails", "5.2.3" spec.add_development_dependency "rake", "~> 12.0" spec.add_development_dependency "rspec", "~> 3.7" spec.add_development_dependency "rubocop", "~> 0.68" spec.add_development_dependency "rubocop-rspec", "~> 1.32" spec.add_development_dependency "slim", "~> 3.0" end
41.9375
84
0.684054
260609b6d58f9290df0bffa5a5d2ee301bacc359
1,724
require "spec_helper" module CC::Analyzer describe StatsdContainerListener do describe "#started" do it "increments a metric in statsd" do statsd = stub(increment: nil) statsd.expects(:increment).with("engines.started") listener = StatsdContainerListener.new("engine", statsd) listener.started(nil) end end describe "#timed_out" do it "increments a metric in statsd" do statsd = stub(timing: nil, increment: nil) statsd.expects(:timing).with("engines.time", 10) statsd.expects(:increment).with("engines.result.error") statsd.expects(:increment).with("engines.result.error.timeout") listener = StatsdContainerListener.new("engine", statsd) listener.timed_out(stub(duration: 10)) end end describe "#finished" do it "increments a metric for success" do statsd = stub(timing: nil, increment: nil) statsd.expects(:timing).with("engines.time", 10) statsd.expects(:increment).with("engines.finished") statsd.expects(:increment).with("engines.result.success") listener = StatsdContainerListener.new("engine", statsd) listener.finished(stub(duration: 10, status: stub(success?: true))) end it "increments a metric for failure" do statsd = stub(timing: nil, increment: nil) statsd.expects(:timing).with("engines.time", 10) statsd.expects(:increment).with("engines.finished") statsd.expects(:increment).with("engines.result.error") listener = StatsdContainerListener.new("engine", statsd) listener.finished(stub(duration: 10, status: stub(success?: false))) end end end end
33.803922
76
0.657773
62af9b849fbe44dc56232be8dbe26b540569010f
1,122
def endpoints_count YAML.load_file('app/data/endpoints.yml').count end def valid_jti 'd8cfec8b-9b00-471e-996d-6a1d93086e1c' # watchdoge JTI end def sorted_fake_calls(size: 10, oldest_timestamp: 8.days) endpoint_factory = EndpointFactory.new endpoints = endpoint_factory.endpoints.select { |e| e.api_name == 'apie' } fake_calls = [] size.times do timestamp = time_rand(Time.zone.now - oldest_timestamp) source = fake_elk_source(endpoints.sample, timestamp) fake_calls << CallResult.new(source, endpoint_factory) end fake_calls.sort_by(&:timestamp) end def fake_elk_source(endpoint, timestamp, status = nil) { 'path': endpoint.http_path, 'status': status.nil? ? %w[200 206 400 404 500 501].sample : status, '@timestamp': timestamp.to_s, 'parameters': { context: 'Ping', recipient: 'SGMAP', siret: '41816609600069', token: '[FILTERED]' }, 'response': { 'provider_name': endpoint.provider, 'fallback_used': [true, false].sample } }.stringify_keys end def time_rand(from = 0.0, to = Time.zone.now) Time.zone.at(from + rand * (to.to_f - from.to_f)) end
29.526316
104
0.702317
b987a24a919058201bc8f4a20bd7a6d631cd409e
1,407
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'integration/activejob/version' Gem::Specification.new do |spec| spec.name = "integration-activejob" spec.version = Integration::Activejob::VERSION spec.authors = ["John"] spec.email = ["[email protected]"] spec.summary = %q{TODO: Write a short summary, because Rubygems requires one.} spec.description = %q{TODO: Write a longer description or delete this line.} spec.homepage = "TODO: Put your gem's website or public repo URL here." spec.license = "MIT" # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or # delete this section to allow pushing this gem 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.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.11" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.0" end
41.382353
104
0.672353
7a04206c2c75aa86fc62394b6c5e6c91e4d55286
515
module Student class ProblemsController < BaseController # before_action :set_problem, only: [:show] # GET /student/problems # GET /student/problems.json def index @problems = Problem.all end # GET /student/problems/1 # GET /student/problems/1.json def show @problem = Problem.find(params[:id]) @answer = Answer.new @all_answers = Answer.where(:user_id => current_user.id,\ :problem_id => params[:id]) end end end
23.409091
63
0.603883
f8a3bf64b7aa831125607bfa1836a1de8f904ddb
663
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "timequery/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "timequery" s.version = Timequery::VERSION s.authors = ["mars"] s.email = ["[email protected]"] s.homepage = "https://github.com/wuyuedefeng/timequery" s.summary = "time model range query." s.description = "time model range query." s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"] s.add_dependency "rails", "~> 5.1.4" s.add_development_dependency "sqlite3" end
28.826087
83
0.647059
bffc4e4e5dcaef7404fd4654eba06eaa54209aab
2,303
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you 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 File.expand_path('../../spec_helper', __FILE__) module Selenium module WebDriver module Firefox describe Launcher do let(:resp) { {'sessionId' => 'foo', 'value' => Remote::Capabilities.firefox.as_json} } let(:launcher) { instance_double(Launcher, launch: true, url: 'http://example.com') } let(:caps) { Remote::Capabilities.firefox } let(:http) { instance_double(Remote::Http::Default, call: resp).as_null_object } before do allow(Remote::Capabilities).to receive(:firefox).and_return(caps) allow_any_instance_of(Service).to receive(:start) allow_any_instance_of(Service).to receive(:binary_path) end it 'does not start driver when receives url' do expect(Launcher).not_to receive(:new) expect(http).to receive(:server_url=).with(URI.parse('http://example.com:4321')) Driver.new(marionette: false, http_client: http, url: 'http://example.com:4321') end it 'defaults to desired port' do expect(Launcher).to receive(:new).with(anything, DEFAULT_PORT, nil).and_return(launcher) Driver.new(marionette: false, http_client: http) end it 'accepts a driver port' do port = '1234' expect(Launcher).to receive(:new).with(anything, '1234', nil).and_return(launcher) Driver.new(marionette: false, http_client: http, port: port) end end end # Firefox end # WebDriver end # Selenium
39.706897
98
0.686062
ff78ae744057d12e348802d918b63acc1be94e9f
887
# Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. module AWS class CloudTrail class Client < Core::QueryClient API_VERSION = '2013-11-01' signature_version :Version4, 'cloudtrail' # @api private CACHEABLE_REQUESTS = Set[] end class Client::V20131101 < Client define_client_methods('2013-11-01') end end end
24.638889
78
0.711387
281f1589bd2035658a349f377a5f3c1595b87b04
466
# encoding: utf-8 # This file is distributed under New Relic's license terms. # See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details. require File.expand_path(File.join(File.dirname(__FILE__),'..','..','test_helper')) require 'new_relic/rack/browser_monitoring' require 'new_relic/rack/developer_mode' class NewRelic::Rack::AllTest < MiniTest::Unit::TestCase # just here to load the files above def test_truth assert true end end
31.066667
83
0.759657
91b43753cb62f322a90fa38f5bc43b626db542cc
17,750
require 'rails_helper' module Stats describe R102SarAppealsPerformanceReport do before(:all) do create_report_type(abbr: :r102) Team.all.map(&:destroy) Timecop.freeze Time.new(2017, 6, 30, 12, 0, 0) do @bizgrp_ab = create :business_group, name: 'BGAB' @dir_a = create :directorate, name: 'DRA', business_group: @bizgrp_ab @dir_b = create :directorate, name: 'DRB', business_group: @bizgrp_ab @bizgrp_cd = create :business_group, name: 'BGCD' @dir_cd = create :directorate, name: 'DRCD', business_group: @bizgrp_cd @team_dacu_disclosure = find_or_create :team_dacu_disclosure @team_dacu_bmt = find_or_create :team_disclosure_bmt @team_a = create :business_unit, name: 'RTA', directorate: @dir_a @team_b = create :business_unit, name: 'RTB', directorate: @dir_b @team_c = create :business_unit, name: 'RTC', directorate: @dir_cd, moved_to_unit_id: 8 @team_d = create :business_unit, name: 'RTD', directorate: @dir_cd @responder_a = create :responder, responding_teams: [@team_a] @responder_b = create :responder, responding_teams: [@team_b] @responder_c = create :responder, responding_teams: [@team_c] @responder_d = create :responder, responding_teams: [@team_d] @outcome = find_or_create :outcome, :granted @info_held = find_or_create :info_status, :held # standard SARs and IRs which should be ignored by report create_sar(received: '20170605', responded: nil, deadline: '20170702', team: @team_d, responder: @responder_d, ident: 'case for team d - open in time', case_type: :accepted_sar) create_sar(received: '20170606', responded: '20170625', deadline: '20170630', team: @team_c, responder: @responder_c, ident: 'case for team c - responded in time', case_type: :accepted_sar) create_sar(received: '20170607', responded: '20170620', deadline: '20170625', team: @team_b, responder: @responder_b, ident: 'case for team b - responded in time', case_type: :accepted_sar) create_sar(received: '20170606', responded: '20170625', deadline: '20170630', team: @team_a, responder: @responder_a, ident: 'case for team a - responded in time', case_type: :accepted_sar) create_interal_review(received: '20170601', responded: '20170628', deadline: '20170625', team: @team_a, responder: @responder_a, ident: 'case for team a - responded late', case_type: :compliance_review_with_response) create_interal_review(received: '20170604', responded: '20170629', deadline: '20170625', team: @team_a, responder: @responder_a, ident: 'case for team a - responded late', case_type: :compliance_review_with_response) create_interal_review(received: '20170605', responded: nil, deadline: '20170625', team: @team_a, responder: @responder_a, ident: 'case for team a - open late', case_type: :compliance_review_with_response) create_interal_review(received: '20170605', responded: nil, deadline: '20170625', team: @team_a, responder: @responder_a, ident: 'case for team a - open late', case_type: :compliance_review_with_response) create_interal_review(received: '20170605', responded: nil, deadline: '20170702', team: @team_a, responder: @responder_a, ident: 'case for team a - open in time', case_type: :compliance_review_with_response) create_interal_review(received: '20170606', responded: '20170625', deadline: '20170630', team: @team_a, responder: @responder_a, ident: 'case for team a - responded in time', case_type: :compliance_review_with_response) create_interal_review(received: '20170605', responded: nil, deadline: '20170625', team: @team_b, responder: @responder_b, ident: 'case for team b - open late', case_type: :compliance_review_with_response) create_interal_review(received: '20170605', responded: nil, deadline: '20170702', team: @team_b, responder: @responder_b, ident: 'case for team b - open in time', case_type: :compliance_review_with_response) create_interal_review(received: '20170607', responded: '20170620', deadline: '20170625', team: @team_b, responder: @responder_b, ident: 'case for team b - responded in time', case_type: :compliance_review_with_response) create_interal_review(received: '20170604', responded: '20170629', deadline: '20170625', team: @team_c, responder: @responder_c, ident: 'case for team c - responded late', case_type: :compliance_review_with_response) create_interal_review(received: '20170606', responded: '20170625', deadline: '20170630', team: @team_c, responder: @responder_c, ident: 'case for team c - responded in time', case_type: :compliance_review_with_response) create_interal_review(received: '20170605', responded: nil, deadline: '20170702', team: @team_d, responder: @responder_d, ident: 'case for team d - open in time', case_type: :compliance_review_with_response) # ICO FOIs that should be ignored based on today's date of 30/6/2017 create_ico(type: :foi, received: '20170601', responded: '20170628', deadline: '20170625', team: @team_a, responder: @responder_a, ident: 'ico foi for team a - responded late') create_ico(type: :foi, received: '20170604', responded: '20170629', deadline: '20170625', team: @team_a, responder: @responder_a, ident: 'ico foi for team a - responded late') create_ico(type: :foi, received: '20170605', responded: nil, deadline: '20170625', team: @team_a, responder: @responder_a, ident: 'ico foi for team a - open late') create_ico(type: :foi, received: '20170605', responded: nil, deadline: '20170625', team: @team_a, responder: @responder_a, ident: 'ico foi for team a - open late') create_ico(type: :foi, received: '20170605', responded: nil, deadline: '20170702', team: @team_a, responder: @responder_a, ident: 'ico foi for team a - open in time') create_ico(type: :foi, received: '20170606', responded: '20170625', deadline: '20170630', team: @team_a, responder: @responder_a, ident: 'ico foi for team a - responded in time') create_ico(type: :foi, received: '20170605', responded: nil, deadline: '20170625', team: @team_b, responder: @responder_b, ident: 'ico foi for team b - open late') create_ico(type: :foi, received: '20170605', responded: nil, deadline: '20170702', team: @team_b, responder: @responder_b, ident: 'ico foi for team b - open in time') create_ico(type: :foi, received: '20170607', responded: '20170620', deadline: '20170625', team: @team_b, responder: @responder_b, ident: 'ico foi for team b - responded in time') create_ico(type: :foi, received: '20170604', responded: '20170629', deadline: '20170625', team: @team_c, responder: @responder_c, ident: 'ico foi for team c - responded late') create_ico(type: :foi, received: '20170606', responded: '20170625', deadline: '20170630', team: @team_c, responder: @responder_c, ident: 'ico foi for team c - responded in time') create_ico(type: :foi, received: '20170605', responded: nil, deadline: '20170702', team: @team_d, responder: @responder_d, ident: 'ico foi for team d - open in time') # ICO SARs based on today's date of 30/6/2017 create_ico(type: :sar, received: '20170601', responded: '20170628', deadline: '20170625', team: @team_a, responder: @responder_a, ident: 'ico sar for team a - responded late') create_ico(type: :sar, received: '20170604', responded: '20170629', deadline: '20170625', team: @team_a, responder: @responder_a, ident: 'ico sar for team a - responded late') create_ico(type: :sar, received: '20170605', responded: nil, deadline: '20170625', team: @team_a, responder: @responder_a, ident: 'ico sar for team a - open late') create_ico(type: :sar, received: '20170605', responded: nil, deadline: '20170625', team: @team_a, responder: @responder_a, ident: 'ico sar for team a - open late') create_ico(type: :sar, received: '20170605', responded: nil, deadline: '20170702', team: @team_a, responder: @responder_a, ident: 'ico sar for team a - open in time') create_ico(type: :sar, received: '20170606', responded: '20170625', deadline: '20170630', team: @team_a, responder: @responder_a, ident: 'ico sar for team a - responded in time') create_ico(type: :sar, received: '20170605', responded: nil, deadline: '20170625', team: @team_b, responder: @responder_b, ident: 'ico sar for team b - open late') create_ico(type: :sar, received: '20170605', responded: nil, deadline: '20170702', team: @team_b, responder: @responder_b, ident: 'ico sar for team b - open in time') create_ico(type: :sar, received: '20170607', responded: '20170620', deadline: '20170625', team: @team_b, responder: @responder_b, ident: 'ico sar for team b - responded in time') create_ico(type: :sar, received: '20170604', responded: '20170629', deadline: '20170625', team: @team_c, responder: @responder_c, ident: 'ico sar for team c - responded late') create_ico(type: :sar, received: '20170606', responded: '20170625', deadline: '20170630', team: @team_c, responder: @responder_c, ident: 'ico sar for team c - responded in time') create_ico(type: :sar, received: '20170605', responded: nil, deadline: '20170702', team: @team_d, responder: @responder_d, ident: 'ico sar for team d - open in time') end required_teams = [@bizgrp_ab, @dir_a, @dir_b, @bizgrp_cd, @dir_cd, @team_dacu_disclosure, @team_dacu_bmt, @team_a, @team_b, @team_c, @team_d] Team.where.not(id: required_teams.map(&:id)).destroy_all end after(:all) { DbHousekeeping.clean(seed: true) } describe '#title' do it 'returns the report title' do expect(R102SarAppealsPerformanceReport.title).to eq 'SAR Appeal performance stats' end end describe '#description' do it 'returns the report description' do expect(R102SarAppealsPerformanceReport.description).to eq 'Shows all ICO appeals which are open, or have been closed this month, analysed by timeliness' end end describe '#results' do before do Timecop.freeze Time.new(2017, 6, 30, 12, 0, 0) do report = R102SarAppealsPerformanceReport.new report.run @results = report.results end end it 'generates hierarchy starting with business_groups' do expect(@results.keys).to eq Team.hierarchy.map(&:id) + [:total] end it 'adds up directorate stats in each business_group' do expect(@results[@bizgrp_ab.id]) .to eq({ business_group: @bizgrp_ab.name, directorate: '', business_unit: '', business_unit_id: nil, new_business_unit_id: nil, deactivated: '', moved: '', responsible: @bizgrp_ab.team_lead, ico_appeal_performance: 44.4, ico_appeal_total: 9, ico_appeal_responded_in_time: 2, ico_appeal_responded_late: 2, ico_appeal_open_in_time: 2, ico_appeal_open_late: 3, }) end it 'adds up business_unit stats in each directorate' do expect(@results[@bizgrp_cd.id]) .to eq({ business_group: @bizgrp_cd.name, directorate: '', business_unit: '', business_unit_id: nil, new_business_unit_id: nil, deactivated: '', moved: '', responsible: @bizgrp_cd.team_lead, ico_appeal_performance: 66.7, ico_appeal_total: 3, ico_appeal_responded_in_time: 1, ico_appeal_responded_late: 1, ico_appeal_open_in_time: 1, ico_appeal_open_late: 0, }) end it 'adds up individual business_unit stats' do expect(@results[@team_c.id]) .to eq({ business_group: @bizgrp_cd.name, directorate: @dir_cd.name, business_unit: @team_c.name, business_unit_id: @team_c.id, new_business_unit_id: @team_c.moved_to_unit_id, deactivated: '', moved: '', responsible: @team_c.team_lead, ico_appeal_performance: 50.0, ico_appeal_total: 2, ico_appeal_responded_in_time: 1, ico_appeal_responded_late: 1, ico_appeal_open_in_time: 0, ico_appeal_open_late: 0, }) end end describe '#to_csv' do it 'outputs results as a csv lines' do Timecop.freeze Time.new(2017, 6, 30, 12, 0, 0) do super_header = %q{"","","","",} + %q{ICO appeals,ICO appeals,ICO appeals,ICO appeals,ICO appeals,ICO appeals} header = %q{Business group,Directorate,Business unit,Responsible,} + %q{Performance %,Total received,Responded - in time,Responded - late,Open - in time,Open - late} expected_text = <<~EOCSV SAR Appeal performance stats - 1 Jan 2017 to 30 Jun 2017 #{super_header} #{header} BGAB,"","",#{@bizgrp_ab.team_lead},44.4,9,2,2,2,3 BGAB,DRA,"",#{@dir_a.team_lead},33.3,6,1,2,1,2 BGAB,DRA,RTA,#{@team_a.team_lead},33.3,6,1,2,1,2 BGAB,DRB,"",#{@dir_b.team_lead},66.7,3,1,0,1,1 BGAB,DRB,RTB,#{@team_b.team_lead},66.7,3,1,0,1,1 BGCD,"","",#{@bizgrp_cd.team_lead},66.7,3,1,1,1,0 BGCD,DRCD,"",#{@dir_cd.team_lead},66.7,3,1,1,1,0 BGCD,DRCD,RTC,#{@team_c.team_lead},50.0,2,1,1,0,0 BGCD,DRCD,RTD,#{@team_d.team_lead},100.0,1,0,0,1,0 Total,"","","",50.0,12,3,3,3,3 EOCSV report = R102SarAppealsPerformanceReport.new report.run actual_lines = report.to_csv.map { |row| row.map(&:value) } expected_lines = expected_text.split("\n") actual_lines.zip(expected_lines).each do |actual, expected| expect(CSV.generate_line(actual).chomp).to eq(expected) end end end end context 'with a case in the db that is unassigned' do before do Timecop.freeze Time.new(2017, 6, 30, 12, 0, 0) do create :compliance_review, identifier: 'unassigned case' end end it 'does not raise an error' do report = R102SarAppealsPerformanceReport.new expect { report.run }.not_to raise_error end end # rubocop:disable Metrics/ParameterLists def create_sar(received:, responded:, deadline:, team:, responder:, ident:, case_type:) received_date = Date.parse(received) responded_date = responded.nil? ? nil : Date.parse(responded) kase = nil Timecop.freeze(received_date + 10.hours) do kase = create case_type, responding_team: team, responder: responder, identifier: ident kase.external_deadline = Date.parse(deadline) unless responded_date.nil? Timecop.freeze responded_date do kase.update!(date_responded: Time.now, outcome_id: @outcome.id, info_held_status: @info_held) kase.state_machine.respond_and_close!(acting_user: responder, acting_team: team) end end end kase.save! kase end def create_interal_review(received:, responded:, deadline:, team:, responder:, ident:, case_type:) received_date = Date.parse(received) responded_date = responded.nil? ? nil : Date.parse(responded) kase = nil Timecop.freeze(received_date + 10.hours) do kase = create case_type, responding_team: team, responder: responder, identifier: ident kase.external_deadline = Date.parse(deadline) unless responded_date.nil? Timecop.freeze responded_date do kase.state_machine.respond!(acting_user: responder, acting_team: team) kase.update!(date_responded: Time.now, outcome_id: @outcome.id, info_held_status: @info_held) kase.state_machine.close!(acting_user: kase.managing_team.users.first, acting_team: kase.managing_team) end end end kase.save! kase end def create_ico(type:, received:, responded:, deadline:, team:, responder:, ident:) received_date = Date.parse(received) responded_date = responded.nil? ? nil : Date.parse(responded) deadline_date = Date.parse(deadline) kase = nil if responded_date.nil? factory = "accepted_ico_#{type}_case".to_sym kase = create factory, creation_time: received_date, external_deadline: deadline_date, responding_team: team, responder: responder, identifier: ident else factory = "responded_ico_#{type}_case".to_sym kase = create factory, creation_time: received_date, external_deadline: deadline_date, responding_team: team, responder: responder, date_responded: responded_date, identifier: ident end kase end # rubocop:enable Metrics/ParameterLists end end
62.5
227
0.637634
e2ff23da32a3ed0af38448138725a2e810ef3bf3
1,081
require_relative 'boot' require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" require "active_storage/engine" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" require "action_cable/engine" require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Snag class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.2 # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. # Don't generate system test files. config.generators.system_tests = nil end end
31.794118
82
0.778908
28156965abeb5417785305ef474e847412624b9c
195
module MondoApi class Response attr_reader :body def initialize(success:, body:) @success = success @body = body end def success? @success end end end
13
35
0.6
8727122f8323811380cfa1c39268668bd1a6200e
192
class CreateTweets < ActiveRecord::Migration[6.0] def change create_table :tweets do |t| t.string :content t.integer :user_id t.timestamps null: false end end end
21.333333
49
0.666667
4a653d7029332c5aca7faca5d00dfb1ddcedbf9b
1,418
# -*- encoding: utf-8 -*- require './lib/recursive_open_struct/version' Gem::Specification.new do |s| s.name = "recursive-open-struct" s.version = RecursiveOpenStruct::VERSION s.authors = ["William (B.J.) Snow Orvis"] s.email = "[email protected]" s.date = Time.now.utc.strftime("%Y-%m-%d") s.homepage = "http://github.com/aetherknight/recursive-open-struct" s.licenses = ["MIT"] s.summary = "OpenStruct subclass that returns nested hash attributes as RecursiveOpenStructs" s.description = <<-QUOTE .gsub(/^ /,'') RecursiveOpenStruct is a subclass of OpenStruct. It differs from OpenStruct in that it allows nested hashes to be treated in a recursive fashion. For example: ros = RecursiveOpenStruct.new({ :a => { :b => 'c' } }) ros.a.b # 'c' Also, nested hashes can still be accessed as hashes: ros.a_as_a_hash # { :b => 'c' } QUOTE s.files = `git ls-files`.split("\n") s.test_files = `git ls-files spec`.split("\n") s.require_paths = ["lib"] s.extra_rdoc_files = [ "CHANGELOG.md", "LICENSE.txt", "README.md" ] s.add_development_dependency('bundler', [">= 0"]) s.add_development_dependency('pry', [">= 0"]) s.add_development_dependency('rake', [">= 0"]) s.add_development_dependency('rdoc', [">= 0"]) s.add_development_dependency('rspec', "~> 3.2") s.add_development_dependency('simplecov', [">= 0"]) end
31.511111
95
0.649506
ff34f7e7b2e0bb5a91e50b3ad2c7b42ba7cb3437
3,480
module Cannie # Module for defining and checking permissions module Permissions def self.included(base) base.extend ClassMethods end # Class methods available in the class scope for defining permissions module ClassMethods # Defines a namespace for permissions and defines the permissions inside the namespace. # # @param [Symbol, String] name name of the namespace # @param [Proc] block block to define permissions inside the namespace def namespace(name, &block) orig_scope = @scope @scope = [orig_scope, name].compact.join('/') instance_exec(&block) ensure @scope = orig_scope end # Defines a controller for permissions and defines the permissions inside the controller. # # @param [Symbol, String] name name of the controller # @param [Proc] block block to define permissions inside the controller def controller(name, &block) @controller = name instance_exec(&block) ensure @controller = nil end # Defines the rules for specified action. # # @param [String, Symbol, Array<String,Symbol>] action name of the action # @param [Hash] options additional options # @option options [Symbol, String] on name of the controller or list of # controller names for which current rule should be applies # @option options [Proc] if current rule should be applied for the action # when the `if` block is evaluated to true # @option options [Proc] unless current rule should be applied for the # action when the `unless` block is evaluated to false def allow(action, options = {}) opts = options.slice(:if, :unless) subjects = Array(@controller || options[:on]).map { |v| subject(v) } Array(action).each do |action_name| subjects.each do |subj| rules << Rule.new(action_name, subj, opts) end end end # Returns list of currently defined access rules. # # @return [Array<Rule>] def rules @rules ||= [] end private def subject(name) (name == :all && name) || [@scope, name].compact.join('/') end end attr_reader :user # Initializes instance of Permissions class for given user # # @param [Object] user a user, whose permissions will be checked # @return [Permissions] new instance of Permissions class def initialize(user) @user = user end # Checks if at least one rule for specified action add subject is present. # # @param [Symbol] action # @param [String, Symbol] subject # @return [Boolean] def can?(action, subject) rules_for(action, subject).present? end # Raises error Cannie::ActionForbidden if there is no rules for specified action and subject. # # @param [Symbol] action # @param [String, Symbol] subject def permit!(action, subject) raise Cannie::ActionForbidden unless can?(action, subject) end private def rules @rules ||= self.class.rules.select { |rule| rule.applies_to?(self) } end def rules_for(action, subject) subject = subject.respond_to?(:controller_path) ? subject.controller_path : subject.to_s rules.select do |rule| rule.action.to_sym == action.to_sym && (rule.subject == :all || rule.subject == subject) end end end end
31.636364
97
0.637069
087cf327788916bb1b51cf0ff3d90679797cd7ba
112
json.extract! @favourite_store, :id, :name, :address, :latitude, :longitude, :user_id, :created_at, :updated_at
56
111
0.741071
180d7fe656c300004ee683ec943435f1a6d96f1e
2,415
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Compute::Mgmt::V2019_12_01 module Models # # Api request input for LogAnalytics getThrottledRequests Api. # class ThrottledRequestsInput < LogAnalyticsInputBase include MsRestAzure # # Mapper for ThrottledRequestsInput class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ThrottledRequestsInput', type: { name: 'Composite', class_name: 'ThrottledRequestsInput', model_properties: { blob_container_sas_uri: { client_side_validation: true, required: true, serialized_name: 'blobContainerSasUri', type: { name: 'String' } }, from_time: { client_side_validation: true, required: true, serialized_name: 'fromTime', type: { name: 'DateTime' } }, to_time: { client_side_validation: true, required: true, serialized_name: 'toTime', type: { name: 'DateTime' } }, group_by_throttle_policy: { client_side_validation: true, required: false, serialized_name: 'groupByThrottlePolicy', type: { name: 'Boolean' } }, group_by_operation_name: { client_side_validation: true, required: false, serialized_name: 'groupByOperationName', type: { name: 'Boolean' } }, group_by_resource_name: { client_side_validation: true, required: false, serialized_name: 'groupByResourceName', type: { name: 'Boolean' } } } } } end end end end
29.096386
70
0.474534
1def651fc931caace6b171b82fdd989cffe6e2f1
536
class CreateTangSubscriptions < ActiveRecord::Migration def change create_table :tang_subscriptions do |t| t.string :stripe_id t.integer :customer_id, index: true t.integer :plan_id, index: true, foreign_key: true t.decimal :application_fee_percent t.integer :quantity t.decimal :tax_percent t.timestamp :trial_end t.integer :coupon_id, index: true, foreign_key: true t.timestamp :coupon_start t.string :status t.timestamps null: false end end end
24.363636
58
0.679104
abc2f67a1e0c7e9b9c2c4c60d4e51388a645383a
188
# Capistrano recipes for an Apache Passenger app server namespace :passenger do desc "Restart the rails app" task :restart do run "touch #{current_path}/tmp/restart.txt" end end
23.5
55
0.744681
032e122d4890b6940b8eb3344acdf33506a643c8
1,809
describe 'apache::mod::itk', :type => :class do let :pre_condition do 'class { "apache": mpm_module => false, }' end context "on a Debian OS" do let :facts do { :osfamily => 'Debian', :operatingsystemrelease => '6', :concat_basedir => '/dne', } end it { should contain_class("apache::params") } it { should_not contain_apache__mod('itk') } it { should contain_file("/etc/apache2/mods-available/itk.conf").with_ensure('file') } it { should contain_file("/etc/apache2/mods-enabled/itk.conf").with_ensure('link') } context "with Apache version < 2.4" do let :params do { :apache_version => 2.2, } end it { should_not contain_file("/etc/apache2/mods-available/itk.load") } it { should_not contain_file("/etc/apache2/mods-enabled/itk.load") } it { should contain_package("apache2-mpm-itk") } end context "with Apache version >= 2.4" do let :params do { :apache_version => 2.4, } end it { should contain_file("/etc/apache2/mods-available/itk.load").with({ 'ensure' => 'file', 'content' => "LoadModule mpm_itk_module /usr/lib/apache2/modules/mod_mpm_itk.so\n" }) } it { should contain_file("/etc/apache2/mods-enabled/itk.load").with_ensure('link') } end end context "on a FreeBSD OS" do let :facts do { :osfamily => 'FreeBSD', :operatingsystemrelease => '9', :concat_basedir => '/dne', } end it { should contain_class("apache::params") } it { should_not contain_apache__mod('itk') } it { should contain_file("/usr/local/etc/apache22/Modules/itk.conf").with_ensure('file') } end end
30.661017
94
0.579878
e9b17371d176f3f49547276c57940db4343bb153
6,286
require File.expand_path("../../spec_helper", __FILE__) describe CouchRest do before(:each) do @cr = CouchRest.new(COUCHHOST) begin @db = @cr.database(TESTDB) @db.delete! rescue nil end end after(:each) do begin @db.delete! rescue nil end end describe "getting info" do it "should list databases" do @cr.databases.should be_an_instance_of(Array) end it "should get info" do @cr.info["couchdb"].should == "Welcome" @cr.info.class.should == Hash end end it "should restart" do @cr.restart! begin @cr.info rescue # Give the couchdb time to restart sleep 0.2 retry end end it "should provide one-time access to uuids" do @cr.next_uuid.should_not be_nil end describe "initializing a database" do it "should return a db" do db = @cr.database(TESTDB) db.should be_an_instance_of(CouchRest::Database) db.host.should == @cr.uri end end describe "parsing urls" do it "should parse just a dbname" do db = CouchRest.parse "my-db" db[:database].should == "my-db" db[:host].should == "http://127.0.0.1:5984" end it "should parse a host and db" do db = CouchRest.parse "127.0.0.1/my-db" db[:database].should == "my-db" db[:host].should == "http://127.0.0.1" end it "should parse a host and db with http" do db = CouchRest.parse "http://127.0.0.1/my-db" db[:database].should == "my-db" db[:host].should == "http://127.0.0.1" end it "should parse a host and db with https" do db = CouchRest.parse "https://127.0.0.1/my-db" db[:database].should == "my-db" db[:host].should == "https://127.0.0.1" end it "should parse a host with a port and db" do db = CouchRest.parse "127.0.0.1:5555/my-db" db[:database].should == "my-db" db[:host].should == "http://127.0.0.1:5555" end it "should parse a host with a port and db with http" do db = CouchRest.parse "http://127.0.0.1:5555/my-db" db[:database].should == "my-db" db[:host].should == "http://127.0.0.1:5555" end it "should parse a host with a port and db with https" do db = CouchRest.parse "https://127.0.0.1:5555/my-db" db[:database].should == "my-db" db[:host].should == "https://127.0.0.1:5555" end it "should parse just a host" do db = CouchRest.parse "http://127.0.0.1:5555/" db[:database].should be_nil db[:host].should == "http://127.0.0.1:5555" end it "should parse just a host with https" do db = CouchRest.parse "https://127.0.0.1:5555/" db[:database].should be_nil db[:host].should == "https://127.0.0.1:5555" end it "should parse just a host no slash" do db = CouchRest.parse "http://127.0.0.1:5555" db[:host].should == "http://127.0.0.1:5555" db[:database].should be_nil end it "should parse just a host no slash and https" do db = CouchRest.parse "https://127.0.0.1:5555" db[:host].should == "https://127.0.0.1:5555" db[:database].should be_nil end it "should get docid" do db = CouchRest.parse "127.0.0.1:5555/my-db/my-doc" db[:database].should == "my-db" db[:host].should == "http://127.0.0.1:5555" db[:doc].should == "my-doc" end it "should get docid with http" do db = CouchRest.parse "http://127.0.0.1:5555/my-db/my-doc" db[:database].should == "my-db" db[:host].should == "http://127.0.0.1:5555" db[:doc].should == "my-doc" end it "should get docid with https" do db = CouchRest.parse "https://127.0.0.1:5555/my-db/my-doc" db[:database].should == "my-db" db[:host].should == "https://127.0.0.1:5555" db[:doc].should == "my-doc" end end describe "easy initializing a database adapter" do it "should be possible without an explicit CouchRest instantiation" do db = CouchRest.database "http://127.0.0.1:5984/couchrest-test" db.should be_an_instance_of(CouchRest::Database) db.host.should == "http://127.0.0.1:5984" end # TODO add https support (need test environment...) # it "should work with https" # do # db = CouchRest.database "https://127.0.0.1:5984/couchrest-test" # db.host.should == "https://127.0.0.1:5984" # end it "should not create the database automatically" do db = CouchRest.database "http://127.0.0.1:5984/couchrest-test" lambda{db.info}.should raise_error(RestClient::ResourceNotFound) end end describe "ensuring the db exists" do it "should be super easy" do db = CouchRest.database! "#{COUCHHOST}/couchrest-test-2" db.name.should == 'couchrest-test-2' db.info["db_name"].should == 'couchrest-test-2' end end describe "successfully creating a database" do it "should start without a database" do @cr.databases.should_not include(TESTDB) end it "should return the created database" do db = @cr.create_db(TESTDB) db.should be_an_instance_of(CouchRest::Database) end it "should create the database" do db = @cr.create_db(TESTDB) @cr.databases.should include(TESTDB) end end describe "failing to create a database because the name is taken" do before(:each) do db = @cr.create_db(TESTDB) end it "should start with the test database" do @cr.databases.should include(TESTDB) end it "should PUT the database and raise an error" do lambda{ @cr.create_db(TESTDB) }.should raise_error(RestClient::Request::RequestFailed) end end describe "using a proxy for RestClient connections" do it "should set proxy url for RestClient" do CouchRest.proxy 'http://localhost:8888/' proxy_uri = URI.parse(RestClient.proxy) proxy_uri.host.should eql( 'localhost' ) proxy_uri.port.should eql( 8888 ) CouchRest.proxy nil end end describe "Including old ExtendedDocument library" do it "should raise an exception" do lambda do class TestDoc < CouchRest::ExtendedDocument attr_reader :fail end end.should raise_error(RuntimeError) end end end
30.965517
76
0.616927
618b6d9ad904ad2f9c509de3a330b2a569637630
3,159
require 'spec_helper' RSpec.describe Rip::Parser do let(:fixtures) { Rip::Parser.root + 'spec' + 'fixtures' } describe '.load' do end describe '.load_file' do let(:parse_tree) { Rip::Parser.load_file(fixtures + 'syntax_sample.rip') } subject { parse_tree } def find_rhs(name) parse_tree.expressions.select(&:assignment?).detect do |assignment| assignment.lhs.name == name.to_s end.rhs end it { should be_an_instance_of(Rip::Parser::Node) } context 'top-level' do let(:expressions) { parse_tree.expressions } let(:assignment_values) do parse_tree.expressions.select(&:assignment?).map(&:rhs) end let(:actual_counts) do [ *expressions, *assignment_values ].sort_by(&:type).group_by(&:type).map do |type, expression| [ type, expression.count ] end.to_h end let(:expected_counts) do { assignment: 16, class: 2, date_time: 1, import: 2, integer: 1, invocation: 5, invocation_index: 1, lambda: 2, list: 3, map: 1, overload: 3, pair: 1, property_access: 2, regular_expression: 2, string: 2, unit: 2 } end specify { expect(actual_counts).to eq(expected_counts) } end context 'spot-checks' do let(:list) { parse_tree.expressions.detect { |e| e.type == :list } } let(:range) do parse_tree.expressions.select(&:pair?).detect do |pair| pair[:key].characters.map(&:data).join('') == 'range' end.value end let(:lunch_time) { find_rhs('lunch-time') } specify { expect(list.items.count).to eq(3) } specify { expect(list.items.select(&:character?).count).to eq(1) } specify { expect(list.items.select(&:escape_special?).count).to eq(1) } specify { expect(list.items.select(&:escape_unicode?).count).to eq(1) } specify { expect(range.start.integer).to eq('0') } specify { expect(range.end.object.integer).to eq('9') } specify { expect(find_rhs(:map).pairs.count).to eq(1) } specify do expect(lunch_time.type).to eq(:invocation) expect(lunch_time.callable.type).to eq(:property_access) expect(lunch_time.callable.object.type).to eq(:time) end end context 'pathelogical nesting' do let(:property_chain) { find_rhs('please-dont-ever-do-this') } specify { expect(property_chain.object.callable.object.name).to eq('foo') } specify { expect(property_chain.object.callable.property_name).to eq('bar') } specify { expect(property_chain.object.arguments).to eq([]) } specify { expect(property_chain.property_name).to eq('baz') } end end describe '.root' do specify { expect(Rip::Parser.root).to eq(Pathname.new(__dir__).parent.parent.parent.expand_path) } end end
29.523364
102
0.568534
ed97aa808e9b0ce6d72dd980eeea316595cdbd01
2,885
# This file is copied to spec/ when you run 'rails generate rspec:install' require 'spec_helper' ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../config/environment', __dir__) # Prevent database truncation if the environment is production abort('The Rails environment is running in production mode!') if Rails.env.production? require 'rspec/rails' # Add additional requires below this line. Rails is not loaded until this point! # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are # run as spec files by default. This means that files in spec/support that end # in _spec.rb will both be required and run as specs, causing the specs to be # run twice. It is recommended that you do not name files matching this glob to # end with _spec.rb. You can configure this pattern with the --pattern # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. # # The following line is provided for convenience purposes. It has the downside # of increasing the boot-up time by auto-requiring all files in the support # directory. Alternatively, in the individual `*_spec.rb` files, manually # require only the support files necessary. # Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } # Checks for pending migrations and applies them before tests are run. # If you are not using ActiveRecord, you can remove these lines. begin ActiveRecord::Migration.maintain_test_schema! rescue ActiveRecord::PendingMigrationError => e puts e.to_s.strip exit 1 end RSpec.configure do |config| # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. # config.use_transactional_fixtures = true # You can uncomment this line to turn off ActiveRecord support entirely. # config.use_active_record = false # RSpec Rails can automatically mix in different behaviours to your tests # based on their file location, for example enabling you to call `get` and # `post` in specs under `spec/controllers`. # # You can disable this behaviour by removing the line below, and instead # explicitly tag your specs with their type, e.g.: # # RSpec.describe UsersController, type: :controller do # # ... # end # # The different available types are documented in the features, such as in # https://relishapp.com/rspec/rspec-rails/docs config.infer_spec_type_from_file_location! # Filter lines from Rails gems in backtraces. config.filter_rails_from_backtrace! # arbitrary gems may also be filtered via: # config.filter_gems_from_backtrace("gem name") end
44.384615
86
0.751127
2106b344abc48c33074a0cf0efe0316203586329
13,170
require 'tmpdir' require 'tty/platform' require_relative 'validation' module VideoConverter # Class for video conversion # require 'video_converter/converter' # VideoConverter::Converter.new( # verbose: false, # foreground: false, # clean: true, # input_folder: '~/Downloads', # log_folder: '~/logs/video_converter', # output_folder: '~/Desktop' # ).run class Converter Options = Struct.new( :verbose, :foreground, :clean, :folder, :log_folder, :output_folder, :crf ) DEFAULT_FOLDER = '~/Downloads' DEFAULT_LOG_FOLDER = '~/logs/video_converter' DEFAULT_OUTPUT_FOLDER = '~/Desktop' DEFAULT_CRF = 28.0 include Validation attr_reader :options # Create a new Converter. Recognizes the following environment variables: # # VIDEO_CONVERTER_VERBOSE # VIDEO_CONVERTER_FOREGROUND # VIDEO_CONVERTER_CLEAN # VIDEO_CONVERTER_FOLDER # VIDEO_CONVERTER_LOG_FOLDER # VIDEO_CONVERTER_OUTPUT_FOLDER # VIDEO_CONVERTER_CRF # # The first three all represent Boolean flags. Any value starting with y or # t (case-insensitive) indicates a value of true. Any other value will be # interpreted as false. # # @param options [Options] An Options struct containing configuration # @param verbose [true, false] Output additional information at times # @param foreground [true, false] Run in the foreground # @param clean [true, false] Remove original videos after conversion # @param input_folder [String] Folder to scan for input videos # @param log_folder [String] Folder for log files (background) # @param output_folder [String] Folder for output MP4 files # @param crf [Float] CRF value to use when converting to MP4 with H.264 (0-51) def initialize( options = nil, verbose: boolean_env_var?(:VIDEO_CONVERTER_VERBOSE, default_value: false), foreground: boolean_env_var?(:VIDEO_CONVERTER_FOREGROUND, default_value: false), clean: boolean_env_var?(:VIDEO_CONVERTER_CLEAN, default_value: true), input_folder: ENV['VIDEO_CONVERTER_FOLDER'] || DEFAULT_FOLDER, log_folder: ENV['VIDEO_CONVERTER_LOG_FOLDER'] || DEFAULT_LOG_FOLDER, output_folder: ENV['VIDEO_CONVERTER_OUTPUT_FOLDER'] || DEFAULT_OUTPUT_FOLDER, crf: float_env_var(:VIDEO_CONVERTER_CRF, default_value: DEFAULT_CRF) ) the_crf = options ? options.crf : crf raise ArgumentError, "Illegal CRF value #{the_crf}. Legal values are 0-51." if the_crf < 0 || the_crf > 51 @options = options || Options.new( verbose, foreground, clean, File.expand_path(input_folder), File.expand_path(log_folder), File.expand_path(output_folder), crf ) end # Perform video conversion def run if foreground? convert_all else @log_file = File.join options.log_folder, 'convert_videos.log' if Process.respond_to? :fork pid = fork do nice_process # Ignore SIGHUP when parent process dies Signal.trap 'HUP', 'IGNORE' FileUtils.rm_rf options.log_folder FileUtils.mkdir_p options.log_folder video_count = all_videos.count File.open @log_file, 'w' do |log| report_process_priority log: log convert_all log: log exit(0) unless mac? # Generate a preview make_preview log if all_videos.first notify_user video_count, log end end else pid = run_in_background end unless pid.zero? STDOUT.log "Child process is #{pid}. Output in #{@log_file}.", obfuscate: false exit 0 end end end def cli_command command = [ File.expand_path(File.join('bin', 'convert_videos')), verbose? ? "--verbose" : "--no-verbose", "--foreground", "--folder=#{@options.folder}", "--output-folder=#{@options.output_folder}", "--log-folder=#{@options.log_folder}" ] command << "--no-clean" unless clean? command end # Portability method. Executes a foregrounded convert_videos process as a background task, # similar to how Kernel#fork is used when available. def run_in_background FileUtils.rm_rf @options.log_folder FileUtils.mkdir_p @options.log_folder pid = spawn(*cli_command, %i[err out] => File.join(@options.log_folder, 'convert_videos.log')) nice_process pid report_process_priority pid pid end def nice_process(pid = 0) return unless Process.respond_to?(:setpriority) && defined?(Process::PRIO_PROCESS) Process.setpriority Process::PRIO_PROCESS, pid, 19 end def report_process_priority(pid = 0, log: STDOUT) return unless Process.respond_to?(:getpriority) && defined?(Process::PRIO_PROCESS) pid_to_report = pid.zero? ? Process.pid : pid log.log "Process priority is #{Process.getpriority Process::PRIO_PROCESS, pid} for PID #{pid_to_report}.", obfuscate: false end def all_videos return @all_videos unless @all_videos.nil? full_path = File.expand_path options.folder @all_videos = Dir.chdir options.folder do VIDEO_SUFFIXES.inject([]) do |all_vids, suffix| all_vids + Dir["*.#{suffix.downcase}"] + Dir["*.#{suffix.upcase}"] end end.map { |f| File.join full_path, f } end def print_to_be_converted(log) return unless verbose? log.log 'To be converted:' all_videos.each do |v| log.log " #{v}" end end def conversion_command(path, output_path, type: nil) conversions = case type when Array type.map(&:to_sym) when Symbol [type] when String [type.to_sym] else %i[audio video] end command = ['ffmpeg', '-i', path] if conversions.include? :video # Use -crf options.crf for H.264 when converting to MP4. command += ['-crf', options.crf.to_s] if output_path.is_mp4? command += %w[-codec:audio copy] unless conversions.include?(:audio) || output_path.video_type != path.video_type end if conversions.include? :audio command += %w[-codec:video copy] unless conversions.include?(:video) || output_path.video_type != path.video_type end command + ['-y', output_path] end # Convert audio without converting video. Writes to file.mp4 in @tmpdir. def convert_audio_command(path) conversion_command path, temp_path(path), type: :audio end # Convert video without converting audio. Writes to options.output_folder. def convert_video_command(path) conversion_command path, output_path(path), type: :video end def make_preview_command(path) width, height = dimensions path unless width.nil? || height.nil? if width > height indent = 0.5 * (width - height) crop = "#{height}:#{height}:#{indent}:0" else indent = 0.5 * (height - width) crop = "#{width}:#{width}:0:#{indent}" end end ['ffmpeg', '-i', path, '-f', 'image2', '-filter', "crop=#{crop}", '-vframes', '1', '-y', preview_path] end def make_preview(log) command = make_preview_command output_path(all_videos.first) execute(*command, log: log, output: File.join(options.log_folder, 'preview.log')) rescue ExecutionError # ignore end def output_path(path) File.join(options.output_folder, File.basename(path.sub(REGEXP, 'mp4'))) end def temp_path(path) File.join @tmpdir, File.basename(path.sub(REGEXP, 'mp4')) end def preview_path return @preview_path if @preview_path @preview_path = File.join Dir.tmpdir, 'preview.jpg' end # Convert the file at path. If log_path is non-nil, generate a log # at that location. Main log (open) is log. # # @param path [String] Path to a file to be converted # @param log_path [String, nil] Path to a log file for the conversion # @param log [IO] Open IO for main log # @return nil # @raise ExecutionError If the conversion fails def convert_file(path, log_path, log) if path.is_mp4? # Convert mp4s in two steps. # Step 1: Convert audio without converting video. # Generates file.mp4 in a temporary folder. command = convert_audio_command path # raises ExecutionError execute(*command, output: log_path, log: log) # Now determine the audio bitrates of the original and the file in the temp folder. orig_audio_bitrate = audio_bitrate path converted_audio_bitrate = audio_bitrate temp_path(path) # Choose the one with the lower audio bitrate as input for the second step. # If the converted bitrate is 90% or more of the original, use the original. input = converted_audio_bitrate < orig_audio_bitrate * THRESHOLD ? temp_path(path) : path # Step 2: Convert video without converting audio using the original or # the temp copy with converted audio, whichever is smaller. # Generates file.mp4 in options.output_folder. command = convert_video_command input # raises ExecutionError execute(*command, output: log_path, log: log) FileUtils.rm_f temp_path(path) # This results in a file with minimum audio bitrate (original or reduced) # and a reduced video bitrate without converting audio or video twice. else command = conversion_command path, output_path(path) # raises ExecutionError execute(*command, output: log_path, log: log) end FileUtils.touch(output_path(path), mtime: File.mtime(path)) log.log "Finished converting #{output_path path}.".cyan.bold end def convert_all(log: STDOUT) # Assuming `which` will fail on Windows. Just allow these commands to fail. # system/popen2e will raise Errno::ENOENT, which will be promptly reported. unless windows? || check_commands(%i[ffmpeg mp4info], log: log) log.log 'Please install these packages in order to use this script.'.red.bold exit 1 end log.log "CRF value #{options.crf} is outside the recommended range of 18-28.".yellow if options.crf < 18 || options.crf > 28 FileUtils.mkdir_p options.output_folder unless Dir.exist?(options.output_folder) Dir.mktmpdir do |dir| @tmpdir = dir print_to_be_converted log failures = [] all_videos.each do |path| if log.respond_to? :path log_path = File.join options.log_folder, File.basename(path.sub(REGEXP, 'log')) output_path = output_path path log.log "input: #{path}, output: #{output_path}, log: #{log_path}" if verbose? end begin convert_file path, log_path, log rescue ExecutionError log.log "Conversion failed for #{path}.".yellow FileUtils.rm_f output_path(path) failures << path end end @all_videos -= failures log.log "Finished converting all videos. #{@all_videos.count} succeeded. #{failures.count} failed.".cyan.bold # @tmpdir about to be deleted remove_instance_variable :@tmpdir end validate log clean_sources log end def clean_sources(log) return unless clean? && File.writable?(options.folder) && all_videos.count > 0 log.log 'Removing:' all_videos.each { |v| log.log " #{v}" } FileUtils.rm_f all_videos end def notify_user(count, log) return if count <= 0 message = "Converted #{count} video#{count > 1 ? 's' : ''}." message << " (#{count - all_videos.count} failed.)" unless count == all_videos.count log.log message.cyan.bold command = [ 'terminal-notifier', '-title', 'Video Conversion Complete', '-message', message, '-sound', 'default', '-activate', 'com.apple.Photos' # , # '-open', # "file://#{options.output_folder}" ] command += ['-contentImage', preview_path] if File.exist?(preview_path) # terminal-notifier is a runtime dependency and so will always be present. # On any platform besides macOS, this command will fail. begin execute(*command, log: verbose? ? log : nil, output: verbose? ? log : :close) rescue ExecutionError => e # ignore errors log.log e.message if verbose? end FileUtils.rm_f preview_path end def foreground? options.foreground end def clean? options.clean end def mac? @platform = TTY::Platform.new if @platform.nil? @platform.mac? end def windows? @platform = TTY::Platform.new if @platform.nil? @platform.windows? end end end
31.966019
130
0.633333
b9a89c088b36dd5138e7485c518ef4bbcc0852e0
759
require 'spec_helper' describe Lyft::Client::Api::Rides, '#cancel' do let(:request_path) { "/#{Lyft::Client::Api::VERSION}/rides/#{ride_id}/cancel" } let(:inputs) do { confirmation_token: 'abc123' } end let(:config) do Lyft::Client::Configuration.new client_id: 'id', client_secret: 'secret' end let(:instance) { described_class.new config } let(:access_token) { 'my_token'} let(:ride_id) { '123' } subject { instance } before :each do stub_post(request_path).with(body: inputs, headers: { Authorization: "Bearer #{access_token}" }) end it 'should be successful' do resp = subject.cancel access_token: access_token, params: inputs.merge(ride_id: ride_id) expect(resp.success?).to eql true end end
25.3
100
0.675889
ac88edf03104fe7685896e562d46b04509a7e3ae
1,053
# Encoding: utf-8 require_relative 'spec_helper' describe 'openstack-network::server' do describe 'redhat' do let(:runner) { ChefSpec::SoloRunner.new(REDHAT_OPTS) } let(:node) { runner.node } let(:chef_run) do node.override['openstack']['compute']['network']['service_type'] = 'neutron' runner.converge(described_recipe) end before do node.override['openstack']['network']['plugins']['ml2']['path'] = '/etc/neutron/plugins/ml2' node.override['openstack']['network']['plugins']['ml2']['filename'] = 'openvswitch_agent.ini' end include_context 'neutron-stubs' it 'upgrades openstack-neutron packages' do expect(chef_run).to upgrade_package 'openstack-neutron' end it 'enables openstack-neutron server service' do expect(chef_run).to enable_service 'neutron-server' end it 'does not upgrade openvswitch package' do expect(chef_run).not_to upgrade_package 'openvswitch' expect(chef_run).not_to enable_service 'neutron-openvswitch-agent' end end end
32.90625
99
0.694207
03a4992114fa39471543530fb2c5a990f30bab81
93
module Mogli class Music < Model define_properties :name, :category, :id end end
15.5
43
0.677419
2150cbd2acfc767d115a13b3d6c53bb682a2fbfa
2,298
require File.expand_path('../../spec_helper', __FILE__) module Pod describe Pod::AggregateTarget do describe 'In general' do before do @target_definition = fixture_target_definition @lib = AggregateTarget.new(config.sandbox, false, {}, [], Platform.ios, @target_definition, config.sandbox.root.dirname, nil, nil, {}) end it 'returns the target_definition that generated it' do @lib.target_definition.should == @target_definition end it 'returns the label of the target definition' do @lib.label.should == 'Pods' end it 'returns its name' do @lib.name.should == 'Pods' end it 'returns the name of its product' do @lib.product_name.should == 'libPods.a' end end describe 'Support files' do before do @target_definition = fixture_target_definition @lib = AggregateTarget.new(config.sandbox, false, {}, [], Platform.ios, @target_definition, config.sandbox.root.dirname, nil, nil, {}) end it 'returns the absolute path of the xcconfig file' do @lib.xcconfig_path('Release').to_s.should.include?('Pods/Target Support Files/Pods/Pods.release.xcconfig') end it 'returns the absolute path of the resources script' do @lib.copy_resources_script_path.to_s.should.include?('Pods/Target Support Files/Pods/Pods-resources.sh') end it 'returns the absolute path of the bridge support file' do @lib.bridge_support_path.to_s.should.include?('Pods/Target Support Files/Pods/Pods.bridgesupport') end it 'returns the absolute path of the acknowledgements files without extension' do @lib.acknowledgements_basepath.to_s.should.include?('Pods/Target Support Files/Pods/Pods-acknowledgements') end #--------------------------------------# it 'returns the path of the resources script relative to the Pods project' do @lib.copy_resources_script_relative_path.should == '${PODS_ROOT}/Target Support Files/Pods/Pods-resources.sh' end it 'returns the path of the xcconfig file relative to the user project' do @lib.xcconfig_relative_path('Release').should == 'Pods/Target Support Files/Pods/Pods.release.xcconfig' end end end end
37.064516
142
0.672759
623ddbe9eb5c9aeda32bc1c327d823092034c168
1,669
require 'logger' module AnalyzeMySQL module Structure class Schema attr_reader :tables def initialize(conn, conf, name) @name = name @conn = conn @conf = conf @tables = {} @log = ::Logger.new(STDOUT) refresh_cache end def refresh_cache @conn.query("USE #{@name}") @conn.query('SHOW TABLES').each do |v| table = v.first[1] @tables[table] = AnalyzeMySQL::Structure::Table.new(@conn, @conf, table) if table_included? table end end def table_included?(table) has_all = (!@conf['tables']['include'].nil? && @conf['tables']['include'].include?('all')) has_excludes = !@conf['tables']['exclude'].nil? use_all = (has_all && !has_excludes) if has_all && !@conf['tables']['exclude'].nil? && !@conf['tables']['exclude'].include?(table) @log.info "Table #{table} is included in `all` and not excluded. Using it." return true end if !has_all and !@conf['tables']['include'].include? table @log.debug "Table #{table} is not included in the includes-list. Skipping it." return false end if !has_all and @conf['tables']['include'].include? table @log.info "Table #{table} is included in the includes-list. Using it." return true end if use_all @log.debug "All tables mode selected, using #{table}" if use_all return true end # Raise exception? puts "No matches at all for table #{table}, this might be an error.".red false end end end end
29.803571
107
0.56441
623fe955084f93d38aa1501dd69ff158fb44bc19
2,648
class Redis < Formula desc "Persistent key-value database, with built-in net interface" homepage "https://redis.io/" url "https://download.redis.io/releases/redis-6.0.10.tar.gz" sha256 "79bbb894f9dceb33ca699ee3ca4a4e1228be7fb5547aeb2f99d921e86c1285bd" license "BSD-3-Clause" head "https://github.com/redis/redis.git", branch: "unstable" livecheck do url "https://download.redis.io/releases/" regex(/href=.*?redis[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do sha256 cellar: :any, arm64_big_sur: "0ae80e0e8a0a13d663a1d9e1c74bb17df56deb4b2edd5397b363ec4f6a32e43c" sha256 cellar: :any, big_sur: "ecd20074b450f501345d7533abc51e8f47f28f27a5c8b7c698fe4d80aeb8126c" sha256 cellar: :any, catalina: "92bc496f208cdbcbf5b9251d0e32bca775d19e800b5d19948c54c3f8d03f0c9b" sha256 cellar: :any, mojave: "2c577a2692701929cc90f0bd2fd050e47705d8693086e1050b4b69ec95315ed1" end depends_on "[email protected]" def install system "make", "install", "PREFIX=#{prefix}", "CC=#{ENV.cc}", "BUILD_TLS=yes" %w[run db/redis log].each { |p| (var/p).mkpath } # Fix up default conf file to match our paths inreplace "redis.conf" do |s| s.gsub! "/var/run/redis.pid", var/"run/redis.pid" s.gsub! "dir ./", "dir #{var}/db/redis/" s.sub!(/^bind .*$/, "bind 127.0.0.1 ::1") end etc.install "redis.conf" etc.install "sentinel.conf" => "redis-sentinel.conf" end plist_options manual: "redis-server #{HOMEBREW_PREFIX}/etc/redis.conf" def plist <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <dict> <key>SuccessfulExit</key> <false/> </dict> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/redis-server</string> <string>#{etc}/redis.conf</string> <string>--daemonize no</string> </array> <key>RunAtLoad</key> <true/> <key>WorkingDirectory</key> <string>#{var}</string> <key>StandardErrorPath</key> <string>#{var}/log/redis.log</string> <key>StandardOutPath</key> <string>#{var}/log/redis.log</string> </dict> </plist> EOS end test do system bin/"redis-server", "--test-memory", "2" %w[run db/redis log].each { |p| assert_predicate var/p, :exist?, "#{var/p} doesn't exist!" } end end
33.948718
108
0.616314
0894359ac2837d5924c66682d657ab8d6836ae6f
1,039
cask :v1 => 'deeper' do version :latest sha256 :no_check if MacOS.version == :tiger url 'http://www.titanium.free.fr/download/104/Deeper.dmg' elsif MacOS.version == :leopard url 'http://www.titanium.free.fr/download/105/Deeper.dmg' elsif MacOS.version == :snow_leopard url 'http://www.titanium.free.fr/download/106/Deeper.dmg' elsif MacOS.version == :lion url 'http://www.titanium.free.fr/download/107/Deeper.dmg' elsif MacOS.version == :mountain_lion url 'http://www.titanium.free.fr/download/108/Deeper.dmg' elsif MacOS.version == :mavericks url 'http://www.titanium.free.fr/download/109/Deeper.dmg' else url 'http://www.titanium.free.fr/download/1010/Deeper.dmg' end homepage 'http://www.titanium.free.fr/downloaddeeper.php' license :unknown app 'Deeper.app' caveats do os_version_only('10.4', '10.5', '10.6', '10.7', '10.8', '10.9', '10.10') if [:leopard, :tiger].include? MacOS.version puts 'Deeper only runs from an Administrator account.' end end end
30.558824
76
0.683349
b9be5e0a5114204fa48a701ec8025250a1644c25
330
require "ruby-spacy" require "terminal-table" nlp = Spacy::Language.new("en_core_web_sm") doc = nlp.read("Where are you?") puts "Morph features of the third word: " + doc[2].morph.to_s puts "POS of the third word: " + doc[2].pos # Morph features of the third word: Case=Nom|Person=2|PronType=Prs # POS of the third word: PRON
25.384615
66
0.712121
18caab3590d237b8814137abc3b0db9ea470c221
253
require 'rails_helper' RSpec.describe "parent/special_events/show", type: :view do before(:each) do @parent_special_event = assign(:parent_special_event, SpecialRegistree.create!()) end it "renders attributes in <p>" do render end end
21.083333
85
0.731225
e91b342786777a9656c1ddea8b4e60fc2c46d923
2,172
require 'thinp_xml/listener' require 'thinp_xml/era/metadata' require 'rexml/document' require 'rexml/streamlistener' #---------------------------------------------------------------- module EraXML module EraParseDetail class Listener include ThinpXML::Base::ListenerUtils include REXML::StreamListener attr_reader :metadata def initialize @in_era_array = false @in_writeset = false @writesets = [] end def tag_start(tag, args) attr = to_hash(args) case tag when 'superblock' @superblock = Superblock.new(*get_fields(attr, SUPERBLOCK_FIELDS)) @era_array = Array.new(attr[:nr_blocks].to_i, 0) when 'writeset' @in_writeset = true @writeset_era = attr[:era].to_i @current_writeset = Array.new(attr[:nr_bits].to_i, false) when 'bit' raise "bit when not in a bitset" unless @in_writeset @current_writeset[attr[:block].to_i] = to_bool(attr[:value]) when 'era_array' @in_era_array = true when 'era' raise "not in era array" unless @in_era_array @era_array[attr[:block].to_i] = attr[:era].to_i else raise "unhandled tag '#{tag} #{attr.map {|x| x.inspect}.join(' ')}'" end end def tag_end(tag) case tag when 'writeset' @writesets << Writeset.new(@writeset_era, @current_writeset.size, @current_writeset) @in_writeset = false when 'era_array' @in_era_array = false when 'superblock' @metadata = Metadata.new(@superblock, @writesets, @era_array) end end def to_bool(str) case str when 'true' true when 'false' false else raise "bad bool value: #{str}" end end end end def read_xml(io) l = EraParseDetail::Listener.new REXML::Document.parse_stream(io, l) l.metadata end end #----------------------------------------------------------------
23.868132
78
0.524862
ed4a3e05d6e523d78899f0b6a70758efa8495c4b
3,817
# frozen_string_literal: true # Copyright The OpenTelemetry Authors # # SPDX-License-Identifier: Apache-2.0 require 'test_helper' describe OpenTelemetry::SDK::Resources::Resource do Resource = OpenTelemetry::SDK::Resources::Resource describe '.new' do it 'is private' do _(proc { Resource.new('k1' => 'v1') }).must_raise(NoMethodError) end end describe '.create' do it 'can be initialized with attributes' do expected_attributes = { 'k1' => 'v1', 'k2' => 'v2' } resource = Resource.create(expected_attributes) _(resource.attribute_enumerator.to_h).must_equal(expected_attributes) end it 'can be empty' do resource = Resource.create _(resource.attribute_enumerator.to_h).must_be_empty end it 'enforces keys are strings' do _(proc { Resource.create(k1: 'v1') }).must_raise(ArgumentError) end it 'enforces values are strings, ints, floats, or booleans' do _(proc { Resource.create('k1' => :v1) }).must_raise(ArgumentError) values = ['v1', 123, 456.78, false, true] values.each do |value| resource = Resource.create('k1' => value) _(resource.attribute_enumerator.first.last).must_equal(value) end end end describe '.telemetry_sdk' do it 'returns a resource for the telemetry sdk' do resource_attributes = Resource.telemetry_sdk.attribute_enumerator.to_h _(resource_attributes['telemetry.sdk.name']).must_equal('opentelemetry') _(resource_attributes['telemetry.sdk.language']).must_equal('ruby') _(resource_attributes['telemetry.sdk.version']).must_match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}/) end describe 'when the environment variable is present' do let(:expected_resource_attributes) do { 'key1' => 'value1', 'key2' => 'value2', 'telemetry.sdk.name' => 'opentelemetry', 'telemetry.sdk.language' => 'ruby', 'telemetry.sdk.version' => OpenTelemetry::SDK::VERSION } end it 'includes environment resources' do with_env('OTEL_RESOURCE_ATTRIBUTES' => 'key1=value1,key2=value2') do resource_attributes = Resource.telemetry_sdk.attribute_enumerator.to_h _(resource_attributes).must_equal(expected_resource_attributes) end end end end describe '.process' do let(:expected_resource_attributes) do { 'process.pid' => Process.pid, 'process.command' => $PROGRAM_NAME, 'process.runtime.name' => RUBY_ENGINE, 'process.runtime.version' => RUBY_VERSION, 'process.runtime.description' => RUBY_DESCRIPTION } end it 'returns a resource for the process and runtime' do resource_attributes = Resource.process.attribute_enumerator.to_h _(resource_attributes).must_equal(expected_resource_attributes) end end describe '#merge' do it 'merges two resources into a third' do res1 = Resource.create('k1' => 'v1', 'k2' => 'v2') res2 = Resource.create('k3' => 'v3', 'k4' => 'v4') res3 = res1.merge(res2) _(res3.attribute_enumerator.to_h).must_equal('k1' => 'v1', 'k2' => 'v2', 'k3' => 'v3', 'k4' => 'v4') _(res1.attribute_enumerator.to_h).must_equal('k1' => 'v1', 'k2' => 'v2') _(res2.attribute_enumerator.to_h).must_equal('k3' => 'v3', 'k4' => 'v4') end it 'overwrites receiver\'s keys' do res1 = Resource.create('k1' => 'v1', 'k2' => 'v2') res2 = Resource.create('k2' => '2v2', 'k3' => '2v3') res3 = res1.merge(res2) _(res3.attribute_enumerator.to_h).must_equal('k1' => 'v1', 'k2' => '2v2', 'k3' => '2v3') end end end
34.080357
95
0.614095
21816f9d25e0a0af53569581764e5243968a0cc8
2,297
module Snapshot class SimulatorLauncherConfiguration # both attr_accessor :languages attr_accessor :devices attr_accessor :add_photos attr_accessor :add_videos attr_accessor :clean attr_accessor :erase_simulator attr_accessor :headless attr_accessor :localize_simulator attr_accessor :dark_mode attr_accessor :reinstall_app attr_accessor :app_identifier attr_accessor :disable_slide_to_type attr_accessor :override_status_bar # xcode 8 attr_accessor :number_of_retries attr_accessor :stop_after_first_error attr_accessor :output_simulator_logs # runner attr_accessor :launch_args_set attr_accessor :output_directory # xcode 9 attr_accessor :concurrent_simulators alias concurrent_simulators? concurrent_simulators def initialize(snapshot_config: nil) @languages = snapshot_config[:languages] @devices = snapshot_config[:devices] @add_photos = snapshot_config[:add_photos] @add_videos = snapshot_config[:add_videos] @clean = snapshot_config[:clean] @erase_simulator = snapshot_config[:erase_simulator] @headless = snapshot_config[:headless] @localize_simulator = snapshot_config[:localize_simulator] @dark_mode = snapshot_config[:dark_mode] @reinstall_app = snapshot_config[:reinstall_app] @app_identifier = snapshot_config[:app_identifier] @number_of_retries = snapshot_config[:number_of_retries] @stop_after_first_error = snapshot_config[:stop_after_first_error] @output_simulator_logs = snapshot_config[:output_simulator_logs] @output_directory = snapshot_config[:output_directory] @concurrent_simulators = snapshot_config[:concurrent_simulators] @disable_slide_to_type = snapshot_config[:disable_slide_to_type] @override_status_bar = snapshot_config[:override_status_bar] launch_arguments = Array(snapshot_config[:launch_arguments]) # if more than 1 set of arguments, use a tuple with an index if launch_arguments.count == 0 @launch_args_set = [[""]] elsif launch_arguments.count == 1 @launch_args_set = [launch_arguments] else @launch_args_set = launch_arguments.map.with_index { |e, i| [i, e] } end end end end
36.460317
76
0.741837
5dacd07dd347f86c98a619e5ddce9a309c67aa84
360
# frozen_string_literal: true class Amazon::Workers::Images < Amazon::Workers::Base FEED_TYPE = '_POST_PRODUCT_IMAGE_DATA_' ENVELOPE_CLASS = 'Images' private def log_msg "Images feed: Shop(#{shop_id})/Marketplace(#{marketplace})" end def completed update_states :completed core_api.synced shop_id, :products end end
20
65
0.7
62b7ca4b034ec121f04ac4bd8117ad35e577226f
1,313
class Graphite2 < Formula desc "Smart font renderer for non-Roman scripts" homepage "https://graphite.sil.org/" url "https://github.com/silnrsi/graphite/releases/download/1.3.14/graphite2-1.3.14.tgz" sha256 "f99d1c13aa5fa296898a181dff9b82fb25f6cc0933dbaa7a475d8109bd54209d" license "LGPL-2.1" head "https://github.com/silnrsi/graphite.git" bottle do cellar :any sha256 "0831f474c920b66bbeab3f93a91fa019b82bfffcdd40e369fdab76372700e980" => :catalina sha256 "2f3abb971be03141e9eea54b87c6861d72865bd76fde73ae3161d64c40d51cd9" => :mojave sha256 "62e39dce0ae0440ac164edaab6e1351520bc5414ad509fc0b8d5c890500785bd" => :high_sierra sha256 "b2e120e5486b9c0b3c2eb5c2597e324d890319f502d2475fabdad1f4080f4e67" => :x86_64_linux end depends_on "cmake" => :build on_linux do depends_on "freetype" => :build end resource "testfont" do url "https://scripts.sil.org/pub/woff/fonts/Simple-Graphite-Font.ttf" sha256 "7e573896bbb40088b3a8490f83d6828fb0fd0920ac4ccdfdd7edb804e852186a" end def install system "cmake", ".", *std_cmake_args system "make", "install" end test do resource("testfont").stage do shape = shell_output("#{bin}/gr2fonttest Simple-Graphite-Font.ttf 'abcde'") assert_match /67.*36.*37.*38.*71/m, shape end end end
32.825
94
0.753998
f8f06068000803a5d081ceb944527a9c82004936
579
class UsersController < ApplicationController def index @users = User.all end def show @user = User.find(params[:id]) end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) @user.update(user_params) redirect_to @user end def new @user = User.new end def create @user = User.new(user_params) if @user.save redirect_to @user else render :new end end private def user_params params.require(:user) .permit(:username, :email, :password) end end
14.121951
45
0.618307
6aa78b951716bc8cb36ca9a21606f13f723ed01a
3,969
class PagesController < ApplicationController before_action :define_as_page_pro, only: [:landing_page_pro, :faq_pro] def landing_page_pro @users_count = Rails.cache.fetch(:users_count, expires_in: 30.seconds) { Counter.total_users } @confirmed_matched_users_count = Rails.cache.fetch(:confirmed_matched_users_count, expires_in: 30.minutes) { Match.confirmed.count } @vaccination_centers_count = Rails.cache.fetch(:vaccination_centers_count, expires_in: 30.minutes) { VaccinationCenter.confirmed.count } @typeform_url = "https://form.typeform.com/to/Gj2d2iue" @reviews = Review.where(from: "volunteer") @faq_items = FaqItem.where(area: "pro").limit(4) end def benevoles @volunteers = Volunteer.where(anon: false).order(sort_name: :asc) + Volunteer.where(anon: true).order(sort_name: :asc) end def donateurs @force = params[:force].present? @debug = params[:debug].present? @ulule_buddy_orders = UluleBuddyOrder.all.each_with_object({}) do |e, m| m[e.order_id] = { name: e.name, picture_path: e.picture_path } end data = UluleService.new("covidliste", ENV["ULULE_API_KEY"]).data(@force) @project = data[:project] @bronze_orders = data[:bronze_orders] @silver_orders = data[:silver_orders] @gold_orders = data[:gold_orders] @diamond_orders = data[:diamond_orders] end def sponsors @sponsors = Sponsor.all end def contact @contact_items = FaqItem.where(category: "Collaboration et contact") end def presse end def carte @vaccination_centers = VaccinationCenter.confirmed @map_areas = [ { "label" => "France métropolitaine", "lon" => 2.3, "lat" => 47.1, "zoom" => 5.5 } # { # "label" => "Guyane", # "lon" => -53.02730090442361, # "lat" => 4, # "zoom" => 7 # }, # { # "label" => "Guadeloupe", # "lon" => -61.5, # "lat" => 16.176021024448076, # "zoom" => 10 # }, # { # "label" => "La Réunion", # "lon" => 55.53913649067738, # "lat" => -21.153674695744286, # "zoom" => 10 # }, # { # "label" => "Martinique", # "lon" => -60.97336870145841, # "lat" => 14.632175285699219, # "zoom" => 10 # }, # { # "label" => "Mayotte", # "lon" => 45.16242028163609, # "lat" => -12.831199035192768, # "zoom" => 11 # } ] end def mentions_legales end def privacy end def algorithme @faq_item = FaqItem.find_by(title: "Comment fonctionne la sélection des volontaires ?") end def faq @faq_items = FaqItem.where(area: "main") respond_to do |format| format.html format.json { render json: @faq_items.to_json } end end def faq_pro @faq_items = FaqItem.where(area: "pro") respond_to do |format| format.html format.json { render json: @faq_items.to_json } end end def robots render "pages/robots", layout: false, content_type: "text/plain" end StaticPage.all.each do |page| page_slug = page.slug.underscore define_method page_slug do page_slug_as_string = page_slug.to_s case page_slug_as_string when "cookies" @meta_title = "Notre politique liées aux cookies" when "mentions_legales" @meta_title = "Mentions légales - Covidliste" when "cgu_volontaires" @meta_title = "CGU - Volontaires - Covidliste" when "cgu_pro" @meta_title = "CGU - Professionnels de santé - Covidliste" when "privacy_volontaires" @meta_title = "Protection des données - Volontaires - Covidliste" when "privacy_pro" @meta_title = "Protection des données - Professionnels de santé - Covidliste" end @body = page.body render "pages/static" end end private def skip_pundit? true end end
26.46
140
0.610229
1857b7334b4e6eddf1c475d61e200457a5e050fa
33,935
# Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'date' require 'google/apis/core/base_service' require 'google/apis/core/json_representation' require 'google/apis/core/hashable' require 'google/apis/errors' module Google module Apis module CloudresourcemanagerV1beta1 # Identifying information for a single ancestor of a project. class Ancestor include Google::Apis::Core::Hashable # A container to reference an id for any resource type. A `resource` in Google # Cloud Platform is a generic term for something you (a developer) may want to # interact with through one of our API's. Some examples are an App Engine app, # a Compute Engine instance, a Cloud SQL database, and so on. # Corresponds to the JSON property `resourceId` # @return [Google::Apis::CloudresourcemanagerV1beta1::ResourceId] attr_accessor :resource_id def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @resource_id = args[:resource_id] if args.key?(:resource_id) end end # Specifies the audit configuration for a service. # The configuration determines which permission types are logged, and what # identities, if any, are exempted from logging. # An AuditConfig must have one or more AuditLogConfigs. # If there are AuditConfigs for both `allServices` and a specific service, # the union of the two AuditConfigs is used for that service: the log_types # specified in each AuditConfig are enabled, and the exempted_members in each # AuditLogConfig are exempted. # Example Policy with multiple AuditConfigs: # ` # "audit_configs": [ # ` # "service": "allServices" # "audit_log_configs": [ # ` # "log_type": "DATA_READ", # "exempted_members": [ # "user:[email protected]" # ] # `, # ` # "log_type": "DATA_WRITE", # `, # ` # "log_type": "ADMIN_READ", # ` # ] # `, # ` # "service": "fooservice.googleapis.com" # "audit_log_configs": [ # ` # "log_type": "DATA_READ", # `, # ` # "log_type": "DATA_WRITE", # "exempted_members": [ # "user:[email protected]" # ] # ` # ] # ` # ] # ` # For fooservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ # logging. It also exempts [email protected] from DATA_READ logging, and # [email protected] from DATA_WRITE logging. class AuditConfig include Google::Apis::Core::Hashable # The configuration for logging of each type of permission. # Corresponds to the JSON property `auditLogConfigs` # @return [Array<Google::Apis::CloudresourcemanagerV1beta1::AuditLogConfig>] attr_accessor :audit_log_configs # Specifies a service that will be enabled for audit logging. # For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. # `allServices` is a special value that covers all services. # Corresponds to the JSON property `service` # @return [String] attr_accessor :service def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @audit_log_configs = args[:audit_log_configs] if args.key?(:audit_log_configs) @service = args[:service] if args.key?(:service) end end # Provides the configuration for logging a type of permissions. # Example: # ` # "audit_log_configs": [ # ` # "log_type": "DATA_READ", # "exempted_members": [ # "user:[email protected]" # ] # `, # ` # "log_type": "DATA_WRITE", # ` # ] # ` # This enables 'DATA_READ' and 'DATA_WRITE' logging, while exempting # [email protected] from DATA_READ logging. class AuditLogConfig include Google::Apis::Core::Hashable # Specifies the identities that do not cause logging for this type of # permission. # Follows the same format of Binding.members. # Corresponds to the JSON property `exemptedMembers` # @return [Array<String>] attr_accessor :exempted_members # The log type that this config enables. # Corresponds to the JSON property `logType` # @return [String] attr_accessor :log_type def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @exempted_members = args[:exempted_members] if args.key?(:exempted_members) @log_type = args[:log_type] if args.key?(:log_type) end end # Associates `members` with a `role`. class Binding include Google::Apis::Core::Hashable # Represents an expression text. Example: # title: "User account presence" # description: "Determines whether the request has a user account" # expression: "size(request.user) > 0" # Corresponds to the JSON property `condition` # @return [Google::Apis::CloudresourcemanagerV1beta1::Expr] attr_accessor :condition # Specifies the identities requesting access for a Cloud Platform resource. # `members` can have the following values: # * `allUsers`: A special identifier that represents anyone who is # on the internet; with or without a Google account. # * `allAuthenticatedUsers`: A special identifier that represents anyone # who is authenticated with a Google account or a service account. # * `user:`emailid``: An email address that represents a specific Google # account. For example, `[email protected]` . # * `serviceAccount:`emailid``: An email address that represents a service # account. For example, `[email protected]`. # * `group:`emailid``: An email address that represents a Google group. # For example, `[email protected]`. # * `domain:`domain``: The G Suite domain (primary) that represents all the # users of that domain. For example, `google.com` or `example.com`. # Corresponds to the JSON property `members` # @return [Array<String>] attr_accessor :members # Role that is assigned to `members`. # For example, `roles/viewer`, `roles/editor`, or `roles/owner`. # Corresponds to the JSON property `role` # @return [String] attr_accessor :role def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @condition = args[:condition] if args.key?(:condition) @members = args[:members] if args.key?(:members) @role = args[:role] if args.key?(:role) end end # A generic empty message that you can re-use to avoid defining duplicated # empty messages in your APIs. A typical example is to use it as the request # or the response type of an API method. For instance: # service Foo ` # rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); # ` # The JSON representation for `Empty` is empty JSON object ````. class Empty include Google::Apis::Core::Hashable def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) end end # Represents an expression text. Example: # title: "User account presence" # description: "Determines whether the request has a user account" # expression: "size(request.user) > 0" class Expr include Google::Apis::Core::Hashable # An optional description of the expression. This is a longer text which # describes the expression, e.g. when hovered over it in a UI. # Corresponds to the JSON property `description` # @return [String] attr_accessor :description # Textual representation of an expression in # Common Expression Language syntax. # The application context of the containing message determines which # well-known feature set of CEL is supported. # Corresponds to the JSON property `expression` # @return [String] attr_accessor :expression # An optional string indicating the location of the expression for error # reporting, e.g. a file name and a position in the file. # Corresponds to the JSON property `location` # @return [String] attr_accessor :location # An optional title for the expression, i.e. a short string describing # its purpose. This can be used e.g. in UIs which allow to enter the # expression. # Corresponds to the JSON property `title` # @return [String] attr_accessor :title def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @description = args[:description] if args.key?(:description) @expression = args[:expression] if args.key?(:expression) @location = args[:location] if args.key?(:location) @title = args[:title] if args.key?(:title) end end # Metadata describing a long running folder operation class FolderOperation include Google::Apis::Core::Hashable # The resource name of the folder or organization we are either creating # the folder under or moving the folder to. # Corresponds to the JSON property `destinationParent` # @return [String] attr_accessor :destination_parent # The display name of the folder. # Corresponds to the JSON property `displayName` # @return [String] attr_accessor :display_name # The type of this operation. # Corresponds to the JSON property `operationType` # @return [String] attr_accessor :operation_type # The resource name of the folder's parent. # Only applicable when the operation_type is MOVE. # Corresponds to the JSON property `sourceParent` # @return [String] attr_accessor :source_parent def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @destination_parent = args[:destination_parent] if args.key?(:destination_parent) @display_name = args[:display_name] if args.key?(:display_name) @operation_type = args[:operation_type] if args.key?(:operation_type) @source_parent = args[:source_parent] if args.key?(:source_parent) end end # A classification of the Folder Operation error. class FolderOperationError include Google::Apis::Core::Hashable # The type of operation error experienced. # Corresponds to the JSON property `errorMessageId` # @return [String] attr_accessor :error_message_id def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @error_message_id = args[:error_message_id] if args.key?(:error_message_id) end end # The request sent to the # GetAncestry # method. class GetAncestryRequest include Google::Apis::Core::Hashable def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) end end # Response from the GetAncestry method. class GetAncestryResponse include Google::Apis::Core::Hashable # Ancestors are ordered from bottom to top of the resource hierarchy. The # first ancestor is the project itself, followed by the project's parent, # etc. # Corresponds to the JSON property `ancestor` # @return [Array<Google::Apis::CloudresourcemanagerV1beta1::Ancestor>] attr_accessor :ancestor def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @ancestor = args[:ancestor] if args.key?(:ancestor) end end # Request message for `GetIamPolicy` method. class GetIamPolicyRequest include Google::Apis::Core::Hashable def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) end end # The response returned from the `ListOrganizations` method. class ListOrganizationsResponse include Google::Apis::Core::Hashable # A pagination token to be used to retrieve the next page of results. If the # result is too large to fit within the page size specified in the request, # this field will be set with a token that can be used to fetch the next page # of results. If this field is empty, it indicates that this response # contains the last page of results. # Corresponds to the JSON property `nextPageToken` # @return [String] attr_accessor :next_page_token # The list of Organizations that matched the list query, possibly paginated. # Corresponds to the JSON property `organizations` # @return [Array<Google::Apis::CloudresourcemanagerV1beta1::Organization>] attr_accessor :organizations def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @next_page_token = args[:next_page_token] if args.key?(:next_page_token) @organizations = args[:organizations] if args.key?(:organizations) end end # A page of the response received from the # ListProjects # method. # A paginated response where more pages are available has # `next_page_token` set. This token can be used in a subsequent request to # retrieve the next request page. class ListProjectsResponse include Google::Apis::Core::Hashable # Pagination token. # If the result set is too large to fit in a single response, this token # is returned. It encodes the position of the current result cursor. # Feeding this value into a new list request with the `page_token` parameter # gives the next page of the results. # When `next_page_token` is not filled in, there is no next page and # the list returned is the last page in the result set. # Pagination tokens have a limited lifetime. # Corresponds to the JSON property `nextPageToken` # @return [String] attr_accessor :next_page_token # The list of Projects that matched the list filter. This list can # be paginated. # Corresponds to the JSON property `projects` # @return [Array<Google::Apis::CloudresourcemanagerV1beta1::Project>] attr_accessor :projects def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @next_page_token = args[:next_page_token] if args.key?(:next_page_token) @projects = args[:projects] if args.key?(:projects) end end # The root node in the resource hierarchy to which a particular entity's # (e.g., company) resources belong. class Organization include Google::Apis::Core::Hashable # Timestamp when the Organization was created. Assigned by the server. # @OutputOnly # Corresponds to the JSON property `creationTime` # @return [String] attr_accessor :creation_time # A human-readable string that refers to the Organization in the # GCP Console UI. This string is set by the server and cannot be # changed. The string will be set to the primary domain (for example, # "google.com") of the G Suite customer that owns the organization. # @OutputOnly # Corresponds to the JSON property `displayName` # @return [String] attr_accessor :display_name # The organization's current lifecycle state. Assigned by the server. # @OutputOnly # Corresponds to the JSON property `lifecycleState` # @return [String] attr_accessor :lifecycle_state # Output Only. The resource name of the organization. This is the # organization's relative path in the API. Its format is # "organizations/[organization_id]". For example, "organizations/1234". # Corresponds to the JSON property `name` # @return [String] attr_accessor :name # An immutable id for the Organization that is assigned on creation. This # should be omitted when creating a new Organization. # This field is read-only. # Corresponds to the JSON property `organizationId` # @return [String] attr_accessor :organization_id # The entity that owns an Organization. The lifetime of the Organization and # all of its descendants are bound to the `OrganizationOwner`. If the # `OrganizationOwner` is deleted, the Organization and all its descendants will # be deleted. # Corresponds to the JSON property `owner` # @return [Google::Apis::CloudresourcemanagerV1beta1::OrganizationOwner] attr_accessor :owner def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @creation_time = args[:creation_time] if args.key?(:creation_time) @display_name = args[:display_name] if args.key?(:display_name) @lifecycle_state = args[:lifecycle_state] if args.key?(:lifecycle_state) @name = args[:name] if args.key?(:name) @organization_id = args[:organization_id] if args.key?(:organization_id) @owner = args[:owner] if args.key?(:owner) end end # The entity that owns an Organization. The lifetime of the Organization and # all of its descendants are bound to the `OrganizationOwner`. If the # `OrganizationOwner` is deleted, the Organization and all its descendants will # be deleted. class OrganizationOwner include Google::Apis::Core::Hashable # The G Suite customer id used in the Directory API. # Corresponds to the JSON property `directoryCustomerId` # @return [String] attr_accessor :directory_customer_id def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @directory_customer_id = args[:directory_customer_id] if args.key?(:directory_customer_id) end end # Defines an Identity and Access Management (IAM) policy. It is used to # specify access control policies for Cloud Platform resources. # A `Policy` consists of a list of `bindings`. A `binding` binds a list of # `members` to a `role`, where the members can be user accounts, Google groups, # Google domains, and service accounts. A `role` is a named list of permissions # defined by IAM. # **JSON Example** # ` # "bindings": [ # ` # "role": "roles/owner", # "members": [ # "user:[email protected]", # "group:[email protected]", # "domain:google.com", # "serviceAccount:[email protected]" # ] # `, # ` # "role": "roles/viewer", # "members": ["user:[email protected]"] # ` # ] # ` # **YAML Example** # bindings: # - members: # - user:[email protected] # - group:[email protected] # - domain:google.com # - serviceAccount:[email protected] # role: roles/owner # - members: # - user:[email protected] # role: roles/viewer # For a description of IAM and its features, see the # [IAM developer's guide](https://cloud.google.com/iam/docs). class Policy include Google::Apis::Core::Hashable # Specifies cloud audit logging configuration for this policy. # Corresponds to the JSON property `auditConfigs` # @return [Array<Google::Apis::CloudresourcemanagerV1beta1::AuditConfig>] attr_accessor :audit_configs # Associates a list of `members` to a `role`. # `bindings` with no members will result in an error. # Corresponds to the JSON property `bindings` # @return [Array<Google::Apis::CloudresourcemanagerV1beta1::Binding>] attr_accessor :bindings # `etag` is used for optimistic concurrency control as a way to help # prevent simultaneous updates of a policy from overwriting each other. # It is strongly suggested that systems make use of the `etag` in the # read-modify-write cycle to perform policy updates in order to avoid race # conditions: An `etag` is returned in the response to `getIamPolicy`, and # systems are expected to put that etag in the request to `setIamPolicy` to # ensure that their change will be applied to the same version of the policy. # If no `etag` is provided in the call to `setIamPolicy`, then the existing # policy is overwritten blindly. # Corresponds to the JSON property `etag` # NOTE: Values are automatically base64 encoded/decoded in the client library. # @return [String] attr_accessor :etag # Deprecated. # Corresponds to the JSON property `version` # @return [Fixnum] attr_accessor :version def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @audit_configs = args[:audit_configs] if args.key?(:audit_configs) @bindings = args[:bindings] if args.key?(:bindings) @etag = args[:etag] if args.key?(:etag) @version = args[:version] if args.key?(:version) end end # A Project is a high-level Google Cloud Platform entity. It is a # container for ACLs, APIs, App Engine Apps, VMs, and other # Google Cloud Platform resources. class Project include Google::Apis::Core::Hashable # Creation time. # Read-only. # Corresponds to the JSON property `createTime` # @return [String] attr_accessor :create_time # The labels associated with this Project. # Label keys must be between 1 and 63 characters long and must conform # to the following regular expression: \[a-z\](\[-a-z0-9\]*\[a-z0-9\])?. # Label values must be between 0 and 63 characters long and must conform # to the regular expression (\[a-z\](\[-a-z0-9\]*\[a-z0-9\])?)?. A label # value can be empty. # No more than 256 labels can be associated with a given resource. # Clients should store labels in a representation such as JSON that does not # depend on specific characters being disallowed. # Example: <code>"environment" : "dev"</code> # Read-write. # Corresponds to the JSON property `labels` # @return [Hash<String,String>] attr_accessor :labels # The Project lifecycle state. # Read-only. # Corresponds to the JSON property `lifecycleState` # @return [String] attr_accessor :lifecycle_state # The optional user-assigned display name of the Project. # When present it must be between 4 to 30 characters. # Allowed characters are: lowercase and uppercase letters, numbers, # hyphen, single-quote, double-quote, space, and exclamation point. # Example: <code>My Project</code> # Read-write. # Corresponds to the JSON property `name` # @return [String] attr_accessor :name # A container to reference an id for any resource type. A `resource` in Google # Cloud Platform is a generic term for something you (a developer) may want to # interact with through one of our API's. Some examples are an App Engine app, # a Compute Engine instance, a Cloud SQL database, and so on. # Corresponds to the JSON property `parent` # @return [Google::Apis::CloudresourcemanagerV1beta1::ResourceId] attr_accessor :parent # The unique, user-assigned ID of the Project. # It must be 6 to 30 lowercase letters, digits, or hyphens. # It must start with a letter. # Trailing hyphens are prohibited. # Example: <code>tokyo-rain-123</code> # Read-only after creation. # Corresponds to the JSON property `projectId` # @return [String] attr_accessor :project_id # The number uniquely identifying the project. # Example: <code>415104041262</code> # Read-only. # Corresponds to the JSON property `projectNumber` # @return [Fixnum] attr_accessor :project_number def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @create_time = args[:create_time] if args.key?(:create_time) @labels = args[:labels] if args.key?(:labels) @lifecycle_state = args[:lifecycle_state] if args.key?(:lifecycle_state) @name = args[:name] if args.key?(:name) @parent = args[:parent] if args.key?(:parent) @project_id = args[:project_id] if args.key?(:project_id) @project_number = args[:project_number] if args.key?(:project_number) end end # A status object which is used as the `metadata` field for the Operation # returned by CreateProject. It provides insight for when significant phases of # Project creation have completed. class ProjectCreationStatus include Google::Apis::Core::Hashable # Creation time of the project creation workflow. # Corresponds to the JSON property `createTime` # @return [String] attr_accessor :create_time # True if the project can be retrieved using GetProject. No other operations # on the project are guaranteed to work until the project creation is # complete. # Corresponds to the JSON property `gettable` # @return [Boolean] attr_accessor :gettable alias_method :gettable?, :gettable # True if the project creation process is complete. # Corresponds to the JSON property `ready` # @return [Boolean] attr_accessor :ready alias_method :ready?, :ready def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @create_time = args[:create_time] if args.key?(:create_time) @gettable = args[:gettable] if args.key?(:gettable) @ready = args[:ready] if args.key?(:ready) end end # A container to reference an id for any resource type. A `resource` in Google # Cloud Platform is a generic term for something you (a developer) may want to # interact with through one of our API's. Some examples are an App Engine app, # a Compute Engine instance, a Cloud SQL database, and so on. class ResourceId include Google::Apis::Core::Hashable # Required field for the type-specific id. This should correspond to the id # used in the type-specific API's. # Corresponds to the JSON property `id` # @return [String] attr_accessor :id # Required field representing the resource type this id is for. # At present, the valid types are "project", "folder", and "organization". # Corresponds to the JSON property `type` # @return [String] attr_accessor :type def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @id = args[:id] if args.key?(:id) @type = args[:type] if args.key?(:type) end end # Request message for `SetIamPolicy` method. class SetIamPolicyRequest include Google::Apis::Core::Hashable # Defines an Identity and Access Management (IAM) policy. It is used to # specify access control policies for Cloud Platform resources. # A `Policy` consists of a list of `bindings`. A `binding` binds a list of # `members` to a `role`, where the members can be user accounts, Google groups, # Google domains, and service accounts. A `role` is a named list of permissions # defined by IAM. # **JSON Example** # ` # "bindings": [ # ` # "role": "roles/owner", # "members": [ # "user:[email protected]", # "group:[email protected]", # "domain:google.com", # "serviceAccount:[email protected]" # ] # `, # ` # "role": "roles/viewer", # "members": ["user:[email protected]"] # ` # ] # ` # **YAML Example** # bindings: # - members: # - user:[email protected] # - group:[email protected] # - domain:google.com # - serviceAccount:[email protected] # role: roles/owner # - members: # - user:[email protected] # role: roles/viewer # For a description of IAM and its features, see the # [IAM developer's guide](https://cloud.google.com/iam/docs). # Corresponds to the JSON property `policy` # @return [Google::Apis::CloudresourcemanagerV1beta1::Policy] attr_accessor :policy # OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only # the fields in the mask will be modified. If no mask is provided, the # following default mask is used: # paths: "bindings, etag" # This field is only used by Cloud IAM. # Corresponds to the JSON property `updateMask` # @return [String] attr_accessor :update_mask def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @policy = args[:policy] if args.key?(:policy) @update_mask = args[:update_mask] if args.key?(:update_mask) end end # Request message for `TestIamPermissions` method. class TestIamPermissionsRequest include Google::Apis::Core::Hashable # The set of permissions to check for the `resource`. Permissions with # wildcards (such as '*' or 'storage.*') are not allowed. For more # information see # [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). # Corresponds to the JSON property `permissions` # @return [Array<String>] attr_accessor :permissions def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @permissions = args[:permissions] if args.key?(:permissions) end end # Response message for `TestIamPermissions` method. class TestIamPermissionsResponse include Google::Apis::Core::Hashable # A subset of `TestPermissionsRequest.permissions` that the caller is # allowed. # Corresponds to the JSON property `permissions` # @return [Array<String>] attr_accessor :permissions def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @permissions = args[:permissions] if args.key?(:permissions) end end # The request sent to the UndeleteProject # method. class UndeleteProjectRequest include Google::Apis::Core::Hashable def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) end end end end end
38.00112
100
0.609813
f7e64ca9853b36dfe0a519e5e50d98e0dded4634
1,820
Puppet::Functions.create_function(:'consul::validate_checks') do local_types do type 'HashOrArray = Variant[Hash,Array]' end dispatch :validate_checks do param 'HashOrArray', :obj end def validate_checks(obj) case obj when Array obj.each do |c| validate_checks(c) end when Hash if ( (obj.key?("http") || ( obj.key?("script") || obj.key?("args") ) || obj.key?("tcp")) && (! obj.key?("interval")) ) raise Puppet::ParseError.new('interval must be defined for tcp, http, and script checks') end if obj.key?("ttl") if (obj.key?("http") || ( obj.key?("args") || obj.key?("script") ) || obj.key?("tcp") || obj.key?("interval")) raise Puppet::ParseError.new('script, http, tcp, and interval must not be defined for ttl checks') end elsif obj.key?("http") if (( obj.key?("args") || obj.key?("script") ) || obj.key?("tcp")) raise Puppet::ParseError.new('script and tcp must not be defined for http checks') end elsif obj.key?("tcp") if (obj.key?("http") || ( obj.key?("args") || obj.key?("script") )) raise Puppet::ParseError.new('script and http must not be defined for tcp checks') end elsif ( obj.key?("args") || obj.key?("script") ) if (obj.key?("http") || obj.key?("tcp")) raise Puppet::ParseError.new('http and tcp must not be defined for script checks') end else raise Puppet::ParseError.new('One of ttl, script, tcp, or http must be defined.') end else raise Puppet::ParseError.new("Unable to handle object of type <%s>" % obj.class.to_s) end end end
40.444444
130
0.543407
287b35daa01fe88e14e0d43ae0996888861a6f29
13,259
require File.join(File.dirname(__FILE__), '../test_helper.rb') class GatewayTest < Test::Unit::TestCase include TestHelper def setup @gateway = XeroGateway::Gateway.new(CONSUMER_KEY, CONSUMER_SECRET) end context "GET methods" do should :get_invoices do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("invoices.xml"), :code => "200")) result = @gateway.get_invoices assert result.response_item.first.is_a? XeroGateway::Invoice end should "get invoices by contact ids" do contact_id = 'a99a9aaa-9999-99a9-9aa9-aaaaaa9a9999' stub_response = stub(:plain_body => get_file_as_string("invoices.xml"), :code => "200") expected_url = /.+\/Invoices\?ContactIDs=#{contact_id}/ XeroGateway::OAuth.any_instance .stubs(:get) .with(regexp_matches(expected_url), anything) .returns(stub_response) result = @gateway.get_invoices(:contact_ids => [contact_id]) assert result.response_item.first.is_a? XeroGateway::Invoice end should :get_invoice do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("invoice.xml"), :code => "200")) result = @gateway.get_invoice('a99a9aaa-9999-99a9-9aa9-aaaaaa9a9999') assert result.response_item.is_a? XeroGateway::Invoice end should :get_credit_notes do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("credit_notes.xml"), :code => "200")) result = @gateway.get_credit_notes assert result.response_item.first.is_a? XeroGateway::CreditNote end should :get_credit_note do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("credit_notes.xml"), :code => "200")) result = @gateway.get_credit_note('a2b4370d-efd2-440d-894e-082f21d0b10a') assert result.response_item.first.is_a? XeroGateway::CreditNote end should :get_bank_transactions do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("bank_transaction.xml"), :code => "200")) result = @gateway.get_bank_transactions assert result.response_item.is_a? XeroGateway::BankTransaction end should :get_bank_transaction do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("bank_transactions.xml"), :code => "200")) result = @gateway.get_bank_transaction('c09661a2-a954-4e34-98df-f8b6d1dc9b19') assert result.response_item.is_a? XeroGateway::BankTransaction end should :get_manual_journals do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("manual_journals.xml"), :code => "200")) result = @gateway.get_manual_journals assert result.response_item.is_a? XeroGateway::ManualJournal end should :get_payments do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("payments.xml"), :code => "200")) result = @gateway.get_payments assert result.response_item.first.is_a? XeroGateway::Payment end should :get_payment do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("payments.xml"), :code => "200")) result = @gateway.get_payment('1234') assert result.response_item.first.is_a? XeroGateway::Payment end should :get_contacts do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("contacts.xml"), :code => "200")) result = @gateway.get_contacts assert result.response_item.first.is_a? XeroGateway::Contact end should :get_contact_by_id do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("contact.xml"), :code => "200")) result = @gateway.get_contact_by_id('a99a9aaa-9999-99a9-9aa9-aaaaaa9a9999') assert result.response_item.is_a? XeroGateway::Contact end should :get_contact_by_number do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("contact.xml"), :code => "200")) result = @gateway.get_contact_by_number('12345') assert result.response_item.is_a? XeroGateway::Contact end should :get_contact_groups do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("contact_groups.xml"), :code => "200")) result = @gateway.get_contact_groups assert result.response_item.first.is_a? XeroGateway::ContactGroup end should :get_contact_group_by_id do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("contact_group.xml"), :code => "200")) result = @gateway.get_contact_group_by_id('a99a9aaa-9999-99a9-9aa9-aaaaaa9a9999') assert result.response_item.is_a? XeroGateway::ContactGroup end context :get_report do should "get a BankStatements report" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("reports/bank_statement.xml"), :code => "200")) result = @gateway.get_report("BankStatement", bank_account_id: "c09661a2-a954-4e34-98df-f8b6d1dc9b19") assert result.response_item.is_a? XeroGateway::Report end should "get a AgedPayablesByContact report" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("reports/aged_payables_by_contact.xml"), :code => "200")) result = @gateway.get_report("AgedPayablesByContact", contactID: "c09661a2-a954-4e34-98df-f8b6d1dc9b19") assert result.response_item.is_a? XeroGateway::Report end should "get a AgedReceivablesByContact report" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("reports/aged_receivables_by_contact.xml"), :code => "200")) result = @gateway.get_report("AgedReceivablesByContact", contactID: "c09661a2-a954-4e34-98df-f8b6d1dc9b19") assert result.response_item.is_a? XeroGateway::Report end should "get a BalanceSheet report" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("reports/balance_sheet.xml"), :code => "200")) result = @gateway.get_report("BalanceSheet") assert result.response_item.is_a? XeroGateway::Report end should "get a BankSummary report" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("reports/bank_summary.xml"), :code => "200")) result = @gateway.get_report("BankSummary") assert result.response_item.is_a? XeroGateway::Report end should "get a ExecutiveSummary report" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("reports/executive_summary.xml"), :code => "200")) result = @gateway.get_report("ExecutiveSummary") assert result.response_item.is_a? XeroGateway::Report end should "get a ProfitAndLoss report" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("reports/profit_and_loss.xml"), :code => "200")) result = @gateway.get_report("ProfitAndLoss") assert result.response_item.is_a? XeroGateway::Report end should "get a TrialBalance report" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("reports/trial_balance.xml"), :code => "200")) result = @gateway.get_report("TrialBalance") assert result.response_item.is_a? XeroGateway::Report end end end context "with error handling" do should "handle token expired" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("token_expired"), :code => "401")) assert_raises XeroGateway::OAuth::TokenExpired do @gateway.get_accounts end end should "handle invalid request tokens" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("invalid_request_token"), :code => "401")) assert_raises XeroGateway::OAuth::TokenInvalid do @gateway.get_accounts end end should "handle invalid consumer key" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("invalid_consumer_key"), :code => "401")) assert_raises XeroGateway::OAuth::TokenInvalid do @gateway.get_accounts end end should "handle rate limit exceeded" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("rate_limit_exceeded"), :code => "401")) assert_raises XeroGateway::OAuth::RateLimitExceeded do @gateway.get_accounts end end should "handle unknown errors" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("bogus_oauth_error"), :code => "401")) assert_raises XeroGateway::OAuth::UnknownError do @gateway.get_accounts end end should "handle errors without advice" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("error_without_advice"), :code => "401")) begin @gateway.get_accounts rescue XeroGateway::OAuth::UnknownError => e assert_equal "some_error: No description found: oauth_problem=some_error&oauth_problem_advice=\n", e.message end end should "handle ApiExceptions" do XeroGateway::OAuth.any_instance.stubs(:put).returns(stub(:plain_body => get_file_as_string("api_exception.xml"), :code => "400")) assert_raises XeroGateway::ApiException do @gateway.create_invoice(XeroGateway::Invoice.new) end end should "handle invoices not found" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("api_exception.xml"), :code => "404")) assert_raises XeroGateway::InvoiceNotFoundError do @gateway.get_invoice('unknown-invoice-id') end end should "handle bank transactions not found" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("api_exception.xml"), :code => "404")) assert_raises XeroGateway::BankTransactionNotFoundError do @gateway.get_bank_transaction('unknown-bank-transaction-id') end end should "handle credit notes not found" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("api_exception.xml"), :code => "404")) assert_raises XeroGateway::CreditNoteNotFoundError do @gateway.get_credit_note('unknown-credit-note-id') end end should "handle manual journals not found" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("api_exception.xml"), :code => "404")) assert_raises XeroGateway::ManualJournalNotFoundError do @gateway.get_manual_journal('unknown-manual-journal-id') end end should "handle payments not found" do XeroGateway::OAuth.any_instance.stubs(:get).returns(stub(:plain_body => get_file_as_string("api_exception.xml"), :code => "404")) assert_raises XeroGateway::PaymentNotFoundError do @gateway.get_payments end end should "handle random root elements" do XeroGateway::OAuth.any_instance.stubs(:put).returns(stub(:plain_body => "<RandomRootElement></RandomRootElement>", :code => "200")) assert_raises XeroGateway::UnparseableResponse do @gateway.create_invoice(XeroGateway::Invoice.new) end end should "handle no root element" do XeroGateway::OAuth.any_instance.stubs(:put).returns(stub(:plain_body => get_file_as_string("no_certificates_registered"), :code => 400)) assert_raises RuntimeError do @gateway.create_invoice(XeroGateway::Invoice.new) end end end def test_unknown_error_handling if STUB_XERO_CALLS @gateway.xero_url = "DUMMY_URL" @gateway.stubs(:http_get).with {|client, url, params| url =~ /Invoices\/AN_INVALID_ID$/ }.returns(get_file_as_string("unknown_error.xml")) end result = @gateway.get_invoice("AN_INVALID_ID") assert !result.success? assert_equal 1, result.errors.size assert !result.errors.first.type.nil? assert !result.errors.first.description.nil? end def test_object_not_found_error_handling if STUB_XERO_CALLS @gateway.xero_url = "DUMMY_URL" @gateway.stubs(:http_get).with {|client, url, params| url =~ /Invoices\/UNKNOWN_INVOICE_NO$/ }.returns(get_file_as_string("invoice_not_found_error.xml")) end result = @gateway.get_invoice("UNKNOWN_INVOICE_NO") assert !result.success? assert_equal 1, result.errors.size assert_equal "Xero.API.Library.Exceptions.ObjectDoesNotExistException", result.errors.first.type assert !result.errors.first.description.nil? end end
44.049834
159
0.710008
f8f659658a5442750b2753d0454b8364c39a6618
15,825
require "spec_helper" describe Mongoid::Relations::Accessors do describe "\#{getter}?" do let(:person) do Person.create end context "when the relation is a has one" do context "when the relation exists" do let!(:game) do person.build_game end it "returns true" do person.should have_game end end context "when the relation does not exist" do context "when not autobuilding" do it "returns false" do person.should_not have_game end end context "when autobuilding" do it "returns false" do person.should_not have_book end end end end context "when the relation is a has many" do context "when the relation has documents" do let!(:post) do person.posts.build end it "returns true" do person.should have_posts end end context "when the relation does not have documents" do it "returns false" do person.should_not have_posts end end end context "when the relation is a has and belongs to many" do context "when the relation has documents" do let!(:preference) do person.preferences.build end it "returns true" do person.should have_preferences end end context "when the relation does not have documents" do it "returns false" do person.should_not have_preferences end end end context "when the relation is a belongs to" do context "when the relation exists" do let!(:game) do person.build_game end it "returns true" do game.should have_person end end context "when the relation does not exist" do context "when the relation does not autobuild" do let(:game) do Game.new end it "returns false" do game.should_not have_person end end context "when the relation autobuilds" do let(:book) do Book.new end it "returns false" do book.should_not have_person end end end end context "when the relation is an embeds one" do context "when the relation exists" do let!(:name) do person.build_name end it "returns true" do person.should have_name end end context "when the relation does not exist" do context "when the relation does not autobuild" do it "returns false" do person.should_not have_name end end context "when the relation autobuilds" do let(:person) do Person.new end it "returns false" do person.should_not have_passport end end end end context "when the relation is an embeds many" do context "when the relation has documents" do let!(:address) do person.addresses.build end it "returns true" do person.should have_addresses end end context "when the relation does not have documents" do it "returns false" do person.should_not have_addresses end end end context "when the relation is an embedded in" do context "when the relation exists" do let!(:name) do person.build_name end it "returns true" do name.should have_namable end end context "when the relation does not exist" do context "when the relation does not autobuild" do let(:name) do Name.new end it "returns false" do name.should_not have_namable end end context "when the relation autobuilds" do let(:passport) do Passport.new end it "returns false" do passport.should_not have_person end end end end end describe "\#{getter}" do let(:person) do Person.new end context "when autobuilding the relation" do context "when the relation is an embeds one" do context "when the relation does not exist" do let!(:passport) do person.passport end it "builds the new document" do passport.should be_a(Passport) end it "stores in the altered attribute" do person.as_document["pass"].should eq(passport.attributes) end end context "when the relation exists" do let!(:passport) do person.build_passport(number: "123123321") end it "does not build a new document" do person.passport.should eq(passport) end end end context "when the relation is an embedded in" do let(:passport) do Passport.new end context "when the relation does not exist" do let(:person) do passport.person end it "builds the new document" do person.should be_a(Person) end end context "when the relation exists" do let!(:person) do passport.build_person(title: "sir") end it "does not build a new document" do passport.person.should eq(person) end end end context "when the relation is a has one" do context "when the relation does not exist" do let(:book) do person.book end it "builds the new document" do book.should be_a(Book) end end context "when the relation exists" do let!(:book) do person.build_book(title: "art of war") end it "does not build a new document" do person.book.should eq(book) end end end context "when the relation is a belongs to" do let(:book) do Book.new end context "when the relation does not exist" do let(:person) do book.person end it "builds the new document" do person.should be_a(Person) end end context "when the relation exists" do let!(:person) do book.build_person(title: "sir") end it "does not build a new document" do book.person.should eq(person) end end end end context "when the relation is not polymorphic" do let(:person) do Person.create end context "when the relation is a many to many" do let!(:preference) do Preference.create(name: "Setting") end before do person.preferences << Preference.last end context "when reloading the relation directly" do let(:preferences) do person.preferences(true) end it "reloads the correct documents" do preferences.should eq([ preference ]) end it "reloads a new instance" do preferences.first.should_not equal(preference) end end context "when reloading via the base document" do let(:preferences) do person.reload.preferences end it "reloads the correct documents" do preferences.should eq([ preference ]) end it "reloads a new instance" do preferences.first.should_not equal(preference) end end context "when performing a fresh find on the base" do let(:preferences) do Person.find(person.id).preferences end it "reloads the correct documents" do preferences.should eq([ preference ]) end end end context "when the relation is a many to one" do let!(:post) do Post.create(title: "First!") end before do person.posts << Post.last end context "when reloading the relation directly" do let(:posts) do person.posts(true) end it "reloads the correct documents" do posts.should eq([ post ]) end it "reloads a new instance" do posts.first.should_not equal(post) end end context "when reloading via the base document" do let(:posts) do person.reload.posts end it "reloads the correct documents" do posts.should eq([ post ]) end it "reloads a new instance" do posts.first.should_not equal(post) end end context "when performing a fresh find on the base" do let(:posts) do Person.find(person.id).posts end it "reloads the correct documents" do posts.should eq([ post ]) end end end context "when the relation is a references one" do let!(:game) do Game.create(name: "Centipeded") end before do person.game = Game.last end context "when reloading the relation directly" do let(:reloaded_game) do person.game(true) end it "reloads the correct documents" do reloaded_game.should eq(game) end it "reloads a new instance" do reloaded_game.should_not equal(game) end end context "when reloading via the base document" do let(:reloaded_game) do person.reload.game end it "reloads the correct documents" do reloaded_game.should eq(game) end it "reloads a new instance" do reloaded_game.should_not equal(game) end end context "when performing a fresh find on the base" do let(:reloaded_game) do Person.find(person.id).game end it "reloads the correct documents" do reloaded_game.should eq(game) end end end end context "when the relation is polymorphic" do context "when there's a single references many/one" do let!(:movie) do Movie.create(title: "Inception") end let!(:book) do Book.create(title: "Jurassic Park") end let!(:movie_rating) do movie.ratings.create(value: 10) end let!(:book_rating) do book.create_rating(value: 5) end context "when accessing a referenced in" do let!(:rating) do Rating.where(value: 10).first end it "returns the correct document" do rating.ratable.should eq(movie) end end context "when accessing a references many" do let(:ratings) do Movie.first.ratings end it "returns the correct documents" do ratings.should eq([ movie_rating ]) end end context "when accessing a references one" do let!(:rating) do Book.find(book.id).rating end it "returns the correct document" do rating.should eq(book_rating) end end end context "when there are multiple references many/one" do let(:face) do Face.create end let(:eye_bowl) do EyeBowl.create end let!(:face_left_eye) do face.create_left_eye(pupil_dilation: 10) end let!(:face_right_eye) do face.create_right_eye(pupil_dilation: 5) end let!(:eye_bowl_blue_eye) do eye_bowl.blue_eyes.create(pupil_dilation: 2) end let!(:eye_bowl_brown_eye) do eye_bowl.brown_eyes.create(pupil_dilation: 1) end context "when accessing a referenced in" do let(:eye) do Eye.where(pupil_dilation: 10).first end it "returns the correct type" do eye.eyeable.should be_a(Face) end it "returns the correct document" do eye.eyeable.should eq(face) end end context "when accessing a references many" do context "first references many" do let(:eyes) do EyeBowl.first.blue_eyes end it "returns the correct documents" do eyes.should eq([ eye_bowl_blue_eye ]) end end context "second references many" do let(:eyes) do EyeBowl.first.brown_eyes end it "returns the correct documents" do eyes.should eq([ eye_bowl_brown_eye ]) end end end context "when accessing a references one" do context "first references one" do let(:eye) do Face.first.left_eye end it "returns the correct document" do eye.should eq(face_left_eye) end end context "second references one" do let(:eye) do Face.first.right_eye end it "returns the correct document" do eye.should eq(face_right_eye) end end end end end end context "when setting relations to empty values" do context "when the document is a referenced in" do let(:post) do Post.new end context "when setting the relation directly" do before do post.person = "" end it "converts them to nil" do post.person.should be_nil end end context "when setting the foreign key" do before do post.person_id = "" end it "converts it to nil" do post.person_id.should be_nil end end end context "when the document is a references one" do let(:person) do Person.new end context "when setting the relation directly" do before do person.game = "" end it "converts them to nil" do person.game.should be_nil end end context "when setting the foreign key" do let(:game) do Game.new end before do game.person_id = "" end it "converts it to nil" do game.person_id.should be_nil end end end context "when the document is a references many" do let(:person) do Person.new end context "when setting the foreign key" do let(:post) do Post.new end before do post.person_id = "" end it "converts it to nil" do post.person.should be_nil end end end context "when the document is a references many to many" do let(:person) do Person.new end context "when setting the foreign key" do before do person.preference_ids = [ "", "" ] end it "does not add them" do person.preference_ids.should be_empty end end end end end
20.93254
69
0.533902
26c1395f54d0eeff089a4e9de2ab90fba80a4077
423
cask 'gisto' do version '1.10.17' sha256 '8c95961fab98b6c7f70e70971597b6ad461884beeea17ea44d03896e797cac2a' # github.com/Gisto/Gisto was verified as official when first introduced to the cask url "https://github.com/Gisto/Gisto/releases/download/v#{version}/Gisto-#{version}.dmg" appcast 'https://github.com/Gisto/Gisto/releases.atom' name 'Gisto' homepage 'https://www.gistoapp.com/' app 'Gisto.app' end
32.538462
89
0.756501
bb48bbec19a11f6ed6083b6ac7f6cdb8c3aa884a
1,606
class UndeleteFlag < Flag attr_accessible :problem validates_inclusion_of :problem, :in => %w( un_delete ), :on => :create, :message => " problem %s is not recognized" def submithelper client.flag_venue(venueId, :problem => problem, :comment => comment_text) end def resolved? return true if status == 'resolved' resolved = false begin venue = client.venue(venueId) # self.update_attribute('primaryHasHome', has_home?(venue)) if is_home?(venue) self.update_attribute('status', 'alternate resolution') self.update_attribute('resolved_details', '(home)') return true end if is_closed?(venue) self.update_attribute('status', 'alternate resolution') self.update_attribute('resolved_details', '(closed)') return true end if primary_id_changed?(venue) self.update_attribute('status', 'alternate resolution') self.update_attribute('resolved_details', '(merged)') return true end if venue.deleted == true resolved = false else resolved = true self.update_attribute('status', 'resolved') self.update_attribute('resolved_details', nil) self.update_attribute('last_checked', Time.now) end rescue Foursquare2::APIError => e if e.message =~ /has been deleted/ or e.message =~ /is invalid for venue id/ resolved = false else raise e end end self.update_attribute('last_checked', Time.now) resolved end def friendly_name "Undelete Venue" end end
26.327869
118
0.640722
2189b9d83ac64b3a8fa29fa96b5bf2f0854ecbbf
4,620
class ImagemagickAT6 < Formula desc "Tools and libraries to manipulate images in many formats" homepage "https://www.imagemagick.org/" # Please always keep the Homebrew mirror as the primary URL as the # ImageMagick site removes tarballs regularly which means we get issues # unnecessarily and older versions of the formula are broken. url "https://dl.bintray.com/homebrew/mirror/imagemagick%406-6.9.9-31.tar.xz" mirror "https://www.imagemagick.org/download/ImageMagick-6.9.9-31.tar.xz" sha256 "b487091382271106ed8172a320604761d8234b8f954b2b37ed61025d436b551e" bottle do sha256 "060b912575258a4c9352d4d31212157ae433938a9150c73f9cebc809efda4e7a" => :high_sierra sha256 "7321ba1aa323506af98de9215307699fd79a98407e6883ecc950c9c25aa5090d" => :sierra sha256 "9c4fc0bdf3d12bf7bded5641d6a1c18c2752ed791f8b30d0eed614eb07eb1054" => :el_capitan sha256 "5b926ed1f6968f54636494c8680aa4106a019950882e6d2b2778bc817c7e1c9b" => :x86_64_linux end keg_only :versioned_formula option "with-fftw", "Compile with FFTW support" option "with-hdri", "Compile with HDRI support" option "with-opencl", "Compile with OpenCL support" option "with-gcc", "Compile with OpenMP support" option "with-perl", "Compile with PerlMagick" option "without-magick-plus-plus", "disable build/install of Magick++" option "without-modules", "Disable support for dynamically loadable modules" option "without-threads", "Disable threads support" option "with-zero-configuration", "Disables depending on XML configuration files" deprecated_option "enable-hdri" => "with-hdri" deprecated_option "with-jp2" => "with-openjpeg" deprecated_option "with-openmp" => "with-gcc" depends_on "pkg-config" => :build depends_on "libtool" => :run depends_on "xz" depends_on "jpeg" => :recommended depends_on "libpng" => :recommended depends_on "libtiff" => :recommended depends_on "freetype" => :recommended depends_on "fontconfig" => :optional depends_on "gcc" => :optional depends_on "little-cms" => :optional depends_on "little-cms2" => :optional depends_on "libwmf" => :optional depends_on "librsvg" => :optional depends_on "liblqr" => :optional depends_on "openexr" => :optional depends_on "ghostscript" => :optional depends_on "webp" => :optional depends_on "openjpeg" => :optional depends_on "fftw" => :optional depends_on "pango" => :optional depends_on :perl => ["5.5", :optional] skip_clean :la def install args = %W[ --disable-osx-universal-binary --prefix=#{prefix} --disable-dependency-tracking --disable-silent-rules --enable-shared --enable-static ] if build.without? "modules" args << "--without-modules" else args << "--with-modules" end if build.with? "opencl" args << "--enable-opencl" else args << "--disable-opencl" end if build.with? "openmp" args << "--enable-openmp" else args << "--disable-openmp" end if build.with? "webp" args << "--with-webp=yes" else args << "--without-webp" end if build.with? "openjpeg" args << "--with-openjp2" else args << "--without-openjp2" end args << "--without-gslib" if build.without? "ghostscript" args << "--with-perl" << "--with-perl-options='PREFIX=#{prefix}'" if build.with? "perl" args << "--with-gs-font-dir=#{HOMEBREW_PREFIX}/share/ghostscript/fonts" if build.without? "ghostscript" args << "--without-magick-plus-plus" if build.without? "magick-plus-plus" args << "--enable-hdri=yes" if build.with? "hdri" args << "--without-fftw" if build.without? "fftw" args << "--without-pango" if build.without? "pango" args << "--without-threads" if build.without? "threads" args << "--with-rsvg" if build.with? "librsvg" args << "--without-x" if build.without? "x11" args << "--with-fontconfig=yes" if build.with? "fontconfig" args << "--with-freetype=yes" if build.with? "freetype" args << "--enable-zero-configuration" if build.with? "zero-configuration" # versioned stuff in main tree is pointless for us inreplace "configure", "${PACKAGE_NAME}-${PACKAGE_VERSION}", "${PACKAGE_NAME}" system "./configure", *args system "make", "install" end test do assert_match "PNG", shell_output("#{bin}/identify #{test_fixtures("test.png")}") # Check support for recommended features and delegates. features = shell_output("#{bin}/convert -version") %w[Modules freetype jpeg png tiff].each do |feature| assert_match feature, features end end end
35.813953
107
0.686797
d5f9fe14b7d1be5d1e9fa8d5acd22650765a37c3
908
# # Cookbook: clouderamanager # Role: clouderamanager-ha-filer.rb # # Copyright (c) 2011 Dell 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. # name "clouderamanager-ha-filer" description "Cloudera Manager High Availability Filer Role" run_list( "recipe[clouderamanager::default]", "recipe[clouderamanager::cm-ha-filer-export]" ) default_attributes() override_attributes()
32.428571
75
0.742291
6163b0392c4015177379280f293694b5b24480ad
4,413
# encoding: UTF-8 class Money class FormattingRules def initialize(currency, *raw_rules) @currency = currency # support for old format parameters @rules = normalize_formatting_rules(raw_rules) @rules = default_formatting_rules.merge(@rules) unless @rules[:ignore_defaults] @rules = localize_formatting_rules(@rules) @rules = translate_formatting_rules(@rules) if @rules[:translate] @rules[:format] ||= determine_format_from_formatting_rules(@rules) @rules[:delimiter_pattern] ||= delimiter_pattern_rule(@rules) warn_about_deprecated_rules(@rules) end def [](key) @rules[key] end def has_key?(key) @rules.has_key? key end private attr_reader :currency # Cleans up formatting rules. # # @param [Hash] rules # # @return [Hash] def normalize_formatting_rules(rules) if rules.size == 0 rules = {} elsif rules.size == 1 rules = rules.pop rules = rules.dup if rules.is_a?(Hash) if rules.is_a?(Symbol) warn '[DEPRECATION] Use Hash when passing rules to Money#format.' rules = { rules => true } end end if !rules.include?(:decimal_mark) && rules.include?(:separator) rules[:decimal_mark] = rules[:separator] end if !rules.include?(:thousands_separator) && rules.include?(:delimiter) rules[:thousands_separator] = rules[:delimiter] end rules end def default_formatting_rules Money.default_formatting_rules || {} end def translate_formatting_rules(rules) begin rules[:symbol] = I18n.t currency.iso_code, scope: "number.currency.symbol", raise: true rescue I18n::MissingTranslationData # Do nothing end rules end def localize_formatting_rules(rules) if currency.iso_code == "JPY" && I18n.locale == :ja rules[:symbol] = "円" unless rules[:symbol] == false rules[:format] = '%n%u' end rules end def determine_format_from_formatting_rules(rules) return currency.format if currency.format && !rules.has_key?(:symbol_position) symbol_position = symbol_position_from(rules) if symbol_position == :before rules.fetch(:symbol_before_without_space, true) ? '%u%n' : '%u %n' else rules[:symbol_after_without_space] ? '%n%u' : '%n %u' end end def delimiter_pattern_rule(rules) if rules[:south_asian_number_formatting] # from http://blog.revathskumar.com/2014/11/regex-comma-seperated-indian-currency-format.html /(\d+?)(?=(\d\d)+(\d)(?!\d))(\.\d+)?/ else I18n.t('number.currency.format.delimiter_pattern', default: nil) || /(\d)(?=(?:\d{3})+(?:[^\d]{1}|$))/ end end def symbol_position_from(rules) if rules.has_key?(:symbol_position) if [:before, :after].include?(rules[:symbol_position]) return rules[:symbol_position] else raise ArgumentError, ":symbol_position must be ':before' or ':after'" end elsif currency.symbol_first? :before else :after end end def warn_about_deprecated_rules(rules) if rules.has_key?(:symbol_position) position = rules[:symbol_position] template = position == :before ? '%u %n' : '%n %u' warn "[DEPRECATION] `symbol_position: :#{position}` is deprecated - you can replace it with `format: #{template}`" end if rules.has_key?(:symbol_before_without_space) warn "[DEPRECATION] `symbol_before_without_space:` option is deprecated - you can replace it with `format: '%u%n'`" end if rules.has_key?(:symbol_after_without_space) warn "[DEPRECATION] `symbol_after_without_space:` option is deprecated - you can replace it with `format: '%n%u'`" end if rules.has_key?(:html) warn "[DEPRECATION] `html` is deprecated - use `html_wrap` instead. Please note that `html_wrap` will wrap all parts of currency and if you use `with_currency` option, currency element class changes from `currency` to `money-currency`." end if rules.has_key?(:html_wrap_symbol) warn "[DEPRECATION] `html_wrap_symbol` is deprecated - use `html_wrap` instead. Please note that `html_wrap` will wrap all parts of currency." end end end end
30.86014
244
0.637435
7a2c6dab4dd4d0734832b64b979337ddf5dc7252
16,716
require 'spec_helper' describe "inquiry_answers", type: :feature, dbscope: :example do let(:site) { cms_site } let(:faq_node) { create :faq_node_page, cur_site: site } let(:node) { create :inquiry_node_form, cur_site: site, faq: faq_node } let(:index_path) { inquiry_answers_path(site, node) } let(:remote_addr) { "X.X.X.X" } let(:user_agent) { unique_id } let(:answer) { Inquiry::Answer.new(cur_site: site, cur_node: node, remote_addr: remote_addr, user_agent: user_agent) } let(:name) { unique_id } let(:email) { "#{unique_id}@example.jp" } let(:email_confirmation) { email } let(:radio_value) { radio_column.select_options.sample } let(:select_value) { select_column.select_options.sample } let(:check_value) { Hash[check_column.select_options.map.with_index { |val, i| [i.to_s, val] }.sample(2)] } let(:same_as_name) { unique_id } let(:name_column) { node.columns[0] } let(:company_column) { node.columns[1] } let(:email_column) { node.columns[2] } let(:radio_column) { node.columns[3] } let(:select_column) { node.columns[4] } let(:check_column) { node.columns[5] } let(:same_as_name_column) { node.columns[6] } before do node.columns.create! attributes_for(:inquiry_column_name).reverse_merge({cur_site: site}).merge(question: 'enabled') node.columns.create! attributes_for(:inquiry_column_optional).reverse_merge({cur_site: site}) node.columns.create! attributes_for(:inquiry_column_email).reverse_merge({cur_site: site}).merge(question: 'enabled') node.columns.create! attributes_for(:inquiry_column_radio).reverse_merge({cur_site: site}) node.columns.create! attributes_for(:inquiry_column_select).reverse_merge({cur_site: site}) node.columns.create! attributes_for(:inquiry_column_check).reverse_merge({cur_site: site}) node.columns.create! attributes_for(:inquiry_column_same_as_name).reverse_merge({cur_site: site}) node.reload end before do data = {} data[name_column.id] = [name] data[email_column.id] = [email, email] data[radio_column.id] = [radio_value] data[select_column.id] = [select_value] data[check_column.id] = [check_value] data[same_as_name_column.id] = [same_as_name] answer.set_data(data) answer.save! end context "basic crud" do before { login_cms_user } context "usual case" do it do visit index_path expect(page).to have_css(".list-item a", text: answer.data_summary) click_on answer.data_summary expect(page).to have_css(".mod-inquiry-answer-body dt", text: name_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: name) expect(page).to have_css(".mod-inquiry-answer-body dt", text: email_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: email) expect(page).to have_css(".mod-inquiry-answer-body dt", text: radio_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: radio_value) expect(page).to have_css(".mod-inquiry-answer-body dt", text: select_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: select_value) expect(page).to have_css(".mod-inquiry-answer-body dt", text: same_as_name_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: same_as_name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: remote_addr) expect(page).to have_css(".mod-inquiry-answer-body dd", text: user_agent) click_on I18n.t("ss.links.delete") click_on I18n.t("ss.buttons.delete") expect(page).to have_no_css(".list-item a", text: answer.data_summary) expect(Inquiry::Answer.count).to eq 0 end end context "when a column was destroyed after answers ware committed" do before { email_column.destroy } it do visit index_path expect(page).to have_css(".list-item a", text: answer.data_summary) click_on answer.data_summary expect(page).to have_css(".mod-inquiry-answer-body dt", text: name_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: name) expect(page).to have_css(".mod-inquiry-answer-body dt", text: radio_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: radio_value) expect(page).to have_css(".mod-inquiry-answer-body dt", text: select_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: select_value) expect(page).to have_css(".mod-inquiry-answer-body dt", text: same_as_name_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: same_as_name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: remote_addr) expect(page).to have_css(".mod-inquiry-answer-body dd", text: user_agent) click_on I18n.t("ss.links.delete") click_on I18n.t("ss.buttons.delete") expect(page).to have_no_css(".list-item a", text: answer.data_summary) expect(Inquiry::Answer.count).to eq 0 end end context "edit answer state" do it do visit index_path expect(page).to have_css(".list-item a", text: answer.data_summary) within ".list-items" do expect(page).to have_text((answer.label :state)) end click_on answer.data_summary expect(page).to have_text I18n.t("inquiry.options.answer_state.open") click_on I18n.t("ss.links.edit") within "form#item-form" do select I18n.t("inquiry.options.answer_state.closed"), from: 'item[state]' fill_in "item[comment]", with: "comment" click_on I18n.t("ss.buttons.save") end click_on I18n.t("ss.links.back_to_index") expect(page).to have_text I18n.t("inquiry.options.answer_state.closed") within ".list-items" do expect(page).not_to have_text I18n.t("inquiry.options.answer_state.closed") end # unclosed within "form.index-search" do select I18n.t("inquiry.options.search_answer_state.unclosed"), from: 's[state]' click_on I18n.t("ss.buttons.search") end within ".list-items" do expect(page).not_to have_text I18n.t("inquiry.options.answer_state.closed") end # open within "form.index-search" do select I18n.t("inquiry.options.search_answer_state.open"), from: 's[state]' click_on I18n.t("ss.buttons.search") end within ".list-items" do expect(page).not_to have_text I18n.t("inquiry.options.answer_state.closed") end # closed within "form.index-search" do select I18n.t("inquiry.options.search_answer_state.closed"), from: 's[state]' click_on I18n.t("ss.buttons.search") end within ".list-items" do expect(page).to have_text I18n.t("inquiry.options.answer_state.closed") end # all within "form.index-search" do select I18n.t("inquiry.options.search_answer_state.all"), from: 's[state]' click_on I18n.t("ss.buttons.search") end within ".list-items" do expect(page).to have_text I18n.t("inquiry.options.answer_state.closed") end end end end context "search" do before { login_cms_user } context "usual case" do it do visit index_path expect(page).to have_css(".list-item a", text: answer.data_summary) click_on I18n.t("ss.buttons.search") click_on answer.data_summary expect(page).to have_css(".mod-inquiry-answer-body dt", text: name_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: name) expect(page).to have_css(".mod-inquiry-answer-body dt", text: email_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: email) expect(page).to have_css(".mod-inquiry-answer-body dt", text: radio_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: radio_value) expect(page).to have_css(".mod-inquiry-answer-body dt", text: select_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: select_value) expect(page).to have_css(".mod-inquiry-answer-body dt", text: same_as_name_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: same_as_name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: remote_addr) expect(page).to have_css(".mod-inquiry-answer-body dd", text: user_agent) click_on I18n.t("ss.links.delete") click_on I18n.t("ss.buttons.delete") expect(page).to have_no_css(".list-item a", text: answer.data_summary) expect(Inquiry::Answer.count).to eq 0 end end context "when a column was destroyed after answers ware committed" do before { email_column.destroy } it do visit index_path expect(page).to have_css(".list-item a", text: answer.data_summary) click_on I18n.t("ss.buttons.search") click_on answer.data_summary expect(page).to have_css(".mod-inquiry-answer-body dt", text: name_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: name) expect(page).to have_css(".mod-inquiry-answer-body dt", text: radio_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: radio_value) expect(page).to have_css(".mod-inquiry-answer-body dt", text: select_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: select_value) expect(page).to have_css(".mod-inquiry-answer-body dt", text: same_as_name_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: same_as_name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: remote_addr) expect(page).to have_css(".mod-inquiry-answer-body dd", text: user_agent) click_on I18n.t("ss.links.delete") click_on I18n.t("ss.buttons.delete") expect(page).to have_no_css(".list-item a", text: answer.data_summary) expect(Inquiry::Answer.count).to eq 0 end end end context "download" do before { login_cms_user } context "usual case" do it do visit index_path expect(page).to have_css(".list-item a", text: answer.data_summary) click_on I18n.t('ss.links.download') expect(status_code).to eq 200 csv_lines = CSV.parse(page.html.encode("UTF-8")) expect(csv_lines.length).to eq 2 expect(csv_lines[0][0]).to eq 'id' expect(csv_lines[0][1]).to eq((answer.t :state)) expect(csv_lines[0][2]).to eq((answer.t :comment)) expect(csv_lines[0][3]).to eq name_column.name expect(csv_lines[0][4]).to eq company_column.name expect(csv_lines[0][5]).to eq email_column.name expect(csv_lines[0][6]).to eq radio_column.name expect(csv_lines[0][7]).to eq select_column.name expect(csv_lines[0][8]).to eq check_column.name expect(csv_lines[0][9]).to eq same_as_name_column.name expect(csv_lines[0][10]).to eq Inquiry::Answer.t('source_url') expect(csv_lines[0][11]).to eq Inquiry::Answer.t('source_name') expect(csv_lines[0][12]).to eq Inquiry::Answer.t('created') expect(csv_lines[1][0]).to eq answer.id.to_s expect(csv_lines[1][1]).to eq((answer.label :state)) expect(csv_lines[1][2]).to eq answer.comment expect(csv_lines[1][3]).to eq name expect(csv_lines[1][4]).to be_nil expect(csv_lines[1][5]).to eq email expect(csv_lines[1][6]).to eq radio_value expect(csv_lines[1][7]).to eq select_value expect(csv_lines[1][8]).to eq check_value.values.join("\n") expect(csv_lines[1][9]).to eq same_as_name expect(csv_lines[1][10]).to be_nil expect(csv_lines[1][11]).to be_nil expect(csv_lines[1][12]).to eq answer.created.strftime('%Y/%m/%d %H:%M') end end context "when a column was destroyed after answers ware committed" do before { email_column.destroy } it do visit index_path expect(page).to have_css(".list-item a", text: answer.data_summary) click_on I18n.t('ss.links.download') expect(status_code).to eq 200 csv_lines = CSV.parse(page.html.encode("UTF-8")) expect(csv_lines.length).to eq 2 expect(csv_lines[0][0]).to eq 'id' expect(csv_lines[0][1]).to eq((answer.t :state)) expect(csv_lines[0][2]).to eq((answer.t :comment)) expect(csv_lines[0][3]).to eq name_column.name expect(csv_lines[0][4]).to eq company_column.name expect(csv_lines[0][5]).to eq radio_column.name expect(csv_lines[0][6]).to eq select_column.name expect(csv_lines[0][7]).to eq check_column.name expect(csv_lines[0][8]).to eq same_as_name_column.name expect(csv_lines[0][9]).to eq Inquiry::Answer.t('source_url') expect(csv_lines[0][10]).to eq Inquiry::Answer.t('source_name') expect(csv_lines[0][11]).to eq Inquiry::Answer.t('created') expect(csv_lines[1][0]).to eq answer.id.to_s expect(csv_lines[1][1]).to eq((answer.label :state)) expect(csv_lines[1][2]).to eq answer.comment expect(csv_lines[1][3]).to eq name expect(csv_lines[1][4]).to be_nil expect(csv_lines[1][5]).to eq radio_value expect(csv_lines[1][6]).to eq select_value expect(csv_lines[1][7]).to eq check_value.values.join("\n") expect(csv_lines[1][8]).to eq same_as_name expect(csv_lines[1][9]).to be_nil expect(csv_lines[1][10]).to be_nil expect(csv_lines[1][11]).to eq answer.created.strftime('%Y/%m/%d %H:%M') end end end context "when create faq/page that use inquiry/answer" do before { login_cms_user } context "usual case" do it do visit index_path expect(page).to have_css(".list-item a", text: answer.data_summary) click_on answer.data_summary expect(page).to have_css(".mod-inquiry-answer-body dt", text: name_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: name) expect(page).to have_css(".mod-inquiry-answer-body dt", text: email_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: email) expect(page).to have_css(".mod-inquiry-answer-body dt", text: radio_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: radio_value) expect(page).to have_css(".mod-inquiry-answer-body dt", text: select_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: select_value) expect(page).to have_css(".mod-inquiry-answer-body dt", text: same_as_name_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: same_as_name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: remote_addr) expect(page).to have_css(".mod-inquiry-answer-body dd", text: user_agent) expect(page).to have_css('#menu a', text: "FAQを新規作成") click_on "FAQを新規作成" expect(page).to have_css("#item_question", text: [name, email].join(',')) end end context "when a column was destroyed after answers ware committed" do before { email_column.destroy } it do visit index_path expect(page).to have_css(".list-item a", text: answer.data_summary) click_on answer.data_summary expect(page).to have_css(".mod-inquiry-answer-body dt", text: name_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: name) expect(page).to have_css(".mod-inquiry-answer-body dt", text: radio_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: radio_value) expect(page).to have_css(".mod-inquiry-answer-body dt", text: select_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: select_value) expect(page).to have_css(".mod-inquiry-answer-body dt", text: same_as_name_column.name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: same_as_name) expect(page).to have_css(".mod-inquiry-answer-body dd", text: remote_addr) expect(page).to have_css(".mod-inquiry-answer-body dd", text: user_agent) expect(page).to have_css('#menu a', text: "FAQを新規作成") click_on "FAQを新規作成" expect(page).to have_css("#item_question", text: name) end end end end
43.644909
121
0.659787
4a80e2e5c6182f8a813b73f456c30dbbbe13e25d
654
module Api module V1 class ToursController < Api::V1::ApiController skip_before_action :check_json_request, :authenticate_user! def create user = User.find_by_id params[:user_id] if user.present? ActiveRecord::Base.transaction do tour = user.tours.create(tour_params) render json: tour.search_quote(params[:radius]) end else render json: { error: I18n.t('api.errors.not_found') }, status: :not_found end end private def tour_params params.require(:tour).permit(:name, :latitude, :longitude) end end end end
23.357143
84
0.61315
ab7d6368016aa845f52c4a3231c882b622e4b83d
146
Rails.application.config.middleware.use OmniAuth::Builder do provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"] end
48.666667
81
0.808219
1d9f7237e13e68b622774f4f06aa84eeb8c26bdc
5,851
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. require 'date' # rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength module OCI # Details to update an Autonomous Database wallet. # class Database::Models::UpdateAutonomousDatabaseWalletDetails # Indicates whether to rotate the wallet or not. If `false`, the wallet will not be rotated. The default is `false`. # @return [BOOLEAN] attr_accessor :should_rotate # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { # rubocop:disable Style/SymbolLiteral 'should_rotate': :'shouldRotate' # rubocop:enable Style/SymbolLiteral } end # Attribute type mapping. def self.swagger_types { # rubocop:disable Style/SymbolLiteral 'should_rotate': :'BOOLEAN' # rubocop:enable Style/SymbolLiteral } end # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # Initializes the object # @param [Hash] attributes Model attributes in the form of hash # @option attributes [BOOLEAN] :should_rotate The value to assign to the {#should_rotate} property def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } self.should_rotate = attributes[:'shouldRotate'] unless attributes[:'shouldRotate'].nil? self.should_rotate = false if should_rotate.nil? && !attributes.key?(:'shouldRotate') # rubocop:disable Style/StringLiterals raise 'You cannot provide both :shouldRotate and :should_rotate' if attributes.key?(:'shouldRotate') && attributes.key?(:'should_rotate') self.should_rotate = attributes[:'should_rotate'] unless attributes[:'should_rotate'].nil? self.should_rotate = false if should_rotate.nil? && !attributes.key?(:'shouldRotate') && !attributes.key?(:'should_rotate') # rubocop:disable Style/StringLiterals end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # Checks equality by comparing each attribute. # @param [Object] other the other object to be compared def ==(other) return true if equal?(other) self.class == other.class && should_rotate == other.should_rotate end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # @see the `==` method # @param [Object] other the other object to be compared def eql?(other) self == other end # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [should_rotate].hash end # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) public_method("#{key}=").call( attributes[self.class.attribute_map[key]] .map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) } ) end elsif !attributes[self.class.attribute_map[key]].nil? public_method("#{key}=").call( OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]]) ) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = public_method(attr).call next if value.nil? && !instance_variable_defined?("@#{attr}") hash[param] = _to_hash(value) end hash end private # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end # rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
37.031646
245
0.680567
79158f9e85afe9293f80d2a457edd53e3e765653
42
module RubberDuck VERSION = "0.1.0" end
10.5
19
0.690476
03ead68b82a46c7e1e884aa7fb58a48202af5f58
1,123
require_relative '../../../spec_helper' require_relative 'shared/constants' describe "Digest::MD5#hexdigest" do it "returns a hexdigest" do cur_digest = Digest::MD5.new cur_digest.hexdigest.should == MD5Constants::BlankHexdigest # add something to check that the state is reset later cur_digest << "test" cur_digest.hexdigest(MD5Constants::Contents).should == MD5Constants::Hexdigest # second invocation is intentional, to make sure there are no side-effects cur_digest.hexdigest(MD5Constants::Contents).should == MD5Constants::Hexdigest # after all is done, verify that the digest is in the original, blank state cur_digest.hexdigest.should == MD5Constants::BlankHexdigest end end describe "Digest::MD5.hexdigest" do it "returns a hexdigest" do Digest::MD5.hexdigest(MD5Constants::Contents).should == MD5Constants::Hexdigest # second invocation is intentional, to make sure there are no side-effects Digest::MD5.hexdigest(MD5Constants::Contents).should == MD5Constants::Hexdigest Digest::MD5.hexdigest("").should == MD5Constants::BlankHexdigest end end
34.030303
83
0.747106
1d2a8df01be76aa535caaf13d4849eb8563f5ee9
92
class NOVAHawk::Providers::Azure::NetworkManager::LoadBalancerPool < ::LoadBalancerPool end
30.666667
87
0.826087
08f678d907c27b922be63b0902d0c9d0c8167652
283
class CreateUsers < ActiveRecord::Migration[5.2] def change create_table :users do |t| t.text :first_name, null: false t.text :last_name, null: false t.text :email, null: false t.timestamps end add_index :users, :email, unique: true end end
20.214286
48
0.646643
7ae089704a101a614eed341064bba5fa5aad7ae0
431
require_relative '../../spec_helper' require_relative 'shared/terminate' require 'strscan' describe "StringScanner#clear" do it_behaves_like :strscan_terminate, :clear it "warns in verbose mode that the method is obsolete" do s = StringScanner.new("abc") -> { s.clear }.should complain(/clear.*obsolete.*terminate/, verbose: true) -> { s.clear }.should_not complain(verbose: false) end end
22.684211
66
0.689095
5dca182e97bd8b8e6b619debd70cdbe31a058b76
456
# frozen_string_literal: true require "action_view" module ActionView module ConsistentFallback module TemplateRendering def render_template(template, layout_name = nil, locals = nil) if template.variants == [nil] && !@lookup_context.variants.empty? @lookup_context.variants = [] end super end end end end ActionView::TemplateRenderer.prepend(ActionView::ConsistentFallback::TemplateRendering)
22.8
87
0.708333
039fa0d6df2653c51f2381550ae5228ccb7acf4f
1,179
class Bedops < Formula desc "Set and statistical operations on genomic data of arbitrary scale" homepage "https://github.com/bedops/bedops" url "https://github.com/bedops/bedops/archive/v2.4.39.tar.gz" sha256 "f8bae10c6e1ccfb873be13446c67fc3a54658515fb5071663883f788fc0e4912" license "GPL-2.0" bottle do cellar :any_skip_relocation sha256 "c2b678454a352033f226fbc3e08163ab7ede676572b7b96b993189cf35df70ff" => :big_sur sha256 "4841f0a68a87db34e0a64afd1c802d7af622773f1a7d3bf3e13a52dc7d790a3d" => :arm64_big_sur sha256 "067fa5b0cf0288e60ec7378b07b622218ff385dfc7cadd19ac6fe92ef087aff3" => :catalina sha256 "a3e404afc30d1f77ebfd5c713933a36fed137ab2086da3d7a07ff08d2cd36fb6" => :mojave sha256 "d30e93e415036d271dd424feebc451de8de2e6ed195f950ff6682623c2969dab" => :high_sierra end def install system "make" system "make", "install", "BINDIR=#{bin}" end test do (testpath/"first.bed").write <<~EOS chr1\t100\t200 EOS (testpath/"second.bed").write <<~EOS chr1\t300\t400 EOS output = shell_output("#{bin}/bedops --complement first.bed second.bed") assert_match "chr1\t200\t300", output end end
35.727273
95
0.759118
797ff0ff681c793fff046fb7058a9f2053612443
5,896
# frozen_string_literal: true # This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause # this file to always be loaded, without a need to explicitly require it in any # files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need # it. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| require 'simplecov' require 'simplecov-console' SimpleCov.start do add_filter 'spec' add_filter 'deprecated' add_group 'Ignored Code' do |src_file| open(src_file.filename).grep(/:nocov:/).any? end SimpleCov.formatters = SimpleCov::Formatter::MultiFormatter.new([ SimpleCov::Formatter::Console, SimpleCov::Formatter::HTMLFormatter, SimpleCov::Formatter::JSONFormatter # SimpleCovSmallBadge::Formatter ]) end # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # This option will default to `:apply_to_host_groups` in RSpec 4 (and will # have no way to turn it off -- the option exists only for backwards # compatibility in RSpec 3). It causes shared context metadata to be # inherited by the metadata hash of host groups and examples, rather than # triggering implicit auto-inclusion in groups with matching metadata. config.shared_context_metadata_behavior = :apply_to_host_groups # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. # # This allows you to limit a spec run to individual examples or groups # # you care about by tagging them with `:focus` metadata. When nothing # # is tagged with `:focus`, all examples get run. RSpec also provides # # aliases for `it`, `describe`, and `context` that include `:focus` # # metadata: `fit`, `fdescribe` and `fcontext`, respectively. # config.filter_run_when_matching :focus # # # Allows RSpec to persist some state between runs in order to support # # the `--only-failures` and `--next-failure` CLI options. We recommend # # you configure your source control system to ignore this file. # config.example_status_persistence_file_path = "spec/examples.txt" # # # Limits the available syntax to the non-monkey patched syntax that is # # recommended. For more details, see: # # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ # # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode # config.disable_monkey_patching! # # # This setting enables warnings. It's recommended, but in some cases may # # be too noisy due to issues in dependencies. # config.warnings = true # # # Many RSpec users commonly either run the entire suite or an individual # # file, and it's useful to allow more verbose output when running an # # individual spec file. # if config.files_to_run.one? # # Use the documentation formatter for detailed output, # # unless a formatter has already been configured # # (e.g. via a command-line flag). # config.default_formatter = "doc" # end # # # Print the 10 slowest examples and example groups at the # # end of the spec run, to help surface which specs are running # # particularly slow. # config.profile_examples = 10 # # # Run specs in random order to surface order dependencies. If you find an # # order dependency and want to debug it, you can fix the order by providing # # the seed, which is printed after each run. # # --seed 1234 # config.order = :random # # # Seed global randomization in this process using the `--seed` CLI option. # # Setting this allows you to use `--seed` to deterministically reproduce # # test failures related to randomization by passing the same `--seed` value # # as the one that triggered the failure. # Kernel.srand config.seed end
50.393162
106
0.674695
4a5719f7503149ea690100370235ea760969cdda
205
# Cookbook Name:: im # Recipe:: gather_evidence # # Copyright IBM Corp. 2016, 2018 # # <> Gather evidence recipe (gather_evidence.rb) # <> It will create log file mentioning installed application version.
25.625
70
0.741463
5da5d024ae6bda5dd11d92ff51b121d2ab72587e
222
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryBot.define do factory :lms_instance do lms_type_id { 1 } organization_id { 1 } url { "https://canvas.instructure.com" } end end
20.181818
68
0.707207
08aa685db1e2fdd35cb195510bfd3ca4a3f88b67
1,660
class Cksfv < Formula desc "File verification utility" homepage "https://zakalwe.fi/~shd/foss/cksfv/" url "https://zakalwe.fi/~shd/foss/cksfv/files/cksfv-1.3.15.tar.bz2" sha256 "a173be5b6519e19169b6bb0b8a8530f04303fe3b17706927b9bd58461256064c" license "GPL-2.0-or-later" livecheck do url "https://zakalwe.fi/~shd/foss/cksfv/files/" regex(/href=.*?cksfv[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "581d29d48ab1ac605ffae68890cbd12419387331fdeb794f0055300a00af7ca5" sha256 cellar: :any_skip_relocation, arm64_big_sur: "a024ad7db7fd8bcc1ad251d6392963533b3d2733b3d9f1fa49dcdcdd11573b57" sha256 cellar: :any_skip_relocation, monterey: "4d6559a12aabd7031e1a56b343681e73a378e3df6dd8eca6409089761c26e97a" sha256 cellar: :any_skip_relocation, big_sur: "a747f42a401eae71dd1931f2d09e8d215646f645ce3024a3702b6af36b22d242" sha256 cellar: :any_skip_relocation, catalina: "9e0b05988d3af7d666d08c8d3f4d8792f043f899a88e689d819e0b1dfd4bc2b4" sha256 cellar: :any_skip_relocation, mojave: "6110de963cf29500583d02ac6629abc215ec85ce13de8855b251e2aaa67bf6d7" sha256 cellar: :any_skip_relocation, high_sierra: "309816a8249a73a40760807ce0e5801a3ad223b21eb2a2e4b4a1d4d99859ff8a" sha256 cellar: :any_skip_relocation, x86_64_linux: "ff8e6905611d7301b37271fdb5486d8d7598c4568a1035fe36269f7f97210723" end def install system "./configure", "--prefix=#{prefix}" system "make", "install" end test do path = testpath/"foo" path.write "abcd" assert_match "#{path} ED82CD11", shell_output("#{bin}/cksfv #{path}") end end
46.111111
123
0.770482
1a63561a5bebe87dc1ac8db9527671161a16cef1
45
module Plivo VERSION = "4.26.0".freeze end
11.25
27
0.688889
28dd68fd411bc9a8c2f7f974b6eabc7b139d601e
581
class ChallengeMailer < ActionMailer::Base default from: '[email protected]' def starts_soon(challenge, user) @challenge = challenge @user = user return if !MailPreference.allowed?(@user, :challenge_starts_soon) mail to: user.email, subject: "[Hackingchinese] #{challenge.title} starts soon" end def started(challenge, user) @challenge = challenge @user = user return if !MailPreference.allowed?(@user, :challenge_started) mail to: user.email, subject: "[Hackingchinese] #{challenge.title} just started!" end end
29.05
69
0.70568
f751842c864f11140c8c3f232d687548ec19cc6e
6,521
# # May 2018 # # Copyright (c) 2017-2018 Cisco and/or its affiliates. # # Puppet resource provider for fvbd # For documentation for the Managed Object corresponding to this Puppet Type # please refer to the following URL # https://pubhub.devnetcloud.com/media/apic-mim-ref-311/docs/MO-fvBD.html # # 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 'json' begin require 'puppet_x/cisco/aci_provider_utils' rescue LoadError # seen on master, not on agent # See longstanding Puppet issues #4248, #7316, #14073, #14149, etc. require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', 'puppet_x', 'cisco', 'aci_provider_utils.rb')) end #====================Common Terms & Notes========================= # MO = ACI Managed Object # Class = Each MO represented by a Class Name (ex: fvTenant) # Prefix = Each MO has a unique Prefix (ex: 'tn' for fvTenant) # RN = Relative Name of a MO in prefix-instance form (ex: tn-tenant1) # Parent = Parent MO for the ACI Managed Object # DN = Distinguished Name that uniquely identifies a MO instance in ACI # (ex: uni/tn-tenant1/BF-mybd1) #====================Provider Utilities=========================== Puppet::Type.type(:cisco_aci_fvbd).provide(:cisco_aci) do desc 'The Cisco provider for fvbd.' mk_resource_methods attr_reader :property_hash, :property_flush # --------------------------------------------------------------- # Class Constants # --------------------------------------------------------------- # Get the MO class name associated with the Puppet Type def self.mo_class_name 'fvBD' end # Get the MO prefix associated with the Puppet Type def self.mo_dn_prefix 'BD' end # Get the URL to query the MO class associated with the Puppet Type def self.mo_class_query_url '/api/class/fvBD.json?query-target=self' end # Get a list of parent MOs (and their prefix) for this Puppet Type def self.parent_namevars { fvtenant: 'tn' } end # Get the namevars for this Puppet Type def self.my_namevars [ :name ] end # Get all the namevars for this Puppet Type (includes parents) def self.allnamevars [ :name, :fvtenant, ] end # Get all the properties for this Puppet Type def self.allproperties [ :arp_flood, :descr, :ep_clear, :ep_move_detect_mode, :intersite_bum_traffic_allow, :intersite_l2_stretch, :ip_learning, :limit_ip_learn_to_subnets, :ll_addr, :mac, :mcast_allow, :multi_dst_pkt_act, :name_alias, :optimize_wan_bandwidth, :owner_key, :owner_tag, :type, :unicast_route, :unk_mac_ucast_act, :unk_mcast_act, :vmac, ] end # Get the hash that maps Puppet Type attributes to MO attributes def self.pt_attr_2_mo_attr { arp_flood: 'arpFlood', descr: 'descr', dn: 'dn', ep_clear: 'epClear', ep_move_detect_mode: 'epMoveDetectMode', intersite_bum_traffic_allow: 'intersiteBumTrafficAllow', intersite_l2_stretch: 'intersiteL2Stretch', ip_learning: 'ipLearning', limit_ip_learn_to_subnets: 'limitIpLearnToSubnets', ll_addr: 'llAddr', mac: 'mac', mcast_allow: 'mcastAllow', multi_dst_pkt_act: 'multiDstPktAct', name: 'name', name_alias: 'nameAlias', optimize_wan_bandwidth: 'OptimizeWanBandwidth', owner_key: 'ownerKey', owner_tag: 'ownerTag', type: 'type', unicast_route: 'unicastRoute', unk_mac_ucast_act: 'unkMacUcastAct', unk_mcast_act: 'unkMcastAct', vmac: 'vmac', } end # --------------------------------------------------------------- # Puppet Provider Class Methods # --------------------------------------------------------------- def self.instances # Discover instances by querying ACI PuppetX::Cisco::ACIUtils.instances(self) end # self.instances def self.prefetch(resources) fvbd_instances = instances resources.keys.each do |name| provider = fvbd_instances.find do |inst| inst.name.to_s == resources[name][:name].to_s && inst.fvtenant.to_s == resources[name][:fvtenant].to_s && inst end resources[name].provider = provider unless provider.nil? end end # --------------------------------------------------------------- # Puppet Provider Instance Methods # --------------------------------------------------------------- def resource @resource.to_hash end def initialize(value={}) super(value) @property_flush = {} # Initialize property_flush with keys from property_hash PuppetX::Cisco::ACIUtils.puppet_hash_init(self) end def exists? (@property_hash[:ensure] == :present) end def create # Update property_flush with desired value from resource PuppetX::Cisco::ACIUtils.create(self) @property_flush[:ensure] = :present end def destroy @property_flush[:ensure] = :absent end def flush # Flush the attributes in property_flush to ACI apic_gui_url = PuppetX::Cisco::ACIUtils.flush(self) notice('APIC GUI URI for provisioned resource ' + apic_gui_url) \ unless apic_gui_url.nil? || apic_gui_url.empty? end # Generate setters that cache proposed changes in the property_flush def self.mk_resource_methods_custom_setters all_puppet_attrs = allnamevars + allproperties all_puppet_attrs.each do |attr| define_method(attr.to_s + '=') do |val| @property_flush[attr] = val end end end mk_resource_methods_custom_setters end
30.471963
83
0.593467
6148639e0e3e665de538ebd16fe7b397adddb917
2,814
# frozen_string_literal: true =begin require 'spec_helper' require 'aca_entities/operations/transform_examples/to_mitc_contract/eligibility_response' RSpec.describe ::AcaEntities::Operations::TransformExamples::ToMitcContract::EligibilityResponse do describe 'When a valid json file passed' do let(:source_file) {Pathname.pwd.join("spec/support/transform_example_payloads/eligibility_response.json")} it 'should parse and then transform when transform_mode set to batch' do AcaEntities::Operations::TransformExamples::ToMitcContract::EligibilityResponse.call(source_file, { transform_mode: :batch }) do |payload| record = AcaEntities::Operations::TransformExamples::ToMitcContract::EligibilityResponse.transform(payload) expect(record).to have_key(:determination_date) record[:applicants].each do |applicant| expect(applicant).to have_key(:person_id) applicant[:medicaid_household].tap do |medicaid_household| expect(medicaid_household[:people]).to be_a(Array) expect(medicaid_household).to have_key(:magi) end expect(applicant).to have_key(:medicaid_eligible) expect(applicant[:chip_ineligible_reason]).to be_a(Array) applicant[:determinations].each do |_key, value| value.tap do |ds| expect(ds).to have_key(:indicator) end end applicant[:cleandets].each do |cleandet| cleandet.tap do |cleandet_rec| expect(cleandet_rec).to have_key(:determination_kind) expect(cleandet_rec).to have_key(:status) end end end end end it 'should transform the payload according to instructions' do AcaEntities::Operations::TransformExamples::ToMitcContract::EligibilityResponse.call(source_file) do |record| expect(record).to have_key(:determination_date) record[:applicants].each do |applicant| expect(applicant).to have_key(:person_id) applicant[:medicaid_household].tap do |medicaid_household| expect(medicaid_household[:people]).to be_a(Array) expect(medicaid_household).to have_key(:magi) end expect(applicant).to have_key(:medicaid_eligible) expect(applicant[:chip_ineligible_reason]).to be_a(Array) applicant[:determinations].each do |_key, value| value.tap do |ds| expect(ds).to have_key(:indicator) end end applicant[:cleandets].each do |cleandet| cleandet.tap do |cleandet_rec| expect(cleandet_rec).to have_key(:determination_kind) expect(cleandet_rec).to have_key(:status) end end end end end end end =end
43.292308
144
0.67022
ab50a20793e56d7b735627f25a7b2cee47f90f95
138
require File.expand_path('../../../spec_helper', __FILE__) describe "Time#eql?" do it "needs to be reviewed for spec completeness" end
23
58
0.717391
1836117f47b7cd45c091fd2fd1311627652c29df
1,376
# 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: 20150511170204) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "divisions", force: :cascade do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end create_table "employees", force: :cascade do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" t.integer "division_id" t.integer "project_id" end create_table "projects", force: :cascade do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end end
34.4
86
0.742006
e914d474dadf37b9457561d7604e6490bc0067e2
225
class Admin::BugReportsController < Admin::ApplicationController layout "admin" def index @bug_reports = BugReport.all.order(created_at: :asc) end def show @bug_report = BugReport.find(params[:id]) end end
18.75
64
0.724444
ed8b95881faeba24358b7a952c4d0aa2124d5c3e
2,410
require 'rails_helper' RSpec.describe User, type: :model do describe User do before do @user = FactoryBot.build(:user) end describe 'ユーザー新規登録' do context '新規登録がうまくいくとき' do it 'nicknameとemail、passwordとpassword_confirmation、birthday、genderが存在すれば登録できること' do expect(@user).to be_valid end it 'passwordが6文字以上あれば登録できること' do @user.password = '123456' @user.password_confirmation = '123456' expect(@user).to be_valid end end context '新規登録がうまくいかないとき' do it 'nicknameが空では登録できないこと' do @user.nickname = nil @user.valid? expect(@user.errors.full_messages).to include('ニックネームを入力してください') end it 'emailが空では登録できないこと' do @user.email = nil @user.valid? expect(@user.errors.full_messages).to include('Eメールを入力してください') end it '重複したemailが存在する場合登録できないこと' do @user.save another_user = FactoryBot.build(:user, email: @user.email) another_user.valid? expect(another_user.errors.full_messages).to include('Eメールはすでに存在します') end it 'passwordが空では登録できないこと' do @user.password = nil @user.valid? expect(@user.errors.full_messages).to include('パスワードを入力してください') end it 'passwordが存在してもpassword_confirmationが空では登録できないこと' do @user.password_confirmation = '' @user.valid? expect(@user.errors.full_messages).to include('パスワード(確認用)とパスワードの入力が一致しません') end it 'passwordが5文字以下であれば登録できないこと' do @user.password = '12345' @user.password_confirmation = '12345' @user.valid? expect(@user.errors.full_messages).to include('パスワードは6文字以上で入力してください') end it 'genderが選択されていなければ登録できないこと' do @user.gender = nil @user.valid? expect(@user.errors.full_messages).to include('性別を入力してください') end it 'introduceが1000以上では登録できないこと' do @user.introduce = Faker::Lorem.paragraphs(number: 500) @user.valid? expect(@user.errors.full_messages).to include('自己紹介は1000文字以内で入力してください') end it 'birthdayが空では登録できないこと' do @user.birthday = nil @user.valid? expect(@user.errors.full_messages).to include('生年月日を入力してください') end end end end end
33.472222
90
0.613693