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
|
---|---|---|---|---|---|
ed25416afefa6e1395bcca3758b7ffd62332e39d | 2,277 | #!/usr/bin/env ruby
require "spaceship"
require "fileutils"
require "yaml"
def format_review(review, add_language)
result = "### " + review["title"]
result += "\n\n"
rating = review["rating"]
for i in 1..5
if i <= rating
result += "β
"
else
result += "β"
end
end
time = Time.at(review["created"] / 1000)
result += " " + review["nickname"] + ", " + time.to_date.to_s
if add_language
result += ", **" + review["storeFront"] + "**"
end
result += "\n\n"
result += "```\n"
result += review["review"]
result += "\n```"
result += "\n\n"
return result
end
def format_all(reviews, add_language = false)
sorted = reviews.sort { |x,y| y["created"] <=> x["created"] }
result = ""
for r in sorted
result += format_review(r, add_language)
end
return result
end
def format_average(ratings, language)
if language
summary = ratings.store_fronts[language]
else
summary = ratings.rating_summary
end
result = "## Average stars: " + summary.average_rating.to_s + "/5.0"
result += "\n\n"
result += "- β
β
β
β
β
- " + summary.five_star_rating_count.to_s + "\n"
result += "- β
β
β
β
β - " + summary.four_star_rating_count.to_s + "\n"
result += "- β
β
β
ββ - " + summary.three_star_rating_count.to_s + "\n"
result += "- β
β
βββ - " + summary.two_star_rating_count.to_s + "\n"
result += "- β
ββββ - " + summary.one_star_rating_count.to_s + "\n"
result += "\n---\n\n"
return result
end
puts "Log in..."
Spaceship::Tunes.login
ratings = Spaceship::Tunes::Application.find("me.dvor.Antidote").ratings
folder = "reviews"
FileUtils::mkdir_p folder
all = []
for key in ratings.store_fronts.keys
language = key.downcase
puts "Getting reviews for language " + language + "..."
file_path = folder + "/" + language + ".md"
reviews = ratings.reviews(language)
all += reviews
result = format_average(ratings, key)
result += format_all(reviews)
File.write(file_path, result)
end
puts "Saving reviews for all languages..."
all_result = format_average(ratings, nil)
all_result += format_all(all, true)
all_path = folder + "/all.md"
File.write(all_path, all_result)
| 22.544554 | 72 | 0.59552 |
3964ef749419b1a776858785109952ba4f2842f8 | 433 | # 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::Network::Mgmt::V2020_07_01
module Models
#
# Defines values for CircuitConnectionStatus
#
module CircuitConnectionStatus
Connected = "Connected"
Connecting = "Connecting"
Disconnected = "Disconnected"
end
end
end
| 24.055556 | 70 | 0.713626 |
6a4cd123340ec9028cc1b2df73001973082aea6b | 968 | ALL_SKILLS = [ 'Analytics', 'Biology', 'Biotech', 'Content', 'Data entry', 'Design', 'Funding', 'Localization', 'Manufacturing', 'Marketing', 'Medicine', 'Mechanics & Electronics', 'Operations', 'PM', 'QA', 'Social Media', 'Software', 'Volunteer vetting', 'Anything' ].freeze
ALL_AVAILABILITY = [ '1-2 hours a day', '2-4 hours a day', '4+ hours a day', 'Only on Weekends', 'Full Time' ].freeze
ALL_NUMBER_OF_VOLUNTEERS = [ '1-10', '10-50', '50-100', '100+' ]
ALL_PROJECT_TYPES = [
'Track the outbreak',
'Reduce spread',
'Scale testing',
'Medical facilities',
'Medical equipments',
'Treatment R&D',
'E-Learning',
'Job placement',
'Mental health',
'Help out communities',
'Map volunteers to needs',
'News and information',
'Social giving',
'Other'
].freeze
ALL_PROJECT_STATUS = [
'Just started',
'In progress',
'Launched',
'Actively recruiting'
].freeze
VOLUNTEERS_REQUIRED_FOR_FUNDING = 50
MAX_VOLUNTEERS_FOR_HIGHLIGHT_OFFER = 30
| 31.225806 | 275 | 0.677686 |
03828ace322f6275900e08e70cbbaebc1518e74f | 318 | module SessionsHelper
def log_in(user)
session[:user_id] = user.id
end
def current_user
if session[:user_id]
@current_user ||= User.find_by(id: session[:user_id])
end
end
def admin_status
if current_user && current_user.is_admin == 1
return true
else
return false
end
end
end
| 15.9 | 59 | 0.679245 |
38ef9fef54f85f3c69ca8d4b9070cae5410c527b | 5,292 | require 'rails_helper'
RSpec.describe AuditsController, type: :controller do
let(:default_params) do
{ organization_id: @organization.to_param }
end
let(:valid_attributes) do
{
organization_id: @organization.id,
storage_location_id: create(:storage_location, organization: @organization).id,
user_id: create(:organization_admin, organization: @organization).id
}
end
let(:invalid_attributes) do
{ organization_id: nil }
end
let(:valid_session) { {} }
describe "while signed in as an organization admin" do
before do
sign_in(@organization_admin)
end
describe "GET #index" do
it "is successful" do
Audit.create! valid_attributes
get :index, params: default_params, session: valid_session
expect(response).to be_successful
end
end
describe "GET #show" do
it "is successful" do
audit = create(:audit, organization: @organization)
get :show, params: default_params.merge(id: audit.to_param), session: valid_session
expect(response).to be_successful
end
end
describe "GET #new" do
it "is successful" do
get :new, params: default_params, session: valid_session
expect(response).to be_successful
end
end
describe "GET #edit" do
it "is successful if the status of audit is `in_progress`" do
audit = create(:audit, organization: @organization)
get :edit, params: default_params.merge(id: audit.to_param), session: valid_session
expect(response).to be_successful
end
it "redirects to #index if the status of audit is not `in_progress`" do
audit = create(:audit, organization: @organization, status: :confirmed)
get :edit, params: default_params.merge(id: audit.to_param), session: valid_session
expect(response).to redirect_to(audits_path)
audit = create(:audit, organization: @organization, status: :finalized)
get :edit, params: default_params.merge(id: audit.to_param), session: valid_session
expect(response).to redirect_to(audits_path)
end
end
describe "POST #create" do
context "with valid params" do
it "creates a new Audit" do
expect do
post :create, params: default_params.merge(audit: valid_attributes), session: valid_session
end.to change(Audit, :count).by(1)
end
it "creates a new Audit with status as `in_progress` if `save_progress` is passed as a param" do
expect do
post :create, params: default_params.merge(audit: valid_attributes, save_progress: ''), session: valid_session
expect(Audit.last.in_progress?).to be_truthy
end.to change(Audit.in_progress, :count).by(1)
end
it "creates a new Audit with status as `confirmed` if `confirm_audit` is passed as a param" do
expect do
post :create, params: default_params.merge(audit: valid_attributes, confirm_audit: ''), session: valid_session
expect(Audit.last.confirmed?).to be_truthy
end.to change(Audit.confirmed, :count).by(1)
end
it "assigns a newly created audit as @audit" do
post :create, params: default_params.merge(audit: valid_attributes), session: valid_session
expect(assigns(:audit)).to be_a(Audit)
expect(assigns(:audit)).to be_persisted
end
it "redirects to the #show after created audit" do
post :create, params: default_params.merge(audit: valid_attributes), session: valid_session
expect(response).to redirect_to(audit_path(Audit.last))
end
end
context "with invalid params" do
it "assigns a newly created but unsaved audit as @audit" do
post :create, params: default_params.merge(audit: invalid_attributes), session: valid_session
expect(assigns(:audit)).to be_a_new(Audit)
end
it "re-renders the 'new' template" do
post :create, params: default_params.merge(audit: invalid_attributes), session: valid_session
expect(response).to render_template(:new)
end
end
end
describe "DELETE #destroy" do
context "with valid params" do
it "destroys the audit if the audit's status is `in_progress`" do
audit = create(:audit, organization: @organization)
expect do
delete :destroy, params: default_params.merge(id: audit.to_param), session: valid_session
end.to change(Audit, :count).by(-1)
end
it "destroys the audit if the audit's status is `confirms`" do
audit = create(:audit, organization: @organization, status: :confirmed)
expect do
delete :destroy, params: default_params.merge(id: audit.to_param), session: valid_session
end.to change(Audit, :count).by(-1)
end
it "can not destroy the audit if the audit's status is `finalized`" do
audit = create(:audit, organization: @organization, status: :finalized)
expect do
delete :destroy, params: default_params.merge(id: audit.to_param), session: valid_session
end.to change(Audit, :count).by(0)
end
end
end
end
end
| 37.531915 | 122 | 0.656463 |
61c646172eac02a80e0f7b9fca6b0f37b23fb403 | 6,016 | #--
# Amazon Web Services EC2 Query API Ruby library
#
# Ruby Gem Name:: amazon-ec2
# Author:: Glenn Rempe (mailto:[email protected])
# Copyright:: Copyright (c) 2007-2008 Glenn Rempe
# License:: Distributes under the same terms as Ruby
# Home:: http://github.com/grempe/amazon-ec2/tree/master
#++
require File.dirname(__FILE__) + '/test_helper.rb'
context "EC2 keypairs " do
setup do
@ec2 = EC2::Base.new( :access_key_id => "not a key", :secret_access_key => "not a secret" )
@create_keypair_response_body = <<-RESPONSE
<CreateKeyPairResponse xmlns="http://ec2.amazonaws.com/doc/2007-03-01">
<keyName>example-key-name</keyName>
<keyFingerprint>1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f</keyFingerprint>
<keyMaterial>-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBAAKCAQBuLFg5ujHrtm1jnutSuoO8Xe56LlT+HM8v/xkaa39EstM3/aFxTHgElQiJLChp
HungXQ29VTc8rc1bW0lkdi23OH5eqkMHGhvEwqa0HWASUMll4o3o/IX+0f2UcPoKCOVUR+jx71Sg
5AU52EQfanIn3ZQ8lFW7Edp5a3q4DhjGlUKToHVbicL5E+g45zfB95wIyywWZfeW/UUF3LpGZyq/
ebIUlq1qTbHkLbCC2r7RTn8vpQWp47BGVYGtGSBMpTRP5hnbzzuqj3itkiLHjU39S2sJCJ0TrJx5
i8BygR4s3mHKBj8l+ePQxG1kGbF6R4yg6sECmXn17MRQVXODNHZbAgMBAAECggEAY1tsiUsIwDl5
91CXirkYGuVfLyLflXenxfI50mDFms/mumTqloHO7tr0oriHDR5K7wMcY/YY5YkcXNo7mvUVD1pM
ZNUJs7rw9gZRTrf7LylaJ58kOcyajw8TsC4e4LPbFaHwS1d6K8rXh64o6WgW4SrsB6ICmr1kGQI7
3wcfgt5ecIu4TZf0OE9IHjn+2eRlsrjBdeORi7KiUNC/pAG23I6MdDOFEQRcCSigCj+4/mciFUSA
SWS4dMbrpb9FNSIcf9dcLxVM7/6KxgJNfZc9XWzUw77Jg8x92Zd0fVhHOux5IZC+UvSKWB4dyfcI
tE8C3p9bbU9VGyY5vLCAiIb4qQKBgQDLiO24GXrIkswF32YtBBMuVgLGCwU9h9HlO9mKAc2m8Cm1
jUE5IpzRjTedc9I2qiIMUTwtgnw42auSCzbUeYMURPtDqyQ7p6AjMujp9EPemcSVOK9vXYL0Ptco
xW9MC0dtV6iPkCN7gOqiZXPRKaFbWADp16p8UAIvS/a5XXk5jwKBgQCKkpHi2EISh1uRkhxljyWC
iDCiK6JBRsMvpLbc0v5dKwP5alo1fmdR5PJaV2qvZSj5CYNpMAy1/EDNTY5OSIJU+0KFmQbyhsbm
rdLNLDL4+TcnT7c62/aH01ohYaf/VCbRhtLlBfqGoQc7+sAc8vmKkesnF7CqCEKDyF/dhrxYdQKB
gC0iZzzNAapayz1+JcVTwwEid6j9JqNXbBc+Z2YwMi+T0Fv/P/hwkX/ypeOXnIUcw0Ih/YtGBVAC
DQbsz7LcY1HqXiHKYNWNvXgwwO+oiChjxvEkSdsTTIfnK4VSCvU9BxDbQHjdiNDJbL6oar92UN7V
rBYvChJZF7LvUH4YmVpHAoGAbZ2X7XvoeEO+uZ58/BGKOIGHByHBDiXtzMhdJr15HTYjxK7OgTZm
gK+8zp4L9IbvLGDMJO8vft32XPEWuvI8twCzFH+CsWLQADZMZKSsBasOZ/h1FwhdMgCMcY+Qlzd4
JZKjTSu3i7vhvx6RzdSedXEMNTZWN4qlIx3kR5aHcukCgYA9T+Zrvm1F0seQPbLknn7EqhXIjBaT
P8TTvW/6bdPi23ExzxZn7KOdrfclYRph1LHMpAONv/x2xALIf91UB+v5ohy1oDoasL0gij1houRe
2ERKKdwz0ZL9SWq6VTdhr/5G994CK72fy5WhyERbDjUIdHaK3M849JJuf8cSrvSb4g==
-----END RSA PRIVATE KEY-----</keyMaterial>
</CreateKeyPairResponse>
RESPONSE
@describe_keypairs_response_body = <<-RESPONSE
<DescribeKeyPairsResponse xmlns="http://ec2.amazonaws.com/doc/2007-03-01">
<keySet>
<item>
<keyName>example-key-name</keyName>
<keyFingerprint>1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f</keyFingerprint>
</item>
</keySet>
</DescribeKeyPairsResponse>
RESPONSE
@delete_keypair_body = <<-RESPONSE
<DeleteKeyPair xmlns="http://ec2.amazonaws.com/doc/2007-03-01">
<return>true</return>
</DeleteKeyPair>
RESPONSE
end
specify "should be able to be created" do
@ec2.stubs(:make_request).with('CreateKeyPair', {"KeyName"=>"example-key-name"}).
returns stub(:body => @create_keypair_response_body, :is_a? => true)
@ec2.create_keypair( :key_name => "example-key-name" ).should.be.an.instance_of Hash
response = @ec2.create_keypair( :key_name => "example-key-name" )
response.keyName.should.equal "example-key-name"
response.keyFingerprint.should.equal "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f"
response.keyMaterial.should.not.equal ""
response.keyMaterial.should.not.be.nil
end
specify "method create_keypair should reject bad arguments" do
@ec2.stubs(:make_request).with('CreateKeyPair', {"KeyName"=>"example-key-name"}).
returns stub(:body => @create_keypair_response_body, :is_a? => true)
lambda { @ec2.create_keypair( :key_name => "example-key-name" ) }.should.not.raise(EC2::ArgumentError)
lambda { @ec2.create_keypair() }.should.raise(EC2::ArgumentError)
lambda { @ec2.create_keypair( :key_name => nil ) }.should.raise(EC2::ArgumentError)
lambda { @ec2.create_keypair( :key_name => "" ) }.should.raise(EC2::ArgumentError)
end
specify "should be able to be described with describe_keypairs" do
@ec2.stubs(:make_request).with('DescribeKeyPairs', {"KeyName.1"=>"example-key-name"}).
returns stub(:body => @describe_keypairs_response_body, :is_a? => true)
@ec2.describe_keypairs( :key_name => "example-key-name" ).should.be.an.instance_of Hash
response = @ec2.describe_keypairs( :key_name => "example-key-name" )
response.keySet.item[0].keyName.should.equal "example-key-name"
response.keySet.item[0].keyFingerprint.should.equal "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f"
end
specify "should be able to be deleted with delete_keypairs" do
@ec2.stubs(:make_request).with('DeleteKeyPair', {"KeyName"=>"example-key-name"}).
returns stub(:body => @delete_keypair_body, :is_a? => true)
@ec2.delete_keypair( :key_name => "example-key-name" ).should.be.an.instance_of Hash
response = @ec2.delete_keypair( :key_name => "example-key-name" )
response.return.should.equal "true"
end
specify "method delete_keypair should reject bad argument" do
@ec2.stubs(:make_request).with('DeleteKeyPair', {"KeyName"=>"example-key-name"}).
returns stub(:body => @delete_keypair_body, :is_a? => true)
lambda { @ec2.delete_keypair( :key_name => "example-key-name" ) }.should.not.raise(EC2::ArgumentError)
lambda { @ec2.delete_keypair() }.should.raise(EC2::ArgumentError)
lambda { @ec2.delete_keypair( :key_name => nil ) }.should.raise(EC2::ArgumentError)
lambda { @ec2.delete_keypair( :key_name => "" ) }.should.raise(EC2::ArgumentError)
end
end
| 48.516129 | 117 | 0.744515 |
0186d6e1b6f1f5057162023d4dd8460904605817 | 119 | class PlanFeature < ActiveRecord::Base
belongs_to :plan
belongs_to :feature
include StripeSaas::PlanFeature
end
| 17 | 38 | 0.789916 |
ac033d447735efcbcb03a3cbcfa200ae5f0e553a | 948 | cask "vscodium" do
version "1.61.1"
sha256 "43b78afcefc90f8e63a03d6f9fd03565703211cf4096d812d1729ca0ed46392a"
url "https://github.com/VSCodium/vscodium/releases/download/#{version}/VSCodium.x64.#{version}.dmg"
name "VSCodium"
desc "Binary releases of VS Code without MS branding/telemetry/licensing"
homepage "https://github.com/VSCodium/vscodium"
auto_updates true
app "VSCodium.app"
binary "#{appdir}/VSCodium.app/Contents/Resources/app/bin/codium"
zap trash: [
"~/Library/Application Support/VSCodium",
"~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.visualstudio.code.oss.sfl*",
"~/Library/Logs/VSCodium",
"~/Library/Preferences/com.visualstudio.code.oss.helper.plist",
"~/Library/Preferences/com.visualstudio.code.oss.plist",
"~/Library/Saved Application State/com.visualstudio.code.oss.savedState",
"~/.vscode-oss",
]
end
| 37.92 | 146 | 0.754219 |
3921cd2bafb1e31878d206179b07fd3e481f42f9 | 4,871 | require 'active_record/migration/sql_helpers'
class CreateDatadicVariables < ActiveRecord::Migration[5.2]
include ActiveRecord::Migration::SqlHelpers
def change
create_table 'ref_data.datadic_variables' do |t|
t.string :study
t.string :source_name
t.string :source_type
t.string :domain
t.string :form_name
t.string :variable_name
t.string :variable_type
t.string :presentation_type
t.string :label
t.string :label_note
t.string :annotation
t.boolean :is_required
t.string :valid_type
t.string :valid_min
t.string :valid_max
t.string :multi_valid_choices, array: true
t.boolean :is_identifier
t.boolean :is_derived_var
t.bigint :multi_derived_from_id, array: true
t.string :doc_url
t.string :target_type
t.string :owner_email
t.string :classification
t.string :other_classification
t.string :multi_timepoints, array: true
t.references :equivalent_to, index: { name: 'idx_dv_equiv' },
foreign_key: { to_table: 'ref_data.datadic_variables' }
t.string :storage_type
t.string :db_or_fs
t.string :schema_or_path
t.string :table_or_file
t.boolean :disabled
t.belongs_to :admin, foreign_key: true
t.belongs_to :redcap_data_dictionary, foreign_key: true
t.timestamps
end
create_table 'ref_data.datadic_variable_history' do |t|
t.belongs_to :datadic_variable, foreign_key: true,
index: { name: 'idx_h_on_datadic_variable_id' }
t.string :study
t.string :source_name
t.string :source_type
t.string :domain
t.string :form_name
t.string :variable_name
t.string :variable_type
t.string :presentation_type
t.string :label
t.string :label_note
t.string :annotation
t.boolean :is_required
t.string :valid_type
t.string :valid_min
t.string :valid_max
t.string :multi_valid_choices, array: true
t.boolean :is_identifier
t.boolean :is_derived_var
t.bigint :multi_derived_from_id, array: true
t.string :doc_url
t.string :target_type
t.string :owner_email
t.string :classification
t.string :other_classification
t.string :multi_timepoints, array: true
t.references :equivalent_to, index: { name: 'idx_dvh_equiv' },
foreign_key: { to_table: 'ref_data.datadic_variables' }
t.string :storage_type
t.string :db_or_fs
t.string :schema_or_path
t.string :table_or_file
t.boolean :disabled
t.belongs_to :admin, foreign_key: true
t.belongs_to :redcap_data_dictionary, foreign_key: true,
index: { name: 'idx_dvh_on_redcap_dd_id' }
t.timestamps
end
create_general_admin_history_trigger('ref_data',
:datadic_variables,
%i[
study
source_name
source_type
domain
form_name
variable_name
variable_type
presentation_type
label
label_note
annotation
is_required
valid_type
valid_min
valid_max
multi_valid_choices
is_identifier
is_derived_var
multi_derived_from_id
doc_url
target_type
owner_email
classification
other_classification
multi_timepoints
equivalent_to_id
storage_type
db_or_fs
schema_or_path
table_or_file
redcap_data_dictionary_id
])
end
end
| 38.054688 | 90 | 0.478957 |
b9e660d4850d73205e8d156ec7754dd5a747734b | 1,432 | require 'spec_helper'
require 'pdk/template/renderer/v1'
describe PDK::Template::Renderer::V1 do
let(:template_root) { '/some/path' }
let(:template_uri) { PDK::Util::TemplateURI.new(template_root) }
let(:pdk_context) { PDK::Context::None.new(nil) }
describe '.compatible?' do
subject(:compatible) { described_class.compatible?(template_root, pdk_context) }
context 'when all module template directories exist' do
before(:each) do
allow(PDK::Util::Filesystem).to receive(:directory?).with('/some/path/moduleroot').and_return(true)
allow(PDK::Util::Filesystem).to receive(:directory?).with('/some/path/moduleroot_init').and_return(true)
end
it 'is compatible' do
expect(compatible).to be true
end
end
context 'when only some of module template directories exist' do
before(:each) do
allow(PDK::Util::Filesystem).to receive(:directory?).with('/some/path/moduleroot').and_return(true)
allow(PDK::Util::Filesystem).to receive(:directory?).with('/some/path/moduleroot_init').and_return(false)
end
it 'is not compatible' do
expect(compatible).to be false
end
end
end
describe '.instance' do
it 'creates a PDK::Template::Renderer::V1::Renderer object' do
expect(described_class.instance(template_root, template_uri, pdk_context)).to be_a(PDK::Template::Renderer::V1::Renderer)
end
end
end
| 34.926829 | 127 | 0.689246 |
d59b3782186813b80cdf20019f14ee7a3b5954bb | 1,324 | RSpec.describe PerseidsStatus::RequestMap do
describe '.from_hash' do
let(:config) { Factory.config }
subject(:request_map) { PerseidsStatus::RequestMap.from_hash(config) }
it 'converts the config hash to a flat list' do
results = []
request_map.each do |request|
results << [request.url, request.test, request.name, request.compare]
end
expect(results).to eq(
[
['https://apple.example.com', :fruit, :apple, 'diff'],
['https://pear.example.com', :fruit, :pear, 'diff'],
['https://carrot.example.com', :vegetable, :carrot, 'wc'],
['https://onion.example.com', :vegetable, :onion, 'wc'],
],
)
end
end
describe '#each' do
subject(:request_map) { PerseidsStatus::RequestMap.new([1, 2, 3]) }
it 'yields each member of the array' do
results = []
request_map.each { |n| results << n }
expect(results).to eq([1, 2, 3])
end
end
describe '#get' do
subject(:request_map) { Factory.request_map }
it 'gets the request based on the test and name' do
request = request_map.get(:vegetable, :carrot)
expect([request.url, request.test, request.name, request.compare])
.to eq(['https://carrot.example.com', :vegetable, :carrot, 'wc'])
end
end
end
| 27.583333 | 77 | 0.603474 |
3323b64f741b2cca8828aa47b82daf006c28329b | 343 | # frozen_string_literal: true
FactoryBot.define do
factory :facebook_page, class: 'Channel::FacebookPage' do
sequence(:page_id) { |n| n }
sequence(:user_access_token) { |n| "random-token-#{n}" }
sequence(:name) { |n| "Facebook Page #{n}" }
sequence(:page_access_token) { |n| "page-access-token-#{n}" }
account
end
end
| 28.583333 | 65 | 0.655977 |
0354c71ce2e7cd0204a736f96e574559b2d0fa68 | 792 | cask "atext" do
version "2.40.5,122"
sha256 :no_check
url "https://www.trankynam.com/atext/downloads/aText.dmg"
name "aText"
desc "Tool to replace abbreviations while typing"
homepage "https://www.trankynam.com/atext/"
livecheck do
url "https://www.trankynam.com/atext/aText-Appcast.xml"
strategy :sparkle
end
auto_updates true
app "aText.app"
zap trash: [
"~/Library/Application Scripts/com.trankynam.aText",
"~/Library/Application Support/com.trankynam.aText",
"~/Library/Caches/com.trankynam.aText",
"~/Library/Containers/com.trankynam.aText",
"~/Library/Cookies/com.trankynam.aText.binarycookies",
"~/Library/Preferences/com.trankynam.aText.plist",
"~/Library/Saved Application State/com.trankynam.aText.savedState",
]
end
| 27.310345 | 71 | 0.712121 |
08360228592ae32009b7c53182b7367cf0e8cad3 | 45 | module Xray
VERSION = "0.3.2.1".freeze
end
| 11.25 | 28 | 0.666667 |
bb71d9b8f4152e3a3a0bb0bf4712ed35fb1981d0 | 1,542 | require 'method_decorators/decorators'
class User < ActiveRecord::Base
extend MethodDecorators
has_many :likes, dependent: :destroy
after_create :update_likes
validates :uid, presence: true
validates :nickname, presence: true, uniqueness: true
validates :provider, presence: true
validates :email, presence: true, on: :update
def self.create_with_omniauth(auth)
user_mapper = UserMapper.new(auth)
create!(user_mapper.attr_hash)
end
def to_param
nickname
end
def update_likes
liked_posts.each do |post|
next if Like.where(user_id:self.id).where(ig_id:post["id"]).first
likes << Like.build_with_post(post)
save
end
end
def initial_liked_media_url
unless token.blank?
"https://api.instagram.com/v1/users/self/media/liked/?access_token=#{token}"
end
end
def liked_posts
media_url = initial_liked_media_url
depth = 0
posts = []
while media_url != nil && depth < 10
json = json_for(media_url)
media_url = json ? json['pagination']['next_url'] : nil
depth += 1
posts.concat(json['data']) if json
end
posts
end
# See https://github.com/michaelfairley/method_decorators
# for more information on this neato syntax
+Retry.new(5)
def json_for(url)
begin
response = RestClient.get url
json = JSON.parse(response)
rescue RestClient::BadRequest => ex
Rails.logger.error([$!, $@].join("\n")) unless Rails.env.test?
update_attribute(:token, nil)
nil
end
end
end
| 24.09375 | 82 | 0.677043 |
08479b59a7a241cbf903936b12cedafdd1dda396 | 1,801 | class PromotionsController < ApplicationController
before_action :authenticate_user!, only: %i[index show new create update destroy
generate_coupons search]
before_action :set_promotion, only: %i[show generate_coupons
edit update destroy approve]
before_action :can_be_approved, only: [:approve]
def index
@promotions = Promotion.all
end
def show; end
def new
@promotion = Promotion.new
end
def create
@promotion = current_user.promotions.new(promotion_params)
if @promotion.save
redirect_to @promotion
else
render :new
end
end
def edit; end
def update
if @promotion.update(promotion_params)
redirect_to @promotion, notice: t('.success')
else
render :edit
end
end
def destroy
@promotion.destroy
redirect_to promotions_path
end
def generate_coupons
@promotion.generate_coupons!
redirect_to @promotion, notice: t('.success')
end
def search
@query = params[:query]
@promotions = Promotion.search(@query)
end
def approve
current_user.promotion_approvals.create!(promotion: @promotion)
PromotionMailer
.with(promotion: @promotion, approver: current_user)
.approval_email
.deliver_now
redirect_to @promotion, notice: 'PromoΓ§Γ£o aprovada com sucesso'
end
private
def set_promotion
@promotion = Promotion.find(params[:id])
end
def promotion_params
params
.require(:promotion)
.permit(:name, :description, :code, :discount_rate,
:coupon_quantity, :expiration_date)
end
def can_be_approved
return if @promotion.can_approve?(current_user)
redirect_to @promotion, alert: 'AΓ§Γ£o nΓ£o permitida'
end
end
| 22.5125 | 82 | 0.671294 |
d51c7d376ec77e5e48f3886dd4a5b10727c1a6a9 | 1,015 | class Asset < ActiveRecord::Base
ASSETTYPE = ["Automobile",
"Bond",
"BridgeLoanNotDeposited",
"CashOnHand",
"CertificateOfDepositTimeDeposit",
"CheckingAccount",
"EarnestMoneyCashDepositTowardPurchase",
"GiftsTotal",
"GiftsNotDeposited",
"LifeInsurance",
"MoneyMarketFund",
"MutualFund",
"NetWorthOfBusinessOwned",
"OtherLiquidAssets",
"OtherNonLiquidAssets",
"PendingNetSaleProceedsFromRealEstateAssets",
"RelocationMoney",
"RetirementFund",
"SaleOtherAssets",
"SavingsAccount",
"SecuredBorrowedFundsNotDeposited",
"Stock",
"TrustAccount"]
end | 39.038462 | 66 | 0.434483 |
6a098b7e1dea4f4ac877fdd3a6a631ab9878d43b | 1,060 | class BookController < ApplicationController
def list
@books = Book.all
end
def show
@book = Book.find(params[:id])
end
def new
@book = Book.new
@subjects = Subject.all
end
def create
@book = Book.new(book_params)
if @book.save
redirect_to :action => 'list'
else
@subjects = Subject.all
render :action => 'new'
end
end
def book_params
params.require(:books).permit(:title, :price, :subject_id, :description)
end
def edit
@book = Book.find(params[:id])
@subjects = Subject.all
end
def update
@book = Book.find(params[:id])
if @book.update_attributes(book_param)
redirect_to :action => 'show', :id => @book
else
@subjects = Subject.all
render :action => 'edit'
end
end
def book_param
params.require(:book).permit(:title, :price, :subject_id, :description)
end
def delete
Book.find(params[:id]).destroy
redirect_to :action => 'list'
end
def show_subjects
@subject = Subject.find(params[:id])
end
end
| 17.966102 | 76 | 0.624528 |
acbc032c1f0bfbe04f9f1d07c796e0a9067f2a25 | 872 | shared_examples 'Unidom::Geo::Concerns::AsRegion' do |model_attributes|
location_1_attribtues = {
longitude: 120.000000,
latitude: 31.000000,
postal_address: '#1 Some Street',
postal_code: '969696',
minimum_longitude: 119.000000,
minimum_latitude: 30.000000,
maximum_longitude: 121.000000,
maximum_latitude: 32.000000
}
location_2_attribtues = {
longitude: 120.000000,
latitude: 31.000000,
postal_address: '#2 Some Street',
postal_code: '979797',
minimum_longitude: 119.000000,
minimum_latitude: 30.000000,
maximum_longitude: 121.000000,
maximum_latitude: 32.000000
}
it_behaves_like 'has_many', model_attributes, :locations, Unidom::Geo::Location, [ location_1_attribtues, location_2_attribtues ]
end
| 31.142857 | 131 | 0.644495 |
ac2b2010d133ef2849c7e57410871329db41218c | 90 | #\ -p 4567
require(File.expand_path("../lti_example", __FILE__))
run Sinatra::Application
| 22.5 | 53 | 0.744444 |
e262a6910c9d4b5fc0acd3736cb11e7cb73dacd6 | 6,115 | module Nexpose
# Object that represents a connection to a Nexpose Security Console.
#
# === Examples
# # Create a new Nexpose::Connection on the default port
# nsc = Connection.new('10.1.40.10', 'nxadmin', 'password')
#
# # Create a new Nexpose::Connection from a URI or "URI" String
# nsc = Connection.from_uri('https://10.1.40.10:3780', 'nxadmin', 'password')
#
# # Create a new Nexpose::Connection with a specific port
# nsc = Connection.new('10.1.40.10', 'nxadmin', 'password', 443)
#
# # Create a new Nexpose::Connection with a silo identifier
# nsc = Connection.new('10.1.40.10', 'nxadmin', 'password', 3780, 'default')
#
# # Create a new Nexpose::Connection with a two-factor authentication (2FA) token
# nsc = Connection.new('10.1.40.10', 'nxadmin', 'password', 3780, nil, '123456')
#
# # Create a new Nexpose::Connection with an excplicitly trusted web certificate
# trusted_cert = ::File.read('cert.pem')
# nsc = Connection.new('10.1.40.10', 'nxadmin', 'password', 3780, nil, nil, trusted_cert)
#
# # Login to NSC and Establish a Session ID
# nsc.login
#
# # Check Session ID
# if nsc.session_id
# puts 'Login Successful'
# else
# puts 'Login Failure'
# end
#
# # Logout
# logout_success = nsc.logout
#
class Connection
include XMLUtils
# Session ID of this connection
attr_reader :session_id
# The hostname or IP Address of the NSC
attr_reader :host
# The port of the NSC (default is 3780)
attr_reader :port
# The username used to login to the NSC
attr_reader :username
# The password used to login to the NSC
attr_reader :password
# The URL for communication
attr_reader :url
# The token used to login to the NSC
attr_reader :token
# The last XML request sent by this object, useful for debugging.
attr_reader :request_xml
# The last XML response received by this object, useful for debugging.
attr_reader :response_xml
# The trust store to validate connections against if any
attr_reader :trust_store
# The main HTTP read_timeout value, in seconds
# For more information visit the link below:
# https://ruby-doc.org/stdlib/libdoc/net/http/rdoc/Net/HTTP.html#read_timeout-attribute-method
attr_accessor :timeout
# The optional HTTP open_timeout value, in seconds
# For more information visit the link below:
# http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/Net/HTTP.html#open_timeout-attribute-method
attr_accessor :open_timeout
# A constructor to load a Connection object from a URI
def self.from_uri(uri, user, pass, silo_id = nil, token = nil, trust_cert = nil)
uri = URI.parse(uri)
new(uri.host, user, pass, uri.port, silo_id, token, trust_cert)
end
# A constructor for Connection
#
# @param [String] ip The IP address or hostname/FQDN of the Nexpose console.
# @param [String] user The username for Nexpose sessions.
# @param [String] pass The password for Nexpose sessions.
# @param [Fixnum] port The port number of the Nexpose console.
# @param [String] silo_id The silo identifier for Nexpose sessions.
# @param [String] token The two-factor authentication (2FA) token for Nexpose sessions.
# @param [String] trust_cert The PEM-formatted web certificate of the Nexpose console. Used for SSL validation.
def initialize(ip, user, pass, port = 3780, silo_id = nil, token = nil, trust_cert = nil)
@host = ip
@username = user
@password = pass
@port = port
@silo_id = silo_id
@token = token
@trust_store = create_trust_store(trust_cert) unless trust_cert.nil?
@session_id = nil
@url = "https://#{@host}:#{@port}/api/API_VERSION/xml"
@timeout = 120
@open_timeout = 120
end
# Establish a new connection and Session ID
def login
login_hash = { 'sync-id' => 0, 'password' => @password, 'user-id' => @username, 'token' => @token }
login_hash['silo-id'] = @silo_id if @silo_id
r = execute(make_xml('LoginRequest', login_hash))
if r.success
@session_id = r.sid
true
end
rescue APIError
raise AuthenticationFailed.new(r)
end
# Logout of the current connection
def logout
r = execute(make_xml('LogoutRequest', { 'sync-id' => 0 }))
return true if r.success
raise APIError.new(r, 'Logout failed')
end
# Execute an API request
def execute(xml, version = '1.1', options = {})
options.store(:timeout, @timeout) unless options.key?(:timeout)
options.store(:open_timeout, @open_timeout)
@request_xml = xml.to_s
@api_version = version
response = APIRequest.execute(@url, @request_xml, @api_version, options, @trust_store)
@response_xml = response.raw_response_data
response
end
# Download a specific URL, typically a report.
# Include an optional file_name parameter to write the output to a file.
#
# Note: XML and HTML reports have charts not downloaded by this method.
# Would need to do something more sophisticated to grab
# all the associated image files.
def download(url, file_name = nil)
return nil if (url.nil? || url.empty?)
uri = URI.parse(url)
http = Net::HTTP.new(@host, @port)
http.use_ssl = true
if @trust_store.nil?
http.verify_mode = OpenSSL::SSL::VERIFY_NONE # XXX: security issue
else
http.cert_store = @trust_store
end
headers = { 'Cookie' => "nexposeCCSessionID=#{@session_id}" }
resp = http.get(uri.to_s, headers)
if file_name
::File.open(file_name, 'wb') { |file| file.write(resp.body) }
else
resp.body
end
end
def create_trust_store(trust_cert)
store = OpenSSL::X509::Store.new
store.trust
store.add_cert(OpenSSL::X509::Certificate.new(trust_cert))
store
end
private :create_trust_store
end
end
| 37.060606 | 115 | 0.647915 |
f715183db68909e728b41e88bb9c04621e1b931a | 390 | RSpec.configure do |config|
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.before(:each) do
DatabaseCleaner.clean
end
end
| 17.727273 | 43 | 0.715385 |
7af809345bf4224606bdc1581109223bb8abbe9b | 1,047 | require 'test_helper'
class BulkUpdateRequestPrunerTest < ActiveSupport::TestCase
context '#warn_old' do
should "update the forum topic for a bulk update request" do
forum_topic = as(create(:user)) { create(:forum_topic) }
bur = create(:bulk_update_request, status: "pending", forum_topic: forum_topic, created_at: (TagRelationship::EXPIRY_WARNING + 1).days.ago)
BulkUpdateRequestPruner.warn_old
assert_equal("pending", bur.reload.status)
assert_match(/pending automatic rejection/, ForumPost.last.body)
end
end
context '#reject_expired' do
should "reject the bulk update request" do
forum_topic = as(create(:user)) { create(:forum_topic) }
bur = create(:bulk_update_request, status: "pending", forum_topic: forum_topic, created_at: (TagRelationship::EXPIRY + 1).days.ago)
BulkUpdateRequestPruner.reject_expired
assert_equal("rejected", bur.reload.status)
assert_match(/rejected because it was not approved within 60 days/, ForumPost.second.body)
end
end
end
| 40.269231 | 145 | 0.730659 |
bf85ca1389912a8201703fa8667bbf3dfad2cad8 | 374 | # frozen_string_literal: true
module Thy
module Types
class Enum
def initialize(values)
@values = values
end
def check(value)
if @values.any? { |v| value == v }
Result::Success
else
Result::Failure.new("Expected #{value.inspect} to be one of: #{@values.inspect}")
end
end
end
end
end
| 18.7 | 91 | 0.558824 |
62683c01052b2bdb12df891bba9145d9ecce6e0e | 710 | require 'test_helper'
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
def setup
@base_title = "Ruby on Rails Tutorial Sample App"
end
test "should get home" do
get root_path
assert_response :success
assert_select "title", "#{@base_title}"
end
test "should get help" do
get help_path
assert_response :success
assert_select "title", "Help | #{@base_title}"
end
test "should get about" do
get about_path
assert_response :success
assert_select "title", "About | #{@base_title}"
end
test "should get contact" do
get contact_path
assert_response :success
assert_select "title", "Contact | #{@base_title}"
end
end
| 21.515152 | 65 | 0.688732 |
1c9cafea210a119b12641bad8f12cce4affc432b | 1,951 | class OrdersController < ApplicationController
before_action :set_order, only: [:show, :edit, :update, :destroy]
# GET /orders
# GET /orders.json
def index
@orders = Order.all
end
# GET /orders/1
# GET /orders/1.json
def show
if params[:id].present?
@order = Order.find_by_id(params[:id])
else
end
end
# Post /orders/new
def new
if params[:food_item].present?
@order = Order.new
@food_item = FoodItem.find_by_id(params[:food_item])
@order.food_item = @food_item
end
end
# GET /orders/1/edit
def edit
end
# POST /orders
# POST /orders.json
def create
@order = Order.new(order_params)
@food_item = FoodItem.find_by_id(params[:food_item])
@order.food_item = @food_item
@order.save
redirect_to order_path(:id => @order.id), notice: 'Thank you for your order page'
end
# PATCH/PUT /orders/1
# PATCH/PUT /orders/1.json
def update
respond_to do |format|
if @order.update(order_params)
format.html { redirect_to @order, notice: 'Order was successfully updated.' }
format.json { render :show, status: :ok, location: @order }
else
format.html { render :edit }
format.json { render json: @order.errors, status: :unprocessable_entity }
end
end
end
# DELETE /orders/1
# DELETE /orders/1.json
def destroy
@order.destroy
respond_to do |format|
format.html { redirect_to orders_url, notice: 'Order was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_order
@order = Order.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def order_params
params.require(:order).permit(:customer_name, :customer_address, :customer_phone, :food_item_id)
end
end
| 24.696203 | 102 | 0.655561 |
9182df4e4ecac1bb4851826856168e67e7a3fed6 | 874 | # frozen_string_literal: true
class User < ApplicationRecord
attr_accessor :login
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, authentication_keys: [:login]
def login
@login || username || email
end
def self.find_for_database_authentication(warden_condition)
conditions = warden_condition.dup
login = conditions.delete(:login)
where(conditions).where(
['lower(username) = :value OR lower(email) = :value',
{ value: login.strip.downcase }]
).first
end
def validate_username
errors.add(:username, :invalid) if User.where(email: username).exists?
end
validates :username, presence: :true, uniqueness: { case_sensitive: false }
end
| 30.137931 | 81 | 0.721968 |
61f8934d03787c72eb9ab625eb0770de17977792 | 2,879 | class Jinja2Cli < Formula
include Language::Python::Virtualenv
desc "CLI for the Jinja2 templating language"
homepage "https://github.com/mattrobenolt/jinja2-cli"
url "https://files.pythonhosted.org/packages/23/67/6f05f5f8a9fc108c58e4eac9b9b7876b400985d33149fe2faa87a9ca502b/jinja2-cli-0.7.0.tar.gz"
sha256 "9ccd8d530dad5d031230afd968cf54637b49842a13ececa6e17c2f67f6e9336e"
license "BSD-2-Clause"
revision 3
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "68e2f4bba1d27a5a75eaabdaf84684ad26867d7281d705e23bc6ed8d96f7da29"
sha256 cellar: :any_skip_relocation, big_sur: "7dd9ea3c9d12a0a9d1d3be2d521d3c7fcefb10843bf62dd7914e35e66a387d63"
sha256 cellar: :any_skip_relocation, catalina: "f87af5f900907686304e0937303eadeb5050d48e3ae85c340ec39e8918177d1e"
sha256 cellar: :any_skip_relocation, mojave: "a64bc73445720cf2a272854643c6f66aa0dfec769bd96f292b134054d5b1f84a"
sha256 cellar: :any_skip_relocation, high_sierra: "6ae50d5282b186cbf0a8b46b44a173a685a8798fec0606efc6d15bccae9b6a92"
end
depends_on "[email protected]"
resource "jinja2" do
url "https://files.pythonhosted.org/packages/93/ea/d884a06f8c7f9b7afbc8138b762e80479fb17aedbbe2b06515a12de9378d/Jinja2-2.10.1.tar.gz"
sha256 "065c4f02ebe7f7cf559e49ee5a95fb800a9e4528727aec6f24402a5374c65013"
end
resource "MarkupSafe" do
url "https://files.pythonhosted.org/packages/b9/2e/64db92e53b86efccfaea71321f597fa2e1b2bd3853d8ce658568f7a13094/MarkupSafe-1.1.1.tar.gz"
sha256 "29872e92839765e546828bb7754a68c418d927cd064fd4708fab9fe9c8bb116b"
end
def install
virtualenv_install_with_resources
end
test do
on_macos do
assert_match version.to_s, shell_output("script -q /dev/null #{bin}/jinja2 --version")
end
on_linux do
assert_match version.to_s, shell_output("script -q /dev/null -e -c \"#{bin}/jinja2 --version\"")
end
expected_result = <<~EOS
The Beatles:
- Ringo Starr
- George Harrison
- Paul McCartney
- John Lennon
EOS
template_file = testpath/"my-template.tmpl"
template_file.write <<~EOS
{{ band.name }}:
{% for member in band.members -%}
- {{ member.first_name }} {{ member.last_name }}
{% endfor -%}
EOS
template_variables_file = testpath/"my-template-variables.json"
template_variables_file.write <<~EOS
{
"band": {
"name": "The Beatles",
"members": [
{"first_name": "Ringo", "last_name": "Starr"},
{"first_name": "George", "last_name": "Harrison"},
{"first_name": "Paul", "last_name": "McCartney"},
{"first_name": "John", "last_name": "Lennon"}
]
}
}
EOS
output = shell_output("#{bin}/jinja2 #{template_file} #{template_variables_file}")
assert_equal output, expected_result
end
end
| 38.905405 | 140 | 0.715874 |
7958336e3512b9d506dad95f52f6ad2cf738e814 | 2,395 | require 'moromi/error/loggerable'
module Moromi
module Error
class DefaultLogger
include ::Moromi::Error::Loggerable
UNKNOWN = 'unknown'.freeze
def write(controller, status, title, exception, options, locals)
Moromi::Error.config.severity_mappings.each do |klass, severity|
if exception.is_a? klass
message = ([exception.message] + ::Rails.backtrace_cleaner.clean(Array(exception.backtrace).compact)).join('\n')
Rails.logger.add severity, message
return
end
end
Rails.logger.add log_severity(exception), to_ltsv(controller, exception) unless skip?(exception)
notify_exception(controller, exception)
rescue => e
backtrace = ::Rails.backtrace_cleaner.clean(e.backtrace).join("\n").gsub("\n", '\n')
Rails.logger.error "[#{self.class}#write] #{e.inspect} #{backtrace}"
end
private
def to_ltsv(controller, exception)
backtrace = (exception&.backtrace || []).compact
information_builder = Moromi::Error.config.information_builder_klass.new(controller)
messages = {
error_class: exception.class,
message: exception.message,
errors: fetch_errors(exception).compact.join("\n").gsub("\n", '\n'),
backtrace: ::Rails.backtrace_cleaner.clean(backtrace).join("\n").gsub("\n", '\n')
}
messages.merge!(information_builder.build)
messages.map { |k, v| "#{k}:#{v}" }.join("\t")
rescue
(exception&.backtrace || []).compact.join("\n").gsub("\n", '\n')
end
def notify_exception(controller, exception)
return unless defined? ExceptionNotifier
return unless Moromi::Error.config.use_exception_notifier
ExceptionNotifier.notify_exception(exception, env: controller.request.env, data: {method: controller.request.method, url: controller.request.url})
end
def skip?(exception)
return false unless exception.respond_to?(:skip_logging?)
exception.skip_logging?
end
def log_severity(exception)
return Logger::Severity::ERROR unless exception.respond_to?(:log_severity)
exception.log_severity
end
def fetch_errors(exception)
return [exception.inspect] unless exception.respond_to?(:errors)
exception.errors
end
end
end
end
| 33.263889 | 154 | 0.647182 |
e96446ddec5a8d555e5e2dce1db6772dd2225c5c | 4,616 | module Fog
module Compute
class ProfitBricks
class Real
# Update a group.
# Normally a PUT request would require that you pass all the attributes and values.
# In this implementation, you must supply the name, even if it isn't being changed.
# As a convenience, the other four attributes will default to false.
# You should explicitly set them to true if you want to have them enabled.
#
# ==== Parameters
# * group_id<~String> - Required, The ID of the specific group to update.
# * options<~Hash>:
# * name<~String> - Required, The name of the group.
# * createDataCenter<~Integer> - The group will be allowed to create virtual data centers.
# * createSnapshot<~Integer> - The group will be allowed to create snapshots.
# * reserveIp<~Integer> - The group will be allowed to reserve IP addresses.
# * accessActivityLog<~Integer> - The group will be allowed to access the activity log.
#
# ==== Returns
# * response<~Excon::Response>:
# * body<~Hash>:
# * id<~String> - The resource's unique identifier
# * type<~String> - The type of the requested resource
# * href<~String> - URL to the objectβs representation (absolute path)
# * properties<~Hash> - Hash containing the volume properties.
# * name<~String> - The name of the group.
# * createDataCenter<~Boolean> - The group will be allowed to create virtual data centers.
# * createSnapshot<~Boolean> - The group will be allowed to create snapshots.
# * reserveIp<~Boolean> - The group will be allowed to reserve IP addresses.
# * accessActivityLog<~Boolean> - The group will be allowed to access the activity log.
# * entities<~Hash> - A hash containing the group entities.
# * users<~Hash> - A collection of users that belong to this group.
# * id<~String> - The resource's unique identifier.
# * type<~String> - The type of the requested resource.
# * href<~String> - URL to the objectβs representation (absolute path).
# * items<~Array> - The array containing individual user resources.
# * resources<~Hash> - A collection of resources that are assigned to this group.
# * id<~String> - The resource's unique identifier.
# * type<~String> - The type of the requested resource.
# * href<~String> - URL to the objectβs representation (absolute path).
# * items<~Array> - An array containing individual resources.
# * id<~String> - The resource's unique identifier.
# * type<~String> - The type of the requested resource.
# * href<~String> - URL to the objectβs representation (absolute path).
#
# {ProfitBricks API Documentation}[https://devops.profitbricks.com/api/cloud/v4/#update-a-group]
def update_group(group_id, options = {})
group = {
:properties => options
}
request(
:expects => [202],
:method => 'PUT',
:path => "/um/groups/#{group_id}",
:body => Fog::JSON.encode(group)
)
end
end
class Mock
def update_group(group_id, options = {})
if group = data[:groups]['items'].find do |grp|
grp["id"] == group_id
end
group['name'] = options[:name]
group['createDataCenter'] = options[:create_data_center] if options[:create_data_center]
group['createSnapshot'] = options[:create_snapshot] if options[:create_snapshot]
group['reserveIp'] = options[:reserve_ip] if options[:reserve_ip]
group['accessActivityLog'] = options[:access_activity_log] if options[:access_activity_log]
else
raise Excon::Error::HTTPStatus, 'The requested resource could not be found'
end
response = Excon::Response.new
response.status = 202
response.body = group
response
end
end
end
end
end
| 53.674419 | 106 | 0.541811 |
f7343a8704f76d861997d657363c4c6a2843aa54 | 248 | require File.dirname(__FILE__) + '/../../spec_helper'
describe "ByteArray#[]" do
it "returns the byte at index" do
s= "A92f"
b = s.data
a = []
0.upto(s.size-1) { |i| a << b[i].chr }
a.should == ["A", "9", "2", "f"]
end
end
| 20.666667 | 53 | 0.516129 |
182867be71067b0bc7ae72282306fa65624ad800 | 4,074 | # frozen_string_literal: true
require_relative '../../spec_helper'
require_relative '../../../lib/rley/lexical/token'
# Load the class under test
require_relative '../../../lib/rley/parser/error_reason'
module Rley # Open this namespace to avoid module qualifier prefixes
module Parser # Open this namespace to avoid module qualifier prefixes
describe NoInput do
context 'Initialization:' do
# Default instantiation rule
subject { NoInput.new }
it 'should be created without argument' do
expect { NoInput.new }.not_to raise_error
end
it 'should know the error token rank' do
expect(subject.rank).to eq(0)
end
end # context
context 'Provided services:' do
it 'should emit a standard message' do
text = 'Input cannot be empty.'
expect(subject.to_s).to eq(text)
expect(subject.message).to eq(text)
end
it 'should give a clear inspection text' do
text = 'Rley::Parser::NoInput: Input cannot be empty.'
expect(subject.inspect).to eq(text)
end
end # context
end # describe
describe ExpectationNotMet do
let(:err_token) { double('fake-token') }
let(:terminals) do
%w[PLUS LPAREN].map { |name| Syntax::Terminal.new(name) }
end
# Default instantiation rule
subject { ExpectationNotMet.new(3, err_token, terminals) }
context 'Initialization:' do
it 'should be created with arguments' do
expect do
ExpectationNotMet.new(3, err_token, terminals)
end.not_to raise_error
end
it 'should know the error position' do
expect(subject.rank).to eq(3)
end
it 'should know the expected terminals' do
expect(subject.expected_terminals).to eq(terminals)
end
end # context
end # describe
describe UnexpectedToken do
let(:err_lexeme) { '-' }
let(:err_terminal) { Syntax::Terminal.new('MINUS') }
let(:pos) { Lexical::Position.new(3, 4) }
let(:err_token) { Lexical::Token.new(err_lexeme, err_terminal, pos) }
let(:terminals) do
%w[PLUS LPAREN].map { |name| Syntax::Terminal.new(name) }
end
# Default instantiation rule
subject { UnexpectedToken.new(3, err_token, terminals) }
context 'Initialization:' do
it 'should be created with arguments' do
expect do
UnexpectedToken.new(3, err_token, terminals)
end.not_to raise_error
end
end # context
context 'Provided services:' do
it 'should emit a message' do
text = <<MESSAGE_END
Syntax error at or near token line 3, column 4 >>>-<<<
Expected one of: ['PLUS', 'LPAREN'], found a 'MINUS' instead.
MESSAGE_END
expect(subject.to_s).to eq(text.chomp)
expect(subject.message).to eq(text.chomp)
end
end # context
end # describe
describe PrematureInputEnd do
let(:err_lexeme) { '+' }
let(:err_terminal) { Syntax::Terminal.new('PLUS') }
let(:pos) { Lexical::Position.new(3, 4) }
let(:err_token) { Lexical::Token.new(err_lexeme, err_terminal, pos) }
let(:terminals) do
%w[INT LPAREN].map { |name| Syntax::Terminal.new(name) }
end
# Default instantiation rule
subject { PrematureInputEnd.new(3, err_token, terminals) }
context 'Initialization:' do
it 'should be created with arguments' do
expect do
PrematureInputEnd.new(3, err_token, terminals)
end.not_to raise_error
end
end # context
context 'Provided services:' do
it 'should emit a message' do
text = <<MESSAGE_END
Premature end of input after '+' at position line 3, column 4
Expected one of: ['INT', 'LPAREN'].
MESSAGE_END
expect(subject.to_s).to eq(text.chomp)
expect(subject.message).to eq(text.chomp)
end
end # context
end # describe
end # module
end # module
# End of file
| 31.338462 | 75 | 0.618066 |
e9f02d78ddc3e82f02d0d8cc1f6cba0f7ce86579 | 12,892 | require 'test_helper'
class RemotePayuLatamTest < Test::Unit::TestCase
def setup
@gateway = PayuLatamGateway.new(fixtures(:payu_latam).update(payment_country: 'AR'))
@amount = 4000
@credit_card = credit_card('4097440000000004', verification_value: '444', first_name: 'APPROVED', last_name: '')
@declined_card = credit_card('4097440000000004', verification_value: '444', first_name: 'REJECTED', last_name: '')
@pending_card = credit_card('4097440000000004', verification_value: '444', first_name: 'PENDING', last_name: '')
@naranja_credit_card = credit_card('5895620000000002', :verification_value => '123', :first_name => 'APPROVED', :last_name => '', :brand => 'naranja')
@options = {
dni_number: '5415668464654',
merchant_buyer_id: '1',
currency: 'ARS',
order_id: generate_unique_id,
description: 'Active Merchant Transaction',
installments_number: 1,
tax: 0,
email: '[email protected]',
ip: '127.0.0.1',
device_session_id: 'vghs6tvkcle931686k1900o6e1',
cookie: 'pt1t38347bs6jc9ruv2ecpv7o2',
user_agent: 'Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0',
billing_address: address(
address1: 'Viamonte',
address2: '1366',
city: 'Plata',
state: 'Buenos Aires',
country: 'AR',
zip: '64000',
phone: '7563126'
)
}
end
# At the time of writing this test, gateway sandbox
# supports auth and purchase transactions only
def test_invalid_login
gateway = PayuLatamGateway.new(merchant_id: '', account_id: '', api_login: 'U', api_key: 'U', payment_country: 'AR')
response = gateway.purchase(@amount, @credit_card, @options)
assert_failure response
end
def test_successful_purchase
response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal 'APPROVED', response.message
assert response.test?
end
def test_successful_purchase_with_naranja_card
response = @gateway.purchase(@amount, @naranja_credit_card, @options)
assert_success response
assert_equal 'APPROVED', response.message
assert response.test?
end
def test_successful_purchase_with_specified_language
response = @gateway.purchase(@amount, @credit_card, @options.merge(language: 'es'))
assert_success response
assert_equal 'APPROVED', response.message
assert response.test?
end
def test_successful_purchase_with_buyer
gateway = PayuLatamGateway.new(fixtures(:payu_latam).update(:account_id => '512327', payment_country: 'BR'))
options_buyer = {
currency: 'BRL',
billing_address: address(
address1: 'Calle 100',
address2: 'BL4',
city: 'Sao Paulo',
state: 'SP',
country: 'BR',
zip: '09210710',
phone: '(11)756312633'
),
shipping_address: address(
address1: 'Calle 200',
address2: 'N107',
city: 'Sao Paulo',
state: 'SP',
country: 'BR',
zip: '01019-030',
phone: '(11)756312633'
),
buyer: {
name: 'Jorge Borges',
dni_number: '5415668464123',
dni_type: 'TI',
merchant_buyer_id: '2',
cnpj: '32593371000110',
email: '[email protected]'
}
}
response = gateway.purchase(@amount, @credit_card, @options.update(options_buyer))
assert_success response
assert_equal 'APPROVED', response.message
assert response.test?
end
def test_successful_purchase_brazil
gateway = PayuLatamGateway.new(fixtures(:payu_latam).update(:account_id => '512327', payment_country: 'BR'))
options_brazil = {
payment_country: 'BR',
currency: 'BRL',
billing_address: address(
address1: 'Calle 100',
address2: 'BL4',
city: 'Sao Paulo',
state: 'SP',
country: 'BR',
zip: '09210710',
phone: '(11)756312633'
),
shipping_address: address(
address1: 'Calle 200',
address2: 'N107',
city: 'Sao Paulo',
state: 'SP',
country: 'BR',
zip: '01019-030',
phone: '(11)756312633'
),
buyer: {
cnpj: '32593371000110'
}
}
response = gateway.purchase(@amount, @credit_card, @options.update(options_brazil))
assert_success response
assert_equal 'APPROVED', response.message
assert response.test?
end
def test_successful_purchase_colombia
gateway = PayuLatamGateway.new(fixtures(:payu_latam).update(:account_id => '512321', payment_country: 'CO'))
options_colombia = {
payment_country: 'CO',
currency: 'COP',
billing_address: address(
address1: 'Calle 100',
address2: 'BL4',
city: 'Bogota',
state: 'Bogota DC',
country: 'CO',
zip: '09210710',
phone: '(11)756312633'
),
shipping_address: address(
address1: 'Calle 200',
address2: 'N107',
city: 'Bogota',
state: 'Bogota DC',
country: 'CO',
zip: '01019-030',
phone: '(11)756312633'
),
tax: '3193',
tax_return_base: '16806'
}
response = gateway.purchase(2000000, @credit_card, @options.update(options_colombia))
assert_success response
assert_equal 'APPROVED', response.message
assert response.test?
end
def test_successful_purchase_mexico
gateway = PayuLatamGateway.new(fixtures(:payu_latam).update(:account_id => '512324', payment_country: 'MX'))
options_mexico = {
payment_country: 'MX',
currency: 'MXN',
billing_address: address(
address1: 'Calle 100',
address2: 'BL4',
city: 'Guadalajara',
state: 'Jalisco',
country: 'MX',
zip: '09210710',
phone: '(11)756312633'
),
shipping_address: address(
address1: 'Calle 200',
address2: 'N107',
city: 'Guadalajara',
state: 'Jalisco',
country: 'MX',
zip: '01019-030',
phone: '(11)756312633'
),
birth_date: '1985-05-25'
}
response = gateway.purchase(@amount, @credit_card, @options.update(options_mexico))
assert_success response
assert_equal 'APPROVED', response.message
assert response.test?
end
def test_successful_purchase_no_description
options = @options
options.delete(:description)
response = @gateway.purchase(@amount, @credit_card, options)
assert_success response
assert_equal 'APPROVED', response.message
assert response.test?
end
def test_failed_purchase
response = @gateway.purchase(@amount, @declined_card, @options)
assert_failure response
assert_equal 'DECLINED', response.params['transactionResponse']['state']
end
def test_failed_purchase_with_no_options
response = @gateway.purchase(@amount, @declined_card, {})
assert_failure response
assert_equal 'DECLINED', response.params['transactionResponse']['state']
end
def test_failed_purchase_with_specified_language
gateway = PayuLatamGateway.new(merchant_id: '', account_id: '', api_login: 'U', api_key: 'U', payment_country: 'AR')
response = gateway.purchase(@amount, @declined_card, @options.merge(language: 'es'))
assert_failure response
assert_equal 'Credenciales invΓ‘lidas', response.message
end
def test_successful_authorize
response = @gateway.authorize(@amount, @credit_card, @options)
assert_success response
assert_equal 'APPROVED', response.message
assert_match %r(^\d+\|(\w|-)+$), response.authorization
end
def test_successful_authorize_with_naranja_card
response = @gateway.authorize(@amount, @naranja_credit_card, @options)
assert_success response
assert_equal 'APPROVED', response.message
assert_match %r(^\d+\|(\w|-)+$), response.authorization
end
def test_successful_authorize_with_specified_language
response = @gateway.authorize(@amount, @credit_card, @options.merge(language: 'es'))
assert_success response
assert_equal 'APPROVED', response.message
assert_match %r(^\d+\|(\w|-)+$), response.authorization
end
def test_failed_authorize
response = @gateway.authorize(@amount, @pending_card, @options)
assert_failure response
assert_equal 'DECLINED', response.params['transactionResponse']['state']
end
def test_failed_authorize_with_specified_language
gateway = PayuLatamGateway.new(merchant_id: '', account_id: '', api_login: 'U', api_key: 'U', payment_country: 'AR')
response = gateway.authorize(@amount, @pending_card, @options.merge(language: 'es'))
assert_failure response
assert_equal 'Credenciales invΓ‘lidas', response.message
end
# As noted above, capture transactions are currently not supported, but in the hope
# they will one day be, here you go
# def test_successful_capture
# response = @gateway.authorize(@amount, @credit_card, @options)
# assert_success response
# assert_equal 'APPROVED', response.message
# assert_match %r(^\d+\|(\w|-)+$), response.authorization
# capture = @gateway.capture(@amount, response.authorization, @options)
# assert_success capture
# assert_equal 'APPROVED', response.message
# assert response.test?
# end
# def test_successful_partial_capture
# response = @gateway.authorize(@amount, @credit_card, @options)
# assert_success response
# assert_equal 'APPROVED', response.message
# assert_match %r(^\d+\|(\w|-)+$), response.authorization
# capture = @gateway.capture(@amount - 1, response.authorization, @options)
# assert_success capture
# assert_equal 'APPROVED', response.message
# assert_equal '39.99', response.params['TX_VALUE']['value']
# assert response.test?
# end
def test_well_formed_refund_fails_as_expected
purchase = @gateway.purchase(@amount, @credit_card, @options)
assert_success purchase
assert refund = @gateway.refund(@amount, purchase.authorization, @options)
assert_equal 'The payment plan id cannot be empty', refund.message
end
def test_failed_refund
response = @gateway.refund(@amount, '')
assert_failure response
assert_match(/property: parentTransactionId, message: must not be null/, response.message)
end
def test_failed_refund_with_specified_language
response = @gateway.refund(@amount, '', language: 'es')
assert_failure response
assert_match(/property: parentTransactionId, message: No puede ser vacio/, response.message)
end
def test_failed_void
response = @gateway.void('')
assert_failure response
assert_match(/property: parentTransactionId, message: must not be null/, response.message)
end
def test_failed_void_with_specified_language
response = @gateway.void('', language: 'es')
assert_failure response
assert_match(/property: parentTransactionId, message: No puede ser vacio/, response.message)
end
def test_failed_capture
response = @gateway.capture(@amount, '')
assert_failure response
assert_match(/must not be null/, response.message)
end
def test_verify_credentials
assert @gateway.verify_credentials
gateway = PayuLatamGateway.new(merchant_id: 'X', account_id: '512322', api_login: 'X', api_key: 'X', payment_country: 'AR')
assert !gateway.verify_credentials
end
def test_successful_verify
verify = @gateway.verify(@credit_card, @options)
assert_success verify
assert_equal 'APPROVED', verify.message
end
def test_successful_verify_with_specified_amount
verify = @gateway.verify(@credit_card, @options.merge(verify_amount: 5100))
assert_success verify
assert_equal 'APPROVED', verify.message
end
def test_successful_verify_with_specified_language
verify = @gateway.verify(@credit_card, @options.merge(language: 'es'))
assert_success verify
assert_equal 'APPROVED', verify.message
end
def test_failed_verify_with_specified_amount
verify = @gateway.verify(@credit_card, @options.merge(verify_amount: 499))
assert_failure verify
assert_equal 'The order value is less than minimum allowed. Minimum value allowed 5 ARS', verify.message
end
def test_failed_verify_with_specified_language
verify = @gateway.verify(@credit_card, @options.merge(verify_amount: 499, language: 'es'))
assert_failure verify
assert_equal 'The order value is less than minimum allowed. Minimum value allowed 5 ARS', verify.message
end
def test_transcript_scrubbing
transcript = capture_transcript(@gateway) do
@gateway.purchase(@amount, @credit_card, @options)
end
clean_transcript = @gateway.scrub(transcript)
assert_scrubbed(@credit_card.number, clean_transcript)
assert_scrubbed(@credit_card.verification_value.to_s, clean_transcript)
assert_scrubbed(@gateway.options[:api_key], clean_transcript)
end
end
| 33.05641 | 154 | 0.684843 |
e2073c92a3d9bf4c6afd0f76e9b5cf606acedc31 | 13,719 | # frozen_string_literal: true
require 'active_support'
require 'active_support/core_ext/string/inflections'
require 'grape-swagger/endpoint/params_parser'
module Grape
class Endpoint
def content_types_for(target_class)
content_types = (target_class.content_types || {}).values
if content_types.empty?
formats = [target_class.format, target_class.default_format].compact.uniq
formats = Grape::Formatter.formatters({}).keys if formats.empty?
content_types = Grape::ContentTypes::CONTENT_TYPES.select do |content_type, _mime_type|
formats.include? content_type
end.values
end
content_types.uniq
end
# swagger spec2.0 related parts
#
# required keys for SwaggerObject
def swagger_object(target_class, request, options)
object = {
info: info_object(options[:info].merge(version: options[:doc_version])),
swagger: '2.0',
produces: content_types_for(target_class),
authorizations: options[:authorizations],
securityDefinitions: options[:security_definitions],
security: options[:security],
host: GrapeSwagger::DocMethods::OptionalObject.build(:host, options, request),
basePath: GrapeSwagger::DocMethods::OptionalObject.build(:base_path, options, request),
schemes: options[:schemes].is_a?(String) ? [options[:schemes]] : options[:schemes]
}
GrapeSwagger::DocMethods::Extensions.add_extensions_to_root(options, object)
object.delete_if { |_, value| value.blank? }
end
# building info object
def info_object(infos)
result = {
title: infos[:title] || 'API title',
description: infos[:description],
termsOfService: infos[:terms_of_service_url],
contact: contact_object(infos),
license: license_object(infos),
version: infos[:version]
}
GrapeSwagger::DocMethods::Extensions.add_extensions_to_info(infos, result)
result.delete_if { |_, value| value.blank? }
end
# sub-objects of info object
# license
def license_object(infos)
{
name: infos.delete(:license),
url: infos.delete(:license_url)
}.delete_if { |_, value| value.blank? }
end
# contact
def contact_object(infos)
{
name: infos.delete(:contact_name),
email: infos.delete(:contact_email),
url: infos.delete(:contact_url)
}.delete_if { |_, value| value.blank? }
end
# building path and definitions objects
def path_and_definition_objects(namespace_routes, options)
@paths = {}
@definitions = {}
namespace_routes.each_value do |routes|
path_item(routes, options)
end
add_definitions_from options[:models]
[@paths, @definitions]
end
def add_definitions_from(models)
return if models.nil?
models.each { |x| expose_params_from_model(x) }
end
# path object
def path_item(routes, options)
routes.each do |route|
next if hidden?(route, options)
@item, path = GrapeSwagger::DocMethods::PathString.build(route, options)
@entity = route.entity || route.options[:success]
verb, method_object = method_object(route, options, path)
if @paths.key?(path.to_s)
@paths[path.to_s][verb] = method_object
else
@paths[path.to_s] = { verb => method_object }
end
GrapeSwagger::DocMethods::Extensions.add(@paths[path.to_s], @definitions, route)
end
end
def method_object(route, options, path)
method = {}
method[:summary] = summary_object(route)
method[:description] = description_object(route)
method[:produces] = produces_object(route, options[:produces] || options[:format])
method[:consumes] = consumes_object(route, options[:format])
method[:parameters] = params_object(route, options, path)
method[:security] = security_object(route)
method[:responses] = response_object(route, options)
method[:tags] = route.options.fetch(:tags, tag_object(route, path))
method[:operationId] = GrapeSwagger::DocMethods::OperationId.build(route, path)
method[:deprecated] = deprecated_object(route)
method.delete_if { |_, value| value.nil? }
[route.request_method.downcase.to_sym, method]
end
def deprecated_object(route)
route.options[:deprecated] if route.options.key?(:deprecated)
end
def security_object(route)
route.options[:security] if route.options.key?(:security)
end
def summary_object(route)
summary = route.options[:desc] if route.options.key?(:desc)
summary = route.description if route.description.present? && route.options.key?(:detail)
summary = route.options[:summary] if route.options.key?(:summary)
summary
end
def description_object(route)
description = route.description if route.description.present?
description = route.options[:detail] if route.options.key?(:detail)
description
end
def produces_object(route, format)
return ['application/octet-stream'] if file_response?(route.attributes.success) &&
!route.attributes.produces.present?
mime_types = GrapeSwagger::DocMethods::ProducesConsumes.call(format)
route_mime_types = %i[formats content_types produces].map do |producer|
possible = route.options[producer]
GrapeSwagger::DocMethods::ProducesConsumes.call(possible) if possible.present?
end.flatten.compact.uniq
route_mime_types.present? ? route_mime_types : mime_types
end
SUPPORTS_CONSUMES = %i[post put patch].freeze
def consumes_object(route, format)
return unless SUPPORTS_CONSUMES.include?(route.request_method.downcase.to_sym)
GrapeSwagger::DocMethods::ProducesConsumes.call(route.settings.dig(:description, :consumes) || format)
end
def params_object(route, options, path)
parameters = partition_params(route, options).map do |param, value|
value = { required: false }.merge(value) if value.is_a?(Hash)
_, value = default_type([[param, value]]).first if value == ''
if value.dig(:documentation, :type)
expose_params(value[:documentation][:type])
elsif value[:type]
expose_params(value[:type])
end
GrapeSwagger::DocMethods::ParseParams.call(param, value, path, route, @definitions)
end
if GrapeSwagger::DocMethods::MoveParams.can_be_moved?(parameters, route.request_method)
parameters = GrapeSwagger::DocMethods::MoveParams.to_definition(path, parameters, route, @definitions)
end
GrapeSwagger::DocMethods::FormatData.to_format(parameters)
parameters.presence
end
def response_object(route, options)
codes = http_codes_from_route(route)
codes.map! { |x| x.is_a?(Array) ? { code: x[0], message: x[1], model: x[2], examples: x[3], headers: x[4] } : x }
codes.each_with_object({}) do |value, memo|
value[:message] ||= ''
memo[value[:code]] = { description: value[:message] }
memo[value[:code]][:headers] = value[:headers] if value[:headers]
next build_file_response(memo[value[:code]]) if file_response?(value[:model])
response_model = @item
response_model = expose_params_from_model(value[:model]) if value[:model]
if memo.key?(200) && route.request_method == 'DELETE' && value[:model].nil?
memo[204] = memo.delete(200)
value[:code] = 204
end
next if value[:code] == 204
next unless !response_model.start_with?('Swagger_doc') && (@definitions[response_model] || value[:model])
@definitions[response_model][:description] = description_object(route)
memo[value[:code]][:schema] = build_reference(route, value, response_model, options)
memo[value[:code]][:examples] = value[:examples] if value[:examples]
end
end
def success_code?(code)
status = code.is_a?(Array) ? code.first : code[:code]
status.between?(200, 299)
end
def http_codes_from_route(route)
if route.http_codes.is_a?(Array) && route.http_codes.any? { |code| success_code?(code) }
route.http_codes.clone
else
success_codes_from_route(route) + (route.http_codes || route.options[:failure] || [])
end
end
def success_codes_from_route(route)
if @entity.is_a?(Array)
return @entity.map do |entity|
success_code_from_entity(route, entity)
end
end
[success_code_from_entity(route, @entity)]
end
def tag_object(route, path)
version = GrapeSwagger::DocMethods::Version.get(route)
version = [version] unless version.is_a?(Array)
prefix = route.prefix.to_s.split('/').reject(&:empty?)
Array(
path.split('{')[0].split('/').reject(&:empty?).delete_if do |i|
prefix.include?(i) || version.map(&:to_s).include?(i)
end.first
).presence
end
private
def build_reference(route, value, response_model, settings)
# TODO: proof that the definition exist, if model isn't specified
reference = { '$ref' => "#/definitions/#{response_model}" }
return reference unless value[:code] < 300
reference = { type: 'array', items: reference } if route.options[:is_array]
build_root(route, reference, response_model, settings)
end
def build_root(route, reference, response_model, settings)
default_root = route.options[:is_array] ? response_model.downcase.pluralize : response_model.downcase
case route.settings.dig(:swagger, :root)
when true
{ type: 'object', properties: { default_root => reference } }
when false
reference
when nil
settings[:add_root] ? { type: 'object', properties: { default_root => reference } } : reference
else
{ type: 'object', properties: { route.settings.dig(:swagger, :root) => reference } }
end
end
def file_response?(value)
value.to_s.casecmp('file').zero? ? true : false
end
def build_file_response(memo)
memo['schema'] = { type: 'file' }
end
def partition_params(route, settings)
declared_params = route.settings[:declared_params] if route.settings[:declared_params].present?
required = merge_params(route)
required = GrapeSwagger::DocMethods::Headers.parse(route) + required unless route.headers.nil?
default_type(required)
request_params = unless declared_params.nil? && route.headers.nil?
GrapeSwagger::Endpoint::ParamsParser.parse_request_params(required, settings)
end || {}
request_params.empty? ? required : request_params
end
def merge_params(route)
param_keys = route.params.keys
route.params.delete_if { |key| key.is_a?(String) && param_keys.include?(key.to_sym) }.to_a
end
def default_type(params)
default_param_type = { required: true, type: 'Integer' }
params.each { |param| param[-1] = param.last == '' ? default_param_type : param.last }
end
def expose_params(value)
if value.is_a?(Class) && GrapeSwagger.model_parsers.find(value)
expose_params_from_model(value)
elsif value.is_a?(String)
begin
expose_params(Object.const_get(value.gsub(/\[|\]/, ''))) # try to load class from its name
rescue NameError
nil
end
end
end
def expose_params_from_model(model)
model = model.is_a?(String) ? model.constantize : model
model_name = model_name(model)
return model_name if @definitions.key?(model_name)
@definitions[model_name] = nil
parser = GrapeSwagger.model_parsers.find(model)
raise GrapeSwagger::Errors::UnregisteredParser, "No parser registered for #{model_name}." unless parser
properties, required = parser.new(model, self).call
unless properties&.any?
raise GrapeSwagger::Errors::SwaggerSpec,
"Empty model #{model_name}, swagger 2.0 doesn't support empty definitions."
end
@definitions[model_name] = GrapeSwagger::DocMethods::BuildModelDefinition.build(model, properties, required)
model_name
end
def model_name(name)
GrapeSwagger::DocMethods::DataType.parse_entity_name(name)
end
def hidden?(route, options)
route_hidden = route.settings.try(:[], :swagger).try(:[], :hidden)
route_hidden = route.options[:hidden] if route.options.key?(:hidden)
return route_hidden unless route_hidden.is_a?(Proc)
options[:token_owner] ? route_hidden.call(send(options[:token_owner].to_sym)) : route_hidden.call
end
def success_code_from_entity(route, entity)
default_code = GrapeSwagger::DocMethods::StatusCodes.get[route.request_method.downcase.to_sym]
if entity.is_a?(Hash)
default_code[:code] = entity[:code] if entity[:code].present?
default_code[:model] = entity[:model] if entity[:model].present?
default_code[:message] = entity[:message] || route.description || default_code[:message].sub('{item}', @item)
default_code[:examples] = entity[:examples] if entity[:examples]
default_code[:headers] = entity[:headers] if entity[:headers]
else
default_code = GrapeSwagger::DocMethods::StatusCodes.get[route.request_method.downcase.to_sym]
default_code[:model] = entity if entity
default_code[:message] = route.description || default_code[:message].sub('{item}', @item)
end
default_code
end
end
end
| 35.819843 | 119 | 0.660252 |
7ab2057927585d6719cc308a56ca33fb89cfad5c | 2,283 | # This is the main point of invocation for rendering a node within Adapt. It
# takes a design and a view template and merge them together for a complete page
# layout.
class NodeRenderer
# Initialize a new renderer.
def initialize(design, view_template, site, node)
@design = design
@view_template = view_template
@node = node
@site = site
end
# Return the assembled markup for the node
def markup
@markup ||= assemble_markup
end
private
# Assemble the markup for the current page
def assemble_markup
design_renderer = liquid_for(@design.markup)
view_renderer = liquid_for(@view_template.markup)
params = node_template_data.merge(global_template_data)
# Render the view template.
rendered_view = view_renderer.render(params, :filters => liquid_filters)
# Render the design and merge in the view.
design_renderer.render(params.merge('content' => rendered_view), :filters => liquid_filters)
end
# Returns the template data for the current node.
def node_template_data
{'node' => @node, @node['classification'] => @node}
end
# Returns the global template data.
def global_template_data
{'site' => @site, '__design_id' => @design.id, '__site_id' => @site['id']}
end
# Returns a new Liquid template for the specified template markup.
def liquid_for(markup)
Liquid::Template.file_system = IncludeTemplateFileSystem.new(@design)
Liquid::Template.register_tag('navigation', NavigationTag)
Liquid::Template.register_tag('resource_link', ResourceLinkTag)
Liquid::Template.register_tag('resource_image', ResourceImageTag)
Liquid::Template.register_tag('search', SearchBlock)
Liquid::Template.parse(markup)
end
# Returns an array of Liquid filters to apply when rendering a node.
def liquid_filters
[
StylesheetFilter,
JavascriptFilter,
AssignToFilter,
LinkToFilter,
GoogleAnalyticsFilter,
GoogleWebmasterToolsFilter,
GoogleJavascriptFilter,
TextileFilter,
DesignResourceFilter,
AttributeFilter,
ResourceFilter,
NodeFilter,
FormFilter
]
end
# Returns an array of Liquid filters to apply when rendering content in a
# view.
def liquid_view_filters
[]
end
end
| 27.506024 | 96 | 0.715287 |
629dc788fff7e9f0f824130ff2e7ac37bcc29398 | 1,366 | require "language/node"
class AwsCdk < Formula
desc "AWS Cloud Development Kit - framework for defining AWS infra as code"
homepage "https://github.com/aws/aws-cdk"
url "https://registry.npmjs.org/aws-cdk/-/aws-cdk-1.89.0.tgz"
sha256 "c40b09240f21cf9e70f92221661101efeaa4db4a411e421a1f177ad973084000"
license "Apache-2.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "6c13d82ebe6f18a3239067887cb55813dcd1bfa842b150ec5926b1e1db2a9ffb"
sha256 cellar: :any_skip_relocation, big_sur: "c7f9c360f7617c85afd4db83c41d1d20cf78ac4158adbcdf51a4ac67fa890359"
sha256 cellar: :any_skip_relocation, catalina: "a43b5886cc388b79b703bb802935f34d2a602f674a41ba13f6043d68ae9ee928"
sha256 cellar: :any_skip_relocation, mojave: "4557edd170aaac6e86d4de32d439fcfb4bfeb7ba4f017848281bb6b551c884ae"
end
depends_on "node"
def install
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
# `cdk init` cannot be run in a non-empty directory
mkdir "testapp" do
shell_output("#{bin}/cdk init app --language=javascript")
list = shell_output("#{bin}/cdk list")
cdkversion = shell_output("#{bin}/cdk --version")
assert_match "TestappStack", list
assert_match version.to_s, cdkversion
end
end
end
| 39.028571 | 122 | 0.751098 |
ac57bbda3f3abf199c370fdb51a20aaf0f01eaec | 744 | Pod::Spec.new do |s|
s.name = 'TestApp1'
s.version = '0.0.1'
s.summary = 'Application to test with sub apps'
s.description = <<-DESC
Application check for modules. It is app 1.
DESC
s.homepage = 'https://github.com/Marthitejasree/TestApp1.git'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Marthitejasree' => '[email protected]' }
s.source = { :git => 'https://github.com/Marthitejasree/TestApp1.git', :tag => s.version.to_s }
s.ios.deployment_target = '13.0'
s.source_files = 'TestApp1/*.{h,m,swift}'
s.resources = ['TestApp1/**/*.{storyboard,xib,xcassets}']
s.dependency 'Alamofire'
end
| 31 | 107 | 0.567204 |
610b6a19e49b929ed33ab641070c171e37a556b3 | 1,879 | require File.expand_path("../../Abstract/abstract-php-phar", __FILE__)
class Composer < AbstractPhpPhar
desc "Dependency Manager for PHP"
homepage "https://getcomposer.org"
url "https://getcomposer.org/download/1.6.2/composer.phar"
sha256 "6ec386528e64186dfe4e3a68a4be57992f931459209fd3d45dde64f5efb25276"
head "https://getcomposer.org/composer.phar"
bottle do
cellar :any_skip_relocation
sha256 "bee673482a6aaa6e47c16886856fc1529a9baa7cb7eca4c663e5f7a7abb4ca08" => :high_sierra
sha256 "bee673482a6aaa6e47c16886856fc1529a9baa7cb7eca4c663e5f7a7abb4ca08" => :sierra
sha256 "bee673482a6aaa6e47c16886856fc1529a9baa7cb7eca4c663e5f7a7abb4ca08" => :el_capitan
end
depends_on PharRequirement
test do
system "#{bin}/composer", "--version"
end
# The default behavior is to create a shell script that invokes the phar file.
# Other tools, at least Ansible, expect the composer executable to be a PHP
# script, so override this method. See
# https://github.com/Homebrew/homebrew-php/issues/3590
def phar_wrapper
<<-EOS.undent
#!/usr/bin/env php
<?php
array_shift($argv);
$arg_string = implode(' ', array_map('escapeshellarg', $argv));
$arg_prefix = preg_match('/--(no-)?ansi/', $arg_string) ? '' : '--ansi ';
$arg_string = $arg_prefix . $arg_string;
passthru("/usr/bin/env php -d allow_url_fopen=On -d detect_unicode=Off #{libexec}/#{@real_phar_file} $arg_string", $return_var);
exit($return_var);
EOS
end
def caveats
<<-EOS
composer no longer depends on the homebrew php Formulas since the last couple of macOS releases
contains a php version compatible with composer. If this has been part of your workflow
previously then please make the appropriate changes and `brew install php71` or other appropriate
Homebrew PHP version.
EOS
end
end
| 38.346939 | 134 | 0.728047 |
030904c239604aa7b12d7783c2bae992e63599f9 | 2,337 | # MIT License
#
# Copyright (c) Sebastian Katzer 2017
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
dummy = SFTP::Session.new(SSH::Session.new)
assert 'SFTP::FileFactory' do
assert_kind_of Class, SFTP::FileFactory
end
assert 'SFTP::FileFactory#initialize' do
assert_raise(ArgumentError) { SFTP::FileFactory.new }
assert_nothing_raised { SFTP::FileFactory.new(dummy) }
end
SFTP.start('test.rebex.net', 'demo', password: 'password') do |sftp|
assert 'SFTP::FileFactory#directory?' do
assert_raise(SFTP::NotConnected) { dummy.file.directory? '/pub' }
assert_raise(ArgumentError) { sftp.file.directory? }
assert_true sftp.file.directory? '/pub'
assert_false sftp.file.directory? 'readme.txt'
assert_false sftp.file.directory? 'I am wrong'
end
assert 'SFTP::FileFactory#open' do
assert_raise(SFTP::NotConnected) { dummy.file.open 'readme.txt' }
assert_raise(ArgumentError) { sftp.file.open }
assert_raise(SFTP::FileError) { sftp.file.open 'readme txt' }
io = sftp.file.open('readme.txt')
assert_kind_of SFTP::File, io
assert_true io.open?
io.close
invoked = false
sftp.file.open('readme.txt') do |file|
invoked = true
io = file
assert_kind_of SFTP::File, file
end
assert_true invoked
assert_true io.closed?
end
end
| 35.409091 | 80 | 0.735131 |
ed7f60b0d55a84c0c75bb4b750ee69cc08f8b476 | 1,108 | require 'rails_helper'
require Rails.root.join('lib', 'tasks', 'hbx_import', 'broker', 'parsers', 'broker_parser')
describe Parser::BrokerParser do
before(:all) do
xml = Nokogiri::XML(File.open(Rails.root.join('spec', 'test_data', 'NewBrokerFile.xml')))
@brokers = Parser::BrokerParser.parse(xml.root.canonicalize).map(&:to_hash)
end
it 'should parse 2 brokers from xml' do
expect(@brokers.length).to eq(2)
end
it 'should extracts person name fields from xml' do
expect(@brokers.first[:name][:first_name]).to eq('Ellen')
expect(@brokers.first[:name][:last_name]).to eq('Cool')
end
it 'should extracts email field' do
expect(@brokers.first[:emails].first[:kind]).to eq('work')
expect(@brokers.first[:emails].first[:address]).to eq('[email protected]')
end
it 'should extracts phone field' do
expect(@brokers.first[:phones].first[:kind]).to eq('work')
expect(@brokers.first[:phones].first[:full_phone_number]).to eq('+1-100-728-5005')
end
it 'should extracts broker fields' do
expect(@brokers.first[:npn]).to eq('14636000')
end
end | 32.588235 | 93 | 0.686823 |
0363188fba500bca69fd7aa5e9dfaaf6c4fcd636 | 565 | require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
Dotenv::Railtie.load
module CollabCont
class Application < Rails::Application
config.assets.precompile += %w( add_users_modal.js )
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
end
end
| 31.388889 | 82 | 0.759292 |
e95b7d25467f12abcb7c97def8d7db794d8f67a0 | 409 | class CreatePagesAndFields< ActiveRecord::Migration<%= migration_version %>
def change
create_table :editable_pages do |t|
t.string :name
t.text :description
t.string :kind
t.timestamps
end
create_table :editable_fields do |t|
t.string :label
t.string :kind
t.text :value
t.references :page, foreign_key: true
t.timestamps
end
end
end
| 22.722222 | 75 | 0.650367 |
e940ebfaf0a13333ab9ccfe566025eb3d12192a0 | 1,789 | # frozen_string_literal: true
module DiceBag
# This class abstracts access to configuration values, to be used within ERB
# templates. Currently, the values are read from the environment, as per the
# Twelve-Factor App principles.
class Configuration
def initialize
@prefixed = {}
end
# Returns a Configuration::PrefixedWithFallback using the given +prefix+.
#
def [](prefix)
@prefixed[prefix] ||= PrefixedWithFallback.new(prefix, self)
end
def method_missing(name)
if name.to_s.end_with?("!")
ensured_in_production(name)
else
ENV[name.to_s.upcase]
end
end
private
def ensured_in_production(name)
variable_name = name.to_s.chomp("!").upcase
value = ENV[variable_name]
if in_production? && value.nil?
raise "Environment variable #{variable_name} required in production but it was not provided"
end
value
end
def in_production?
(defined?(Rails) && Rails.env.production?) ||
(defined?(Sinatra) && Sinatra::Application.production?) ||
ENV["RACK_ENV"] == "production"
end
# This class acts like +Configuration+ but with a prefix applied to the
# environment variables used to provide values. This is useful for providing
# per-environment overrides to value in Rails projects. If the prefixed
# environment variable is not found, the class delegates to the provided
# fallback Configuration class, without the prefix.
#
class PrefixedWithFallback
def initialize(prefix, fallback)
@prefix = prefix.to_s.upcase
@fallback = fallback
end
def method_missing(name)
ENV["#{@prefix}_#{name.to_s.upcase}"] || @fallback.send(name)
end
end
end
end
| 28.854839 | 100 | 0.665735 |
180045e6a8b464cd90aba523de0276f1997cd6dd | 5,439 |
require 'spec_helper'
describe 'VagrantPlugins::GuestAlpine::Cap::ChangeHostname' do
let(:described_class) do
VagrantPlugins::GuestAlpine::Plugin.components.guest_capabilities[:alpine].get(:change_host_name)
end
let(:machine) { double('machine') }
let(:communicator) { VagrantTests::DummyCommunicator::Communicator.new(machine) }
let(:old_hostname) { 'oldhostname.olddomain.tld' }
before do
allow(machine).to receive(:communicate).and_return(communicator)
communicator.stub_command('hostname -f', stdout: old_hostname)
end
after do
communicator.verify_expectations!
end
describe '.change_host_name' do
it 'updates /etc/hostname on the machine' do
communicator.expect_command("echo 'newhostname' > /etc/hostname")
described_class.change_host_name(machine, 'newhostname.newdomain.tld')
end
it 'does nothing when the provided hostname is not different' do
described_class.change_host_name(machine, 'oldhostname.olddomain.tld')
expect(communicator.received_commands).to eq(['hostname -f'])
end
it 'refreshes the hostname service with the hostname command' do
communicator.expect_command('hostname -F /etc/hostname')
described_class.change_host_name(machine, 'newhostname.newdomain.tld')
end
it 'renews dhcp on the system with the new hostname' do
communicator.expect_command('ifdown -a; ifup -a; ifup eth0')
described_class.change_host_name(machine, 'newhostname.newdomain.tld')
end
describe 'flipping out the old hostname in /etc/hosts' do
let(:sed_command) do
# Here we run the change_host_name through and extract the recorded sed
# command from the dummy communicator
described_class.change_host_name(machine, 'newhostname.newdomain.tld')
communicator.received_commands.find { |cmd| cmd =~ /^sed/ }
end
# Now we extract the regexp from that sed command so we can do some
# verification on it
let(:expression) { sed_command.sub(%r{^sed -ri '\(.*\)' /etc/hosts$}, "\1") }
let(:search) { Regexp.new(expression.split('@')[1], Regexp::EXTENDED) }
let(:replace) { expression.split('@')[2] }
let(:grep_command) { "grep '#{old_hostname}' /etc/hosts" }
before do
communicator.stub_command(grep_command, exit_code: 0)
end
it 'works on an simple /etc/hosts file' do
original_etc_hosts = <<-ETC_HOSTS.gsub(/^ */, '')
127.0.0.1 localhost
127.0.1.1 oldhostname.olddomain.tld oldhostname
ETC_HOSTS
modified_etc_hosts = original_etc_hosts.gsub(search, replace)
expect(modified_etc_hosts).to eq <<-RESULT.gsub(/^ */, '')
127.0.0.1 localhost
127.0.1.1 newhostname.newdomain.tld newhostname
RESULT
end
it 'does not modify lines which contain similar hostnames' do
original_etc_hosts = <<-ETC_HOSTS.gsub(/^ */, '')
127.0.0.1 localhost
127.0.1.1 oldhostname.olddomain.tld oldhostname
# common prefix, but different fqdn
192.168.12.34 oldhostname.olddomain.tld.different
# different characters at the dot
192.168.34.56 oldhostname-olddomain.tld
ETC_HOSTS
modified_etc_hosts = original_etc_hosts.gsub(search, replace)
expect(modified_etc_hosts).to eq <<-RESULT.gsub(/^ */, '')
127.0.0.1 localhost
127.0.1.1 newhostname.newdomain.tld newhostname
# common prefix, but different fqdn
192.168.12.34 oldhostname.olddomain.tld.different
# different characters at the dot
192.168.34.56 oldhostname-olddomain.tld
RESULT
end
it "appends 127.0.1.1 if it isn't there" do
communicator.stub_command(grep_command, exit_code: 1)
described_class.change_host_name(machine, 'newhostname.newdomain.tld')
sed = communicator.received_commands.find { |cmd| cmd =~ /^sed/ }
expect(sed).to be_nil
echo = communicator.received_commands.find { |cmd| cmd =~ /^echo/ }
expect(echo).to_not be_nil
end
context 'when the old fqdn has a trailing dot' do
let(:old_hostname) { 'oldhostname.withtrailing.dot.' }
it 'modifies /etc/hosts properly' do
original_etc_hosts = <<-ETC_HOSTS.gsub(/^ */, '')
127.0.0.1 localhost
127.0.1.1 oldhostname.withtrailing.dot. oldhostname
ETC_HOSTS
modified_etc_hosts = original_etc_hosts.gsub(search, replace)
expect(modified_etc_hosts).to eq <<-RESULT.gsub(/^ */, '')
127.0.0.1 localhost
127.0.1.1 newhostname.newdomain.tld newhostname
RESULT
end
end
end
end
end
| 42.162791 | 105 | 0.576944 |
4acc10339289f4532942647d71aa6b1fe86f9aa9 | 136 | require 'sqlite3'
db = SQLite3::Database.new'Test_SQL.sqlite'
db.execute"INSERT INTO Cars (Name, Price) values('Opel', 4500)"
db.close
| 22.666667 | 63 | 0.742647 |
bfb6cfe024ffb9108ab10d83dc1907cb4ee45f4d | 324 | class CreateProxyDepositRights < ActiveRecord::Migration[4.2]
def change
create_table :proxy_deposit_rights do |t|
t.references :grantor
t.references :grantee
t.timestamps null: false
end
add_index :proxy_deposit_rights, :grantor_id
add_index :proxy_deposit_rights, :grantee_id
end
end
| 27 | 61 | 0.737654 |
ede8ac2c686603700683105b7a7dfdcd4d22b456 | 2,842 | # frozen_string_literal: true
#
# Copyright:: 2021, Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'spec_helper'
describe RuboCop::Cop::Chef::Modernize::UnnecessaryDependsChef15, :config do
it 'registers an offense when a cookbook depends on "libarchive"' do
expect_offense(<<~RUBY)
depends 'libarchive'
^^^^^^^^^^^^^^^^^^^^ Don't depend on cookbooks made obsolete by Chef Infra Client 15.0+. These community cookbooks contain resources that are now included in Chef Infra Client itself.
RUBY
end
it 'registers an offense when a cookbook depends on "windows_dns"' do
expect_offense(<<~RUBY)
depends 'windows_dns'
^^^^^^^^^^^^^^^^^^^^^ Don't depend on cookbooks made obsolete by Chef Infra Client 15.0+. These community cookbooks contain resources that are now included in Chef Infra Client itself.
RUBY
end
it 'registers an offense when a cookbook depends on "windows_uac"' do
expect_offense(<<~RUBY)
depends 'windows_uac'
^^^^^^^^^^^^^^^^^^^^^ Don't depend on cookbooks made obsolete by Chef Infra Client 15.0+. These community cookbooks contain resources that are now included in Chef Infra Client itself.
RUBY
end
it 'registers an offense when a cookbook depends on "windows_dfs"' do
expect_offense(<<~RUBY)
depends 'windows_dfs'
^^^^^^^^^^^^^^^^^^^^^ Don't depend on cookbooks made obsolete by Chef Infra Client 15.0+. These community cookbooks contain resources that are now included in Chef Infra Client itself.
RUBY
end
it "doesn't register an offense when depending on any old cookbook" do
expect_no_offenses(<<~RUBY)
depends 'build-essentially'
RUBY
end
it 'registers an offense when a cookbook depends on "windows_dfs" and specifies a version constraint' do
expect_offense(<<~RUBY)
depends 'windows_dfs', '>= 8.0.1'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Don't depend on cookbooks made obsolete by Chef Infra Client 15.0+. These community cookbooks contain resources that are now included in Chef Infra Client itself.
RUBY
end
context 'with TargetChefVersion set to 14' do
let(:config) { target_chef_version(14) }
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
depends 'windows_dfs', '>= 8.0.1'
RUBY
end
end
end
| 39.472222 | 202 | 0.701619 |
f8fdf9f7ac9b71a554376ad918588fa7b189b797 | 120 | class Disciplina < ActiveRecord::Base
has_many :oferecimentos
has_many :professores, :through => :oferecimentos
end
| 24 | 51 | 0.783333 |
79d713cd1e86156a48f23383b2613920e9088274 | 8,284 | class GetRecords < BaseCswModel
RESULT_TYPES = %w(results hits)
RESPONSE_ELEMENTS = %w(brief summary full)
attr_accessor :result_types
validate :validate_method
attr_accessor :result_type
validates :result_type, inclusion: {in: RESULT_TYPES, message: "Result type '%{value}' is not supported. Supported result types are results, hits"}
attr_accessor :start_position
validates :start_position, numericality: {only_integer: true, greater_than_or_equal_to: 1, message: 'startPosition is not a positive integer greater than zero'}
attr_accessor :max_records
validates :max_records, numericality: {only_integer: true, greater_than_or_equal_to: 0, message: 'maxRecords is not a positive integer'}
attr_accessor :response_element
validates :response_element, inclusion: {in: RESPONSE_ELEMENTS, message: "Element set name '%{value}' is not supported. Supported element set names are brief, summary, full"}
attr_accessor :output_schema
validates :output_schema, inclusion: {in: OUTPUT_SCHEMAS, message: "Output schema '%{value}' is not supported. Supported output schemas are http://www.opengis.net/cat/csw/2.0.2, http://www.isotc211.org/2005/gmi"}
@request_body_xml
@filter
@result_type
@start_position
@max_records
# for now it only supports the AND between ALL CMR query parameters
@cmr_query_hash
# indicates whether or not CWICSmart is the requestor
@invoked_from_cwicsmart
def initialize(params, request)
super(params, request)
@cmr_query_hash = Hash.new
@invoked_from_cwicsmart = false
if (@request.get?)
@output_schema = params[:outputSchema].blank? ? 'http://www.isotc211.org/2005/gmi' : params[:outputSchema]
@output_file_format = params[:outputFormat].blank? ? 'application/xml' : params[:outputFormat]
@result_type = params[:resultType].blank? ? 'hits' : params[:resultType]
@response_element = params[:ElementSetName].blank? ? 'brief' : params[:ElementSetName]
@start_position = params[:startPosition].blank? ? '1' : params[:startPosition]
@max_records = params[:maxRecords].blank? ? '10' : params[:maxRecords]
@version = params[:version]
@service = params[:service]
constraint = params[:constraint].blank? ? '' : params[:constraint]
constraint_language = params[:CONSTRAINTLANGUAGE].blank? ? '' : params[:CONSTRAINTLANGUAGE]
if !constraint.blank?
filter = CqlFilter.new(constraint,constraint_language,@cmr_query_hash)
filter.process_constraint()
end
else
if (!@request_body.empty? && @request.post?)
begin
@request_body_xml = Nokogiri::XML(@request_body) { |config| config.strict }
rescue Nokogiri::XML::SyntaxError => e
Rails.logger.error("Could not parse the GetRecords request body XML: #{@request_body} ERROR: #{e.message}")
raise OwsException.new('NoApplicableCode', "Could not parse the GetRecords request body XML: #{e.message}")
end
output_schema_value = @request_body_xml.root['outputSchema']
@output_schema = output_schema_value.blank? ? 'http://www.isotc211.org/2005/gmi' : output_schema_value
# defaults to 'hits' (per spec)
result_type_value = @request_body_xml.root['resultType']
@result_type = (result_type_value.blank? || RESULT_TYPES.include?(result_type_value) == false) ? 'hits' : result_type_value
# defaults to 'brief' (per spec)
element_set_name_value = @request_body_xml.at_xpath('//csw:GetRecords//csw:Query//csw:ElementSetName',
'csw' => 'http://www.opengis.net/cat/csw/2.0.2')
@response_element = element_set_name_value.blank? ? 'brief' : element_set_name_value.text
start_position_value = @request_body_xml.root['startPosition']
# defaults to 1 (per spec)
@start_position = start_position_value.blank? ? '1' : start_position_value
max_records_value = @request_body_xml.root['maxRecords']
# defaults to 10 (per spec)
@max_records = max_records_value.blank? ? '10' : max_records_value
@output_file_format = @request_body_xml.root['outputFormat'].blank? ? 'application/xml' : @request_body_xml.root['outputFormat']
@service = @request_body_xml.root['service']
@version = @request_body_xml.root['version']
# Process the filter
@filter = @request_body_xml.at_xpath('//csw:GetRecords//csw:Query//csw:Constraint//ogc:Filter',
'csw' => 'http://www.opengis.net/cat/csw/2.0.2',
'ogc' => 'http://www.opengis.net/ogc')
if @filter != nil
filter = OgcFilter.new(@filter, @cmr_query_hash)
filter.process_all_queryables
else
#Rails.logger.info("No results filtering criteria specified in GetRecords POST request: #{@request_body}")
end
end
end
end
def find
Rails.logger.info "CMR Params: #{@cmr_query_hash}"
response = nil
@cmr_query_hash[:offset] = @start_position unless @start_position == '1'
@cmr_query_hash[:page_size] = @max_records unless @max_records == '10'
# special behavior for CWICSmart, for some reason the headers for POST from rspec and regular POST appear in
# different places in the rails request headers hash
from_cwic = nil
# regular rails request
if(@request.headers['From-Cwic-Smart'] != nil)
from_cwic = @request.headers['From-Cwic-Smart']
end
# rspec request
if(@request.headers['HTTP_HEADERS'] != nil)
from_cwic = @request.headers['HTTP_HEADERS']['From-Cwic-Smart']
end
if(from_cwic != nil && from_cwic.upcase == 'Y')
@invoked_from_cwicsmart = true
end
@cmr_query_hash = add_cwic_parameter(@cmr_query_hash, @invoked_from_cwicsmart)
begin
time = Benchmark.realtime do
query_url = "#{Rails.configuration.cmr_search_endpoint}/collections"
Rails.logger.info "RestClient call to CMR endpoint: #{query_url}?#{@cmr_query_hash.to_query}"
response = RestClient::Request.execute :method => :get, :url => "#{query_url}?#{@cmr_query_hash.to_query}",
:verify_ssl => OpenSSL::SSL::VERIFY_NONE,
:headers => {:client_id => ENV['client_id'],
:accept => 'application/iso19115+xml'}
end
Rails.logger.info "CMR collection search took #{(time.to_f * 1000).round(0)} ms"
rescue RestClient::Exception => e
error_message = "CMR call failure httpStatus: #{e.http_code} message: #{e.message} response: #{e.response}"
Rails.logger.error(error_message)
# TODO add error handling
raise OwsException.new('NoApplicableCode', error_message)
end
document = Nokogiri::XML(response)
document = BaseCswModel.add_cwic_keywords document
# This model is an array of collections in the iso19115 format. It's up to the view to figure out how to render it
# Each gmi:MI_Metadata element is a collection
model = OpenStruct.new
# didn't convert to UTC Time.now.utc.iso8601
model.server_timestamp = Time.now.iso8601
model.output_schema = @output_schema
model.response_element = @response_element
model.result_type = @result_type
model.number_of_records_matched = document.at_xpath('/results/hits').text.to_i
# will include as a comment in the csw response XML
model.cmr_search_duration_millis = document.at_xpath('/results/took').text.to_i
result_nodes = document.root.xpath('/results/result')
model.number_of_records_returned = result_nodes.blank? ? 0 : result_nodes.size
if (model.number_of_records_matched > model.number_of_records_returned)
model.next_record = 1 + @cmr_query_hash[:offset].to_i + model.number_of_records_returned
else
# indicates that ALL records have been returned
model.next_record = 0
end
model.raw_collections_doc = document
return model
end
private
def validate_method
if ([email protected]? && [email protected]?)
errors.add(:method, 'Only the HTTP POST and GET methods are supported for GetRecords')
end
end
end | 47.609195 | 214 | 0.678416 |
ed441411b825f3f747238d15657535c8c80bec35 | 1,200 | class PostsController < ApplicationController
# GET /posts/1
def show
post
@comment = Comment.new(post_id: params[:id])
@comments = @post.comments.reverse
end
# GET /posts/new
def new
@post = Post.new
end
# GET /posts/1/edit
def edit
post
end
# POST /posts
def create
@post = current_user.posts.build(post_params)
if @post.save
redirect_to authenticated_root_path
else
flash.now[:error] = @post.errors.messages
render :new
end
end
# PATCH/PUT /posts/1
def update
post
authorize @post
if @post.update(post_params)
redirect_to @post, notice: 'Post was successfully updated.'
else
render :edit
end
end
# DELETE /posts/1
def destroy
post
authorize @post
@post.destroy
redirect_to authenticated_root_path, notice: 'Post was successfully destroyed.'
end
private
def post
@post ||= Post.find(params[:id])
@like = @post.likes.where("user_id = ?", current_user.id).first
return @post
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:content)
end
end
| 18.75 | 86 | 0.658333 |
ab413d0f7f7c3b7f2413627f85718f5546dba620 | 1,708 | #
# Author:: Daniel DeLeo (<[email protected]>)
# Copyright:: Copyright (c) 2010 Opscode, 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 'spec_helper'
require 'tiny_server'
describe Chef::Knife::Exec do
before(:all) do
Thin::Logging.silent = false
@server = TinyServer::Manager.new#(:debug => true)
@server.start
end
before(:each) do
@knife = Chef::Knife::Exec.new
@api = TinyServer::API.instance
@api.clear
Chef::Config[:node_name] = false
Chef::Config[:client_key] = false
Chef::Config[:chef_server_url] = 'http://localhost:9000'
$output = StringIO.new
end
after(:all) do
@server.stop
end
pending "executes a script in the context of the shef main context", :ruby_18_only
it "executes a script in the context of the shef main context", :ruby_19_only do
@node = Chef::Node.new
@node.name("ohai-world")
response = {"rows" => [@node],"start" => 0,"total" => 1}
@api.get(%r{^/search/node}, 200, response.to_json)
code = "$output.puts nodes.all.inspect"
@knife.config[:exec] = code
@knife.run
$output.string.should match(%r{node\[ohai-world\]})
end
end
| 28.466667 | 84 | 0.685597 |
26d73c2d8f487b51f489bbbf98a5d741c52bc68a | 446 | # frozen_string_literal: true
require 'spec_helper'
require 'vk/api/newsfeed/responses/get_banned_response'
RSpec.describe Vk::API::Newsfeed::Responses::GetBannedResponse do
subject(:model) { described_class }
it { is_expected.to be < Dry::Struct }
it { is_expected.to be < Vk::Schema::Response }
describe 'attributes' do
subject(:attributes) { model.instance_methods(false) }
it { is_expected.to include :response }
end
end
| 27.875 | 65 | 0.73991 |
91f93973d2bcbc019c2cce186b192aecdbf9d513 | 104 | # frozen_string_literal: true
require "omniauth-netlify/version"
require "omniauth/strategies/netlify"
| 20.8 | 37 | 0.826923 |
f8f3bbe7b05c2aa8b1b943508049fa08356c3673 | 6,135 | # frozen_string_literal: true
module Stupidedi
include Refinements
class Either
# @return [Boolean]
abstract :defined?
###########################################################################
# @group Filtering the Value
# @return [Either]
abstract :select, :args => %w(reason='select' &block)
# @return [Either]
abstract :reject, :args => %w(reason='reject' &block)
# @endgroup
###########################################################################
###########################################################################
# @group Transforming the Value
# @return [Either]
abstract :map, :args => %w(&block)
# @return [Either]
abstract :flatmap, :args => %w(&block)
# @return [Either]
abstract :or, :args => %w(&block)
# @return [Either]
abstract :explain, :args => %w(&block)
# @return [Object]
abstract :fetch, :args => %w(default)
# @endgroup
###########################################################################
class Success < Either
def initialize(value)
@value = value
end
def copy(changes = {})
Success.new \
changes.fetch(:value, @value)
end
# @return true
def defined?
true
end
def fetch(default = nil)
@value
end
#########################################################################
# @group Filtering the Value
# @return [Either]
# @yieldparam value
# @yieldreturn [Boolean]
def select(reason = "select", &block)
if deconstruct(block)
self
else
failure(reason)
end
end
# @return [Either]
# @yieldparam value
# @yieldreturn [Boolean]
def reject(reason = "reject", &block)
if deconstruct(block)
failure(reason)
else
self
end
end
# @endgroup
#########################################################################
#########################################################################
# @group Transforming the Value
# @return [Success]
# @yieldparam value
# @yieldreturn value
def map(&block)
copy(:value => deconstruct(block))
end
# @return [Either]
# @yieldparam value
# @yieldreturn [Either]
def flatmap(&block)
result = deconstruct(block)
if result.is_a?(Either)
result
else
raise TypeError, "block did not return an instance of Either"
end
end
# @return [Success]
def or
self
end
# @return [Success]
def explain
self
end
# @endgroup
#########################################################################
def tap(&block)
deconstruct(block); self
end
# @return [Boolean]
def ==(other)
other.is_a?(Either) and other.select{|x| x == @value }.defined?
end
# @return [void]
def pretty_print(q)
q.text("Either.success")
q.group(2, "(", ")") do
q.breakable ""
q.pp @value
end
end
# @return [String]
def inspect
"Either.success(#{@value.inspect})"
end
private
def deconstruct(block)
block.call(@value)
end
def failure(reason)
Either::Failure.new(reason)
end
end
class Failure < Either
attr_reader :reason
def initialize(reason)
@reason = reason
end
# @return [Failure]
def copy(changes = {})
Failure.new \
changes.fetch(:reason, @reason)
end
# @return false
def defined?
false
end
def fetch(default = nil)
default
end
#########################################################################
# @group Filtering the Value
# @return [Failure]
def select(reason = nil)
self
end
# @return [Failure]
def reject(reason = nil)
self
end
# @endgroup
#########################################################################
#########################################################################
# @group Transforming the Value
# @return [Failure]
def map
self
end
# @return [Failure]
def flatmap
self
end
# @return [Either]
# @yieldparam reason
# @yieldreturn [Either]
def or(&block)
result = deconstruct(block)
if result.is_a?(Either)
result
else
raise TypeError, "block did not return an instance of Either"
end
end
# @return [Failure]
# @yieldparam reason
# @yieldreturn reason
def explain(&block)
copy(:reason => deconstruct(block))
end
# @endgroup
#########################################################################
def tap
self
end
# @return [Boolean]
def ==(other)
other.is_a?(self.class) and other.reason == @reason
end
# @return [void]
def pretty_print(q)
q.text("Either.failure")
q.group(2, "(", ")") do
q.breakable ""
q.pp @reason
end
end
# @return [String]
def inspect
"Either.failure(#{@reason.inspect})"
end
private
def deconstruct(block)
block.call(@reason)
end
end
end
class << Either
###########################################################################
# @group Constructors
# @return [Success]
def success(value)
Either::Success.new(value)
end
# @return [Failure]
def failure(reason)
Either::Failure.new(reason)
end
# @endgroup
###########################################################################
end
Either.eigenclass.send(:protected, :new)
Either::Success.eigenclass.send(:public, :new)
Either::Failure.eigenclass.send(:public, :new)
end
| 21.010274 | 79 | 0.429666 |
d539b59cef1b406443e7de270ffb53361a893527 | 45 | Rails.application.config.token_expires = 3600 | 45 | 45 | 0.866667 |
0894b933f70a4570dd23486f6ca6c56d118a881e | 3,226 | require_relative './simplecov_helper'
require_relative './rspec_configuration'
require 'helpers/spec_helper_helpers'
require 'helpers/named_maps_helper'
require 'helpers/unique_names_helper'
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Needed because load order changes in Ruby 2.3+, related to https://github.com/rspec/rspec-rails/pull/1372
# We can remove this if we upgrade to rspec 3+
ActiveRecord.send(:remove_const, :TestFixtures) if ActiveRecord.const_defined?(:TestFixtures)
require 'rspec/rails'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Inline Resque for queue handling
Resque.inline = true
# host_validation is set to support `example.com` emails in specs
# in production we do check for the existance of mx records associated to the domain
EmailAddress::Config.configure(local_format: :conventional, host_validation: :syntax)
RSpec.configure do |config|
config.include SpecHelperHelpers
config.include CartoDB::Factories
config.include HelperMethods
config.include NamedMapsHelper
config.after(:each) do
Delorean.back_to_the_present
end
unless ENV['PARALLEL']
config.before(:suite) do
CartoDB::RedisTest.up
end
end
config.before(:all) do
unless ENV['PARALLEL']
clean_redis_databases
clean_metadata_database
close_pool_connections
drop_leaked_test_user_databases
end
CartoDB::UserModule::DBService.any_instance.stubs(:configure_ghost_table_event_trigger).returns(true)
end
config.after(:all) do
unless ENV['PARALLEL']
close_pool_connections
drop_leaked_test_user_databases
delete_database_test_users
end
end
unless ENV['PARALLEL']
config.after(:suite) do
CartoDB::RedisTest.down
end
end
module Rack
module Test
module Methods
def build_rack_mock_session
Rack::MockSession.new(app, host)
end
def with_host(temp_host)
old_host = host
host! temp_host
yield
ensure
host! old_host
end
end
end
end
end
def superadmin_headers
http_json_authorization_headers(Cartodb.config[:superadmin]["username"],
Cartodb.config[:superadmin]["password"])
end
def org_metadata_api_headers
http_json_authorization_headers(Cartodb.config[:org_metadata_api]["username"],
Cartodb.config[:org_metadata_api]["password"])
end
def http_json_authorization_headers(user, password)
http_json_headers.merge(
"HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials(user, password),
"HTTP_ACCEPT" => "application/json")
end
def http_json_headers
{ "CONTENT_TYPE" => "application/json", :format => "json" }
end
def fake_data_path(filename)
Rails.root.join("db/fake_data/#{filename}").to_s
end
def login_page_response?(response)
response.status == 200 && response.body.include?("title=\"Email or username\"")
end
| 28.052174 | 107 | 0.722877 |
266f68669efc8ac447eb59617bba668e2a45ae3a | 4,713 | # -*- coding: utf-8 -*-
#
# Cookbook Name:: sentry cookbook
# Definition:: sentry_conf
#
# Making sentry configuration file
#
# :copyright: (c) 2012 - 2013 by Alexandr Lispython ([email protected]).
# :license: BSD, see LICENSE for more details.
# :github: http://github.com/Lispython/sentry-cookbook
#
class Chef::Recipe
include Chef::Mixin::DeepMerge
end
define :sentry_conf,
:name => nil,
:template => "sentry/sentry.conf.erb",
:virtualenv_dir => nil,
:user => "sentry",
:group => "sentry",
:config => nil,
:superusers => [],
:variables => {},
:templates_cookbook => "sentry",
:settings => {} do
Chef::Log.info("Making sentry config for: #{params[:name]}")
include_recipe "python::virtualenv"
include_recipe "python::pip"
include_recipe "sentry::default"
virtualenv_dir = params[:virtualenv_dir] or node["sentry"]["virtulenv"]
#settings_variables = Chef::Mixin::DeepMerge.deep_merge!(node[:sentry][:settings].to_hash, params[:settings])
node.default["settings_variables"] = params[:settings]
config = params[:config] || node["sentry"]["config"]
node.default["settings_variables"]["config"] = config
Chef::Log.info("Making directory for virtualenv: #{virtualenv_dir}")
# Making application virtualenv directory
directory virtualenv_dir do
owner params[:user]
group params[:group]
mode 0777
recursive true
action :create
end
Chef::Log.info("Making virtualenv: #{virtualenv_dir}")
# Creating virtualenv structure
python_virtualenv virtualenv_dir do
owner params[:user]
group params[:group]
action :create
end
Chef::Log.info("Making config #{config}")
# Creating sentry config
template config do
owner params[:user]
group params[:group]
source params[:template]
mode 0777
variables(node["settings_variables"].to_hash)
cookbook params[:templates_cookbook]
end
# Intstall sentry via pip
python_pip "sentry" do
provider Chef::Provider::PythonPip
user params[:user]
group params[:group]
virtualenv virtualenv_dir
version node["sentry"]["version"]
action :install
end
# Install database drivers
node['sentry']['settings']['databases'].each do |key, db_options|
driver_name = nil
if db_options['ENGINE'] == 'django.db.backends.postgresql_psycopg2'
driver_name = 'psycopg2'
elsif db_options['ENGINE'] == 'django.db.backends.mysql'
if node['platform'] == 'ubuntu'
package "libmysqlclient-dev" # mysql-python requires this package to be installed
driver_name = 'mysql-python'
else
driver_name = 'MySQLdb'
end
elsif db_options['ENGINE'] == 'django.db.backends.oracle'
driver_name = 'cx_Oracle'
else
raise "You need specify database ENGINE"
end
if driver_name
Chef::Log.info("Install #{driver_name} driver")
python_pip driver_name do
user params[:user]
group params[:group]
provider Chef::Provider::PythonPip
virtualenv virtualenv_dir
action :install
end
end
end
# # Install third party plugins
node["sentry"]["settings"]["third_party_plugins"].each do |item|
python_pip item["pypi_name"] do
user params[:user]
group params[:group]
provider Chef::Provider::PythonPip
virtualenv virtualenv_dir
if item.has_key?("version")
version item["version"]
end
action :install
end
end
bash "chown virtualenv" do
code <<-EOH
chown -R #{params['user']}:#{params['group']} #{virtualenv_dir}
EOH
end
# # Run migrations
# # sentry --config=/etc/sentry.conf.py upgrade
bash "upgrade sentry" do
user params[:user]
group params[:group]
code <<-EOH
. #{virtualenv_dir}/bin/activate &&
#{virtualenv_dir}/bin/python #{virtualenv_dir}/bin/sentry --config=#{config} upgrade --noinput &&
deactivate
EOH
end
# # Create superusers
template node["sentry"]["superuser_creator_script"] do
owner params[:user]
group params[:group]
source "sentry/superuser_creator.py.erb"
variables(:config => config,
:superusers => params[:superusers] || node["sentry"]["superusers"],
:virtualenv => virtualenv_dir)
cookbook params[:templates_cookbook]
end
# # sentry --config=/etc/sentry.conf.py createsuperuser
bash "create sentry superusers" do
user params[:user]
group params[:group]
code <<-EOH
. #{virtualenv_dir}/bin/activate &&
#{virtualenv_dir}/bin/python #{node['sentry']['superuser_creator_script']} &&
deactivate
EOH
end
file node['sentry']['superuser_creator_script'] do
action :delete
end
end
| 27.242775 | 111 | 0.662635 |
1cb1a6e9640c2e403cdeded47802a4851dfd8331 | 670 | # Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )
Rails.application.config.assets.precompile += %w( login.css )
Rails.application.config.assets.precompile += %w( login.js )
Rails.application.config.assets.precompile += %w( ckeditor/*) | 47.857143 | 93 | 0.767164 |
1cb7c044cfbf4888b0db5113da419333abf2c681 | 16,985 | module Sequel
module Plugins
# The many_through_many plugin allow you to create an association using multiple join tables.
# For example, assume the following associations:
#
# Artist.many_to_many :albums
# Album.many_to_many :tags
#
# The many_through_many plugin would allow this:
#
# Artist.plugin :many_through_many
# Artist.many_through_many :tags, [[:albums_artists, :artist_id, :album_id], [:albums_tags, :album_id, :tag_id]]
#
# Which will give you the tags for all of the artist's albums.
#
# Let's break down the 2nd argument of the many_through_many call:
#
# [[:albums_artists, :artist_id, :album_id],
# [:albums_tags, :album_id, :tag_id]]
#
# This argument is an array of arrays with three elements. Each entry in the main array represents a JOIN in SQL:
#
# first element :: represents the name of the table to join.
# second element :: represents the column used to join to the previous table.
# third element :: represents the column used to join to the next table.
#
# So the "Artist.many_through_many :tags" is translated into something similar to:
#
# FROM artists
# JOIN albums_artists ON (artists.id = albums_artists.artist_id)
# JOIN albums_tags ON (albums_artists.album_id = albums_tag.album_id)
# JOIN tags ON (albums_tags.tag_id = tags.id)
#
# The "artists.id" and "tags.id" criteria come from other association options (defaulting to the primary keys of the current and
# associated tables), but hopefully you can see how each argument in the array is used in the JOIN clauses. Note that you do
# not need to add an entry for the final table (tags in this example), as that comes from the associated class.
#
# Here are some more examples:
#
# # Same as Artist.many_to_many :albums
# Artist.many_through_many :albums, [[:albums_artists, :artist_id, :album_id]]
#
# # All artists that are associated to any album that this artist is associated to
# Artist.many_through_many :artists, [[:albums_artists, :artist_id, :album_id], [:albums_artists, :album_id, :artist_id]]
#
# # All albums by artists that are associated to any album that this artist is associated to
# Artist.many_through_many :artist_albums, [[:albums_artists, :artist_id, :album_id], \
# [:albums_artists, :album_id, :artist_id], [:albums_artists, :artist_id, :album_id]], \
# :class=>:Album
#
# # All tracks on albums by this artist (also could be a many_to_many)
# Artist.many_through_many :tracks, [[:albums_artists, :artist_id, :album_id]], \
# :right_primary_key=>:album_id
#
# Often you don't want the current object to appear in the array of associated objects. This is easiest to handle via an :after_load hook:
#
# Artist.many_through_many :artists, [[:albums_artists, :artist_id, :album_id], [:albums_artists, :album_id, :artist_id]],
# :after_load=>proc{|artist, associated_artists| associated_artists.delete(artist)}
#
# You can also handle it by adding a dataset block that excludes the current record (so it won't be retrieved at all), but
# that won't work when eagerly loading, which is why the :after_load proc is recommended instead.
#
# It's also common to not want duplicate records, in which case the :distinct option can be used:
#
# Artist.many_through_many :artists, [[:albums_artists, :artist_id, :album_id], [:albums, :id, :id], [:albums_artists, :album_id, :artist_id]],
# :distinct=>true
#
# In addition to many_through_many, this plugin also adds one_through_many, for an association to a single object through multiple join tables.
# This is useful if there are unique constraints on the foreign keys in the join tables that reference back to the current table, or if you want
# to set an order on the association and just want the first record.
#
# Usage:
#
# # Make all model subclasses support many_through_many associations
# Sequel::Model.plugin :many_through_many
#
# # Make the Album class support many_through_many associations
# Album.plugin :many_through_many
module ManyThroughMany
# The AssociationReflection subclass for many_through_many associations.
class ManyThroughManyAssociationReflection < Sequel::Model::Associations::ManyToManyAssociationReflection
Sequel::Model::Associations::ASSOCIATION_TYPES[:many_through_many] = self
# many_through_many and one_through_many associations can be clones
def cloneable?(ref)
ref[:type] == :many_through_many || ref[:type] == :one_through_many
end
# The default associated key alias(es) to use when eager loading
# associations via eager.
def default_associated_key_alias
self[:uses_left_composite_keys] ? (0...self[:through].first[:left].length).map{|i| :"x_foreign_key_#{i}_x"} : :x_foreign_key_x
end
%w'associated_key_table predicate_key edges final_edge final_reverse_edge reverse_edges'.each do |meth|
class_eval(<<-END, __FILE__, __LINE__+1)
def #{meth}
cached_fetch(:#{meth}){calculate_edges[:#{meth}]}
end
END
end
# The alias for the first join table.
def join_table_alias
final_reverse_edge[:alias]
end
# Many through many associations don't have a reciprocal
def reciprocal
nil
end
private
def _associated_dataset
ds = associated_class
(reverse_edges + [final_reverse_edge]).each do |t|
h = {:qualify=>:deep}
if t[:alias] != t[:table]
h[:table_alias] = t[:alias]
end
ds = ds.join(t[:table], Array(t[:left]).zip(Array(t[:right])), h)
end
ds
end
# Make sure to use unique table aliases when lazy loading or eager loading
def calculate_reverse_edge_aliases(reverse_edges)
aliases = [associated_class.table_name]
reverse_edges.each do |e|
table_alias = e[:table]
if aliases.include?(table_alias)
i = 0
table_alias = loop do
ta = :"#{table_alias}_#{i}"
break ta unless aliases.include?(ta)
i += 1
end
end
aliases.push(e[:alias] = table_alias)
end
end
# Transform the :through option into a list of edges and reverse edges to use to join tables when loading the association.
def calculate_edges
es = [{:left_table=>self[:model].table_name, :left_key=>self[:left_primary_key_column]}]
self[:through].each do |t|
es.last.merge!(:right_key=>t[:left], :right_table=>t[:table], :join_type=>t[:join_type]||self[:graph_join_type], :conditions=>(t[:conditions]||[]).to_a, :block=>t[:block])
es.last[:only_conditions] = t[:only_conditions] if t.include?(:only_conditions)
es << {:left_table=>t[:table], :left_key=>t[:right]}
end
es.last.merge!(:right_key=>right_primary_key, :right_table=>associated_class.table_name)
edges = es.map do |e|
h = {:table=>e[:right_table], :left=>e[:left_key], :right=>e[:right_key], :conditions=>e[:conditions], :join_type=>e[:join_type], :block=>e[:block]}
h[:only_conditions] = e[:only_conditions] if e.include?(:only_conditions)
h
end
reverse_edges = es.reverse.map{|e| {:table=>e[:left_table], :left=>e[:left_key], :right=>e[:right_key]}}
reverse_edges.pop
calculate_reverse_edge_aliases(reverse_edges)
final_reverse_edge = reverse_edges.pop
final_reverse_alias = final_reverse_edge[:alias]
h = {:final_edge=>edges.pop,
:final_reverse_edge=>final_reverse_edge,
:edges=>edges,
:reverse_edges=>reverse_edges,
:predicate_key=>qualify(final_reverse_alias, edges.first[:right]),
:associated_key_table=>final_reverse_edge[:alias],
}
h.each{|k, v| cached_set(k, v)}
h
end
def filter_by_associations_limit_key
fe = edges.first
Array(qualify(fe[:table], fe[:right])) + Array(qualify(associated_class.table_name, associated_class.primary_key))
end
end
class OneThroughManyAssociationReflection < ManyThroughManyAssociationReflection
Sequel::Model::Associations::ASSOCIATION_TYPES[:one_through_many] = self
include Sequel::Model::Associations::SingularAssociationReflection
end
module ClassMethods
# Create a many_through_many association. Arguments:
# name :: Same as associate, the name of the association.
# through :: The tables and keys to join between the current table and the associated table.
# Must be an array, with elements that are either 3 element arrays, or hashes with keys :table, :left, and :right.
# The required entries in the array/hash are:
# :table (first array element) :: The name of the table to join.
# :left (middle array element) :: The key joining the table to the previous table. Can use an
# array of symbols for a composite key association.
# :right (last array element) :: The key joining the table to the next table. Can use an
# array of symbols for a composite key association.
# If a hash is provided, the following keys are respected when using eager_graph:
# :block :: A proc to use as the block argument to join.
# :conditions :: Extra conditions to add to the JOIN ON clause. Must be a hash or array of two pairs.
# :join_type :: The join type to use for the join, defaults to :left_outer.
# :only_conditions :: Conditions to use for the join instead of the ones specified by the keys.
# opts :: The options for the associaion. Takes the same options as many_to_many.
def many_through_many(name, through, opts=OPTS, &block)
associate(:many_through_many, name, opts.merge(through.is_a?(Hash) ? through : {:through=>through}), &block)
end
# Creates a one_through_many association. See many_through_many for arguments.
def one_through_many(name, through, opts=OPTS, &block)
associate(:one_through_many, name, opts.merge(through.is_a?(Hash) ? through : {:through=>through}), &block)
end
private
# Create the association methods and :eager_loader and :eager_grapher procs.
def def_many_through_many(opts)
one_through_many = opts[:type] == :one_through_many
opts[:read_only] = true
opts[:after_load].unshift(:array_uniq!) if opts[:uniq]
opts[:cartesian_product_number] ||= one_through_many ? 0 : 2
opts[:through] = opts[:through].map do |e|
case e
when Array
raise(Error, "array elements of the through option/argument for many_through_many associations must have at least three elements") unless e.length == 3
{:table=>e[0], :left=>e[1], :right=>e[2]}
when Hash
raise(Error, "hash elements of the through option/argument for many_through_many associations must contain :table, :left, and :right keys") unless e[:table] && e[:left] && e[:right]
e
else
raise(Error, "the through option/argument for many_through_many associations must be an enumerable of arrays or hashes")
end
end
left_key = opts[:left_key] = opts[:through].first[:left]
opts[:left_keys] = Array(left_key)
opts[:uses_left_composite_keys] = left_key.is_a?(Array)
left_pk = (opts[:left_primary_key] ||= self.primary_key)
raise(Error, "no primary key specified for #{inspect}") unless left_pk
opts[:eager_loader_key] = left_pk unless opts.has_key?(:eager_loader_key)
opts[:left_primary_keys] = Array(left_pk)
lpkc = opts[:left_primary_key_column] ||= left_pk
lpkcs = opts[:left_primary_key_columns] ||= Array(lpkc)
opts[:dataset] ||= opts.association_dataset_proc
opts[:left_key_alias] ||= opts.default_associated_key_alias
opts[:eager_loader] ||= opts.method(:default_eager_loader)
join_type = opts[:graph_join_type]
select = opts[:graph_select]
graph_block = opts[:graph_block]
only_conditions = opts[:graph_only_conditions]
use_only_conditions = opts.include?(:graph_only_conditions)
conditions = opts[:graph_conditions]
opts[:eager_grapher] ||= proc do |eo|
ds = eo[:self]
iq = eo[:implicit_qualifier]
egls = eo[:limit_strategy]
if egls && egls != :ruby
associated_key_array = opts.associated_key_array
orig_egds = egds = eager_graph_dataset(opts, eo)
opts.reverse_edges.each{|t| egds = egds.join(t[:table], Array(t[:left]).zip(Array(t[:right])), :table_alias=>t[:alias], :qualify=>:deep)}
ft = opts.final_reverse_edge
egds = egds.join(ft[:table], Array(ft[:left]).zip(Array(ft[:right])), :table_alias=>ft[:alias], :qualify=>:deep).
select_all(egds.first_source).
select_append(*associated_key_array)
egds = opts.apply_eager_graph_limit_strategy(egls, egds)
ds.graph(egds, associated_key_array.map{|v| v.alias}.zip(Array(lpkcs)) + conditions, :qualify=>:deep, :table_alias=>eo[:table_alias], :implicit_qualifier=>iq, :join_type=>eo[:join_type]||join_type, :join_only=>eo[:join_only], :from_self_alias=>eo[:from_self_alias], :select=>select||orig_egds.columns, &graph_block)
else
opts.edges.each do |t|
ds = ds.graph(t[:table], t.fetch(:only_conditions, (Array(t[:right]).zip(Array(t[:left])) + t[:conditions])), :select=>false, :table_alias=>ds.unused_table_alias(t[:table]), :join_type=>eo[:join_type]||t[:join_type], :join_only=>eo[:join_only], :qualify=>:deep, :implicit_qualifier=>iq, :from_self_alias=>eo[:from_self_alias], &t[:block])
iq = nil
end
fe = opts.final_edge
ds.graph(opts.associated_class, use_only_conditions ? only_conditions : (Array(opts.right_primary_key).zip(Array(fe[:left])) + conditions), :select=>select, :table_alias=>eo[:table_alias], :qualify=>:deep, :join_type=>eo[:join_type]||join_type, :join_only=>eo[:join_only], &graph_block)
end
end
end
# Use def_many_through_many, since they share pretty much the same code.
def def_one_through_many(opts)
def_many_through_many(opts)
end
end
module DatasetMethods
private
# Use a subquery to filter rows to those related to the given associated object
def many_through_many_association_filter_expression(op, ref, obj)
lpks = ref[:left_primary_key_columns]
lpks = lpks.first if lpks.length == 1
lpks = ref.qualify(model.table_name, lpks)
edges = ref.edges
first, rest = edges.first, edges[1..-1]
ds = model.db[first[:table]].select(*Array(ref.qualify(first[:table], first[:right])))
rest.each{|e| ds = ds.join(e[:table], e.fetch(:only_conditions, (Array(e[:right]).zip(Array(e[:left])) + e[:conditions])), :table_alias=>ds.unused_table_alias(e[:table]), :qualify=>:deep, &e[:block])}
last_alias = if rest.empty?
first[:table]
else
last_join = ds.opts[:join].last
last_join.table_alias || last_join.table
end
meths = if obj.is_a?(Sequel::Dataset)
ref.qualify(obj.model.table_name, ref.right_primary_keys)
else
ref.right_primary_key_methods
end
expr = association_filter_key_expression(ref.qualify(last_alias, Array(ref.final_edge[:left])), meths, obj)
unless expr == SQL::Constants::FALSE
ds = ds.where(expr).exclude(SQL::BooleanExpression.from_value_pairs(ds.opts[:select].zip([]), :OR))
expr = SQL::BooleanExpression.from_value_pairs(lpks=>ds)
expr = add_association_filter_conditions(ref, obj, expr)
end
association_filter_handle_inversion(op, expr, Array(lpks))
end
alias one_through_many_association_filter_expression many_through_many_association_filter_expression
end
end
end
end
| 52.585139 | 354 | 0.637563 |
622b691723cabeedc9cf361dbd3773a2ab301b8d | 827 | class DeviseInvitableAddToUsers < ActiveRecord::Migration
def up
change_table :users do |t|
t.string :invitation_token
t.datetime :invitation_created_at
t.datetime :invitation_sent_at
t.datetime :invitation_accepted_at
t.integer :invitation_limit
t.references :invited_by, :polymorphic => true
t.index :invitation_token, :unique => true # for invitable
t.index :invited_by_id
end
# And allow null encrypted_password and password_salt:
change_column_null :users, :encrypted_password, true
end
def down
change_table :users do |t|
t.remove_references :invited_by, :polymorphic => true
t.remove :invitation_limit, :invitation_sent_at, :invitation_accepted_at, :invitation_token
end
end
end
| 33.08 | 98 | 0.683192 |
33f77f37c83e4ef6a3c449c59a1bb6804945c955 | 1,887 | module RequestSigning
module TestUtils
# Provides helpers for testing request signature verification integration
# Example:
# require 'rack/test'
# require 'request_signing'
# require 'request_signing/test_utils'
#
# class MyServerTest < Minitest::Test
# include Rack::Test::Methods
# include RequestSigning::TestUtils::Rack
#
# attr_reader :app
#
# def setup
# my_app = MyApp.new
# signer_key_store = RequestSigning::KeyStores::Static.new(
# "test_key" => "123qweasdzxc456rtyfghvbn789uiojk",
# "bad_test_key" => "11111111111111111111111111111111"
# )
# signer = RequestSigning::Signer.new(adapter: :rack, key_store: signer_key_store)
# @app = wrap_with_request_signer(app: my_app, signer: signer)
# end
#
# def test_lets_signed_requests_through
# signed(key_id: "test_key") { post "/v1/foo" }
# assert last_response.successful?
# end
#
# def test_rejects_requests_with_bad_signatures
# signed(key_id: "bad_test_key") { post "/v1/foo" }
# refute last_response.successful?
# end
#
module Rack
def wrap_with_request_signer(signer:, app:)
proc do |env|
if sign_params = env["request_signing.test.sign_params"]
env["HTTP_DATE"] ||= Time.now.httpdate
env["HTTP_SIGNATURE"] = signer.create_signature!(env, sign_params).to_s
end
app.call(env)
end
end
def signed(key_id:, algorithm: "hmac-sha256", headers: %w[(request-target) host date])
env "request_signing.test.sign_params", { key_id: key_id, algorithm: algorithm, headers: headers }
yield
ensure
env "request_signing.test.sign_params", nil
end
end
end
end
| 33.696429 | 106 | 0.611023 |
38793953f37ca0d5eba086c971ab3fdc1eaaf75e | 1,965 | AlohaTest::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress both stylesheets and JavaScripts
config.assets.js_compressor = :uglifier
config.assets.css_compressor = :scss
# Specifies the header that your server uses for sending files
# (comment out if your front-end server doesn't support this)
config.action_dispatch.x_sendfile_header = "X-Sendfile" # Use 'X-Accel-Redirect' for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
end
| 37.075472 | 104 | 0.76285 |
039ed3b27a7e950c8d7bb45293e382ca7564119c | 195 | require 'serverspec'
# Required by serverspec
set :backend, :exec
describe package('sysdig-dkms'), :if => os[:family] == 'debian' || os[:family] == 'ubuntu' do
it { should be_installed }
end
| 21.666667 | 93 | 0.671795 |
bf4bce81aa412c769db199946517f3a555c84c32 | 1,296 | # frozen_string_literal: true
$LOAD_PATH.push File.expand_path('lib', __dir__)
require 'doorkeeper/openid_connect/version'
Gem::Specification.new do |spec|
spec.name = 'doorkeeper-openid_connect'
spec.version = Doorkeeper::OpenidConnect::VERSION
spec.authors = ['Sam Dengler', 'Markus Koller']
spec.email = ['[email protected]', '[email protected]']
spec.homepage = 'https://github.com/doorkeeper-gem/doorkeeper-openid_connect'
spec.summary = 'OpenID Connect extension for Doorkeeper.'
spec.description = 'OpenID Connect extension for Doorkeeper.'
spec.license = 'MIT'
spec.files = Dir[
"{app,config,lib}/**/*",
"CHANGELOG.md",
"LICENSE.txt",
"README.md",
]
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.required_ruby_version = '>= 2.5'
spec.add_runtime_dependency 'doorkeeper', '>= 5.5', '< 5.6'
spec.add_runtime_dependency 'json-jwt', '>= 1.11.0'
spec.add_development_dependency 'conventional-changelog', '~> 1.2'
spec.add_development_dependency 'factory_bot'
spec.add_development_dependency 'pry-byebug'
spec.add_development_dependency 'rspec-rails'
spec.add_development_dependency 'sqlite3', '>= 1.3.6'
end
| 36 | 84 | 0.690586 |
91e757dc2ad4d6ef8cd018427f53667d50277edf | 1,667 | require_dependency 'spree/calculator'
module Spree
class Calculator::TieredPercent < Calculator
preference :base_percent, :decimal, default: 0
preference :tiers, :hash, default: {}
preference :currency, :string, default: -> { Spree::Config[:currency] }
before_validation do
# Convert tier values to decimals. Strings don't do us much good.
if preferred_tiers.is_a?(Hash)
self.preferred_tiers = preferred_tiers.map do |k, v|
[cast_to_d(k.to_s), cast_to_d(v.to_s)]
end.to_h
end
end
validates :preferred_base_percent, numericality: {
greater_than_or_equal_to: 0,
less_than_or_equal_to: 100
}
validate :preferred_tiers_content
def compute(object)
order = object.is_a?(Order) ? object : object.order
_base, percent = preferred_tiers.sort.reverse.detect do |b, _|
order.item_total >= b
end
if preferred_currency.casecmp(order.currency).zero?
(object.amount * (percent || preferred_base_percent) / 100).round(2)
else
0
end
end
private
def cast_to_d(value)
value.to_s.to_d
rescue ArgumentError
BigDecimal.new(0)
end
def preferred_tiers_content
if preferred_tiers.is_a? Hash
unless preferred_tiers.keys.all?{ |k| k.is_a?(Numeric) && k > 0 }
errors.add(:base, :keys_should_be_positive_number)
end
unless preferred_tiers.values.all?{ |k| k.is_a?(Numeric) && k >= 0 && k <= 100 }
errors.add(:base, :values_should_be_percent)
end
else
errors.add(:preferred_tiers, :should_be_hash)
end
end
end
end
| 27.783333 | 88 | 0.644871 |
e84b277907bf542ff02ab9641c50f0a0c1102834 | 4,047 | RAILS_ENV="test"
require 'test/unit'
require 'test/unit/ui/console/testrunner'
require "rubygems"
require "active_support"
ActiveSupport::Callbacks
require File.dirname(__FILE__) + "/../test_project/config/environment"
require File.dirname(__FILE__) + "/../lib/multidb_tester"
require 'spec'
require 'spec/rails'
require File.dirname(__FILE__) + "/../test_project/spec/models/something_spec"
#require "mocha"
#
#MultidbTester.enabled = false
#
#ActiveRecord::Base.establish_connection("test_multidb_sqlite3")
#ActiveRecord::Schema.define do
# create_table :somethings, :force => true do |t|
# t.string :name
# end
#end
#
#ActiveRecord::Base.establish_connection("test")
#ActiveRecord::Schema.define do
# create_table :somethings, :force => true do |t|
# t.string :name
# end
#end
#
#
#outstream = StringIO.new
#errstream = StringIO.new
#rspec_opts = Spec::Runner::Options.new(errstream, outstream)
#rspec_opts.examples_should_not_be_run
#rspec_runner = Spec::Runner.use(rspec_opts)
#
class QuietReporter < Spec::Runner::Reporter
def example_finished(example, error=nil)
@examples << example
end
end
class MultidbRspecTest < Test::Unit::TestCase
def setup
MultidbTester.enabled = true
@old_reporter = Spec::Runner.options.reporter
Spec::Runner.options.reporter = QuietReporter.new(Spec::Runner.options)
end
def teardown
# we don't want multidb extensions for THIS test file
Spec::Runner.options.reporter = @old_reporter
MultidbTester.enabled = false
end
def test_runs_test_once_for_each_db
SomethingCounter.counter = 0
assert run_spec(Spec::Rails::Example::ModelExampleGroup::Subclass_1, "should count")
assert_equal 2, SomethingCounter.counter
end
def test_fails_in_primary_db__only_runs_once
SomethingCounter.counter = 0
assert !run_spec(Spec::Rails::Example::ModelExampleGroup::Subclass_1, "should count both invalid")
assert_equal 1, SomethingCounter.counter
end
def test_both_databases_valid
SomethingCounter.counter = 0
assert run_spec(Spec::Rails::Example::ModelExampleGroup::Subclass_1, "should work")
assert_equal 2, SomethingCounter.counter
end
def test_fails_mysql_only
SomethingCounter.counter = 0
assert !run_spec(Spec::Rails::Example::ModelExampleGroup::Subclass_1, "should work only with mysql")
assert_equal 2, SomethingCounter.counter
end
def test_fails_sqlite_only
SomethingCounter.counter = 0
assert !run_spec(Spec::Rails::Example::ModelExampleGroup::Subclass_1, "should work only with sqlite")
assert_equal 1, SomethingCounter.counter
end
def test_description
MultidbTester.connection_spec_name = "bob"
assert_equal "[bob adapter]", Spec::Rails::Example::ModelExampleGroup::Subclass_1.description_parts.last
end
def test_fixtures
p Spec::Rails::Example::ModelExampleGroup::Subclass_1.send(:before_each_parts)
p Spec::Rails::Example::ModelExampleGroup::Subclass_1.superclass
p Spec::Rails::Example::ModelExampleGroup::Subclass_1.superclass.send(:before_each_parts)
p Spec::Rails::Example::ModelExampleGroup::Subclass_1.superclass.superclass
p Spec::Rails::Example::ModelExampleGroup::Subclass_1.superclass.superclass.send(:before_each_parts)
p Spec::Rails::Example::ModelExampleGroup::Subclass_1.superclass.superclass.superclass
p Spec::Rails::Example::ModelExampleGroup::Subclass_1.superclass.superclass.superclass.send(:before_each_parts)
assert run_spec(Spec::Rails::Example::ModelExampleGroup::Subclass_1, "should find fixtures")
end
def run_spec(spec_class, example_name)
# p Spec::Runner.options.examples
all_examples = spec_class.send(:examples_to_run)
examples = all_examples.select{|e| e.description == example_name}
spec_class.stubs(:examples_to_run).returns(examples)
success = nil
begin
success = spec_class.run
ensure
spec_class.stubs(:examples_to_run).returns(all_examples)
end
success
end
end
Spec::Runner.options.instance_variable_set(:@example_groups, [MultidbRspecTest])
| 32.902439 | 115 | 0.76427 |
1cad2178c531cc69f11e9aaa2b67dcc1831dfa37 | 483 | # 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::V2019_06_01
module Models
#
# Defines values for PrivateEndpointConnectionProvisioningState
#
module PrivateEndpointConnectionProvisioningState
Succeeded = "Succeeded"
Creating = "Creating"
Deleting = "Deleting"
Failed = "Failed"
end
end
end
| 25.421053 | 70 | 0.718427 |
08b00d07ac470188d25720d1eaaf167f3f766174 | 1,168 | # -*- encoding: utf-8 -*-
# stub: sawyer 0.7.0 ruby lib
Gem::Specification.new do |s|
s.name = "sawyer"
s.version = "0.7.0"
s.required_rubygems_version = Gem::Requirement.new(">= 1.3.5") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Rick Olson", "Wynn Netherland"]
s.date = "2016-02-06"
s.email = "[email protected]"
s.homepage = "https://github.com/lostisland/sawyer"
s.licenses = ["MIT"]
s.rubygems_version = "2.4.5.1"
s.summary = "Secret User Agent of HTTP"
s.installed_by_version = "2.4.5.1" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 2
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<faraday>, ["< 0.10", "~> 0.8"])
s.add_runtime_dependency(%q<addressable>, ["< 2.5", ">= 2.3.5"])
else
s.add_dependency(%q<faraday>, ["< 0.10", "~> 0.8"])
s.add_dependency(%q<addressable>, ["< 2.5", ">= 2.3.5"])
end
else
s.add_dependency(%q<faraday>, ["< 0.10", "~> 0.8"])
s.add_dependency(%q<addressable>, ["< 2.5", ">= 2.3.5"])
end
end
| 33.371429 | 109 | 0.620719 |
e9e953265522ccfaaa223a72af559997c40283a4 | 337 | json.array!(@tag_definitions) do |tag_definition|
json.extract! tag_definition, :id, :name, :description, :entity_type, :tag_type, :structure, :subjective, :unique, :tag_type_range_id, :tag_target, :virtual, :virtual_target, :dev_status, :dev_pertinence, :td_version_id
json.url tag_definition_url(tag_definition, format: :json)
end
| 67.4 | 221 | 0.780415 |
f8b2fbb16b68a8a9dfe7114fd6a08bef74761ba2 | 7,296 | module Sequel
module Plugins
# The validation_helpers plugin contains instance method equivalents for most of the legacy
# class-level validations. The names and APIs are different, though. Example:
#
# class Album < Sequel::Model
# plugin :validation_helpers
# def validate
# validates_min_length 1, :num_tracks
# end
# end
#
# The validates_unique validation has a unique API, but the other validations have
# the API explained here:
#
# Arguments:
# * atts - Single attribute symbol or an array of attribute symbols specifying the
# attribute(s) to validate.
# Options:
# * :allow_blank - Whether to skip the validation if the value is blank. You should
# make sure all objects respond to blank if you use this option, which you can do by
# requiring 'sequel/extensions/blank'
# * :allow_missing - Whether to skip the validation if the attribute isn't a key in the
# values hash. This is different from allow_nil, because Sequel only sends the attributes
# in the values when doing an insert or update. If the attribute is not present, Sequel
# doesn't specify it, so the database will use the table's default value. This is different
# from having an attribute in values with a value of nil, which Sequel will send as NULL.
# If your database table has a non NULL default, this may be a good option to use. You
# don't want to use allow_nil, because if the attribute is in values but has a value nil,
# Sequel will attempt to insert a NULL value into the database, instead of using the
# database's default.
# * :allow_nil - Whether to skip the validation if the value is nil.
# * :message - The message to use
module ValidationHelpers
module InstanceMethods
# Check that the attribute values are the given exact length.
def validates_exact_length(exact, atts, opts={})
validatable_attributes(atts, opts){|a,v,m| (m || "is not #{exact} characters") unless v && v.length == exact}
end
# Check the string representation of the attribute value(s) against the regular expression with.
def validates_format(with, atts, opts={})
validatable_attributes(atts, opts){|a,v,m| (m || 'is invalid') unless v.to_s =~ with}
end
# Check attribute value(s) is included in the given set.
def validates_includes(set, atts, opts={})
validatable_attributes(atts, opts){|a,v,m| (m || "is not in range or set: #{set.inspect}") unless set.include?(v)}
end
# Check attribute value(s) string representation is a valid integer.
def validates_integer(atts, opts={})
validatable_attributes(atts, opts) do |a,v,m|
begin
Kernel.Integer(v.to_s)
nil
rescue
m || 'is not a number'
end
end
end
# Check that the attribute values length is in the specified range.
def validates_length_range(range, atts, opts={})
validatable_attributes(atts, opts){|a,v,m| (m || "is outside the allowed range") unless v && range.include?(v.length)}
end
# Check that the attribute values are not longer than the given max length.
def validates_max_length(max, atts, opts={})
validatable_attributes(atts, opts){|a,v,m| (m || "is longer than #{max} characters") unless v && v.length <= max}
end
# Check that the attribute values are not shorter than the given min length.
def validates_min_length(min, atts, opts={})
validatable_attributes(atts, opts){|a,v,m| (m || "is shorter than #{min} characters") unless v && v.length >= min}
end
# Check that the attribute value(s) is not a string. This is generally useful
# in conjunction with raise_on_typecast_failure = false, where you are
# passing in string values for non-string attributes (such as numbers and dates).
# If typecasting fails (invalid number or date), the value of the attribute will
# be a string in an invalid format, and if typecasting succeeds, the value will
# not be a string.
def validates_not_string(atts, opts={})
validatable_attributes(atts, opts) do |a,v,m|
next unless v.is_a?(String)
next m if m
(sch = db_schema[a] and typ = sch[:type]) ? "is not a valid #{typ}" : "is a string"
end
end
# Check attribute value(s) string representation is a valid float.
def validates_numeric(atts, opts={})
validatable_attributes(atts, opts) do |a,v,m|
begin
Kernel.Float(v.to_s)
nil
rescue
m || 'is not a number'
end
end
end
# Check attribute value(s) is not considered blank by the database, but allow false values.
def validates_presence(atts, opts={})
validatable_attributes(atts, opts){|a,v,m| (m || "is not present") if model.db.send(:blank_object?, v) && v != false}
end
# Checks that there are no duplicate values in the database for the given
# attributes. Pass an array of fields instead of multiple
# fields to specify that the combination of fields must be unique,
# instead of that each field should have a unique value.
#
# This means that the code:
# validates_unique([:column1, :column2])
# validates the grouping of column1 and column2 while
# validates_unique(:column1, :column2)
# validates them separately.
#
# You should also add a unique index in the
# database, as this suffers from a fairly obvious race condition.
#
# This validation does not respect the :allow_* options that the other validations accept,
# since it can deals with multiple attributes at once.
#
# Possible Options:
# * :message - The message to use (default: 'is already taken')
def validates_unique(*atts)
message = (atts.pop[:message] if atts.last.is_a?(Hash)) || 'is already taken'
atts.each do |a|
ds = model.filter(Array(a).map{|x| [x, send(x)]})
errors.add(a, message) unless (new? ? ds : ds.exclude(pk_hash)).count == 0
end
end
private
# Skip validating any attribute that matches one of the allow_* options.
# Otherwise, yield the attribute, value, and passed option :message to
# the block. If the block returns anything except nil or false, add it as
# an error message for that attributes.
def validatable_attributes(atts, opts)
am, an, ab, m = opts.values_at(:allow_missing, :allow_nil, :allow_blank, :message)
Array(atts).each do |a|
next if am && !values.has_key?(a)
v = send(a)
next if an && v.nil?
next if ab && v.respond_to?(:blank?) && v.blank?
if message = yield(a, v, m)
errors.add(a, message)
end
end
end
end
end
end
end
| 46.177215 | 128 | 0.618284 |
7ac017501f1288958e49af4f1d4341fd8b2cb326 | 1,276 | # frozen_string_literal: true
class RegexpTest < Minitest::Test
def test_default
regexp = /abc/
assert_match regexp, 'abcde'
end
def test_braces
regexp = %r{abc}
assert_match regexp, 'abcde'
end
def test_braces_with_slashes
regexp = %r{a/b/c}
assert_match regexp, 'a/b/c/d/e'
end
def test_slashes
regexp = %r/abc/
assert_match regexp, 'abcde'
end
def test_brackets
regexp = %r[abc]
assert_match regexp, 'abcde'
end
def test_parens
regexp = %r(abc)
assert_match regexp, 'abcde'
end
def test_interpolation
inter = 'b'
regexp = /a#{inter}c/
assert_match regexp, 'abcde'
end
def test_modifier
regexp = /abc/i
assert_match regexp, 'ABCDE'
end
def test_brace_modifier
regexp = %r{abc}i
assert_match regexp, 'ABCDE'
end
def test_global_interpolation
'foo' =~ /foo/
regexp = /#$&/
assert_match regexp, 'foobar'
end
def test_float
float_pat = /\A
[[:digit:]]+ # 1 or more digits before the decimal point
(\. # Decimal point
[[:digit:]]+ # 1 or more digits after the decimal point
)? # The decimal point and following digits are optional
\Z/x
assert_match float_pat, "12.56"
end
end
| 16.571429 | 65 | 0.627743 |
f77f50ff198ca3abcdfdc0dc8ebee496ef694e12 | 355 | class FontAmaticSc < Formula
head "https://github.com/google/fonts/trunk/ofl/amaticsc", verified: "github.com/google/fonts/", using: :svn
desc "Amatic SC"
homepage "https://fonts.google.com/specimen/Amatic+SC"
def install
(share/"fonts").install "AmaticSC-Bold.ttf"
(share/"fonts").install "AmaticSC-Regular.ttf"
end
test do
end
end
| 29.583333 | 110 | 0.709859 |
33c4bf20c14ffd1f6b8419858ad5fdd2e7efc7b2 | 47 | module FidorApi
VERSION = '2.1.4'.freeze
end
| 11.75 | 26 | 0.702128 |
613aa255b9965181cfb121747e23c37eefa3f051 | 1,229 | # 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!
require "googleauth"
module Google
module Ads
module GoogleAds
module V4
module Services
module HotelPerformanceViewService
# Credentials for the HotelPerformanceViewService API.
class Credentials < ::Google::Auth::Credentials
self.env_vars = [
"GOOGLEADS_CREDENTIALS",
"GOOGLEADS_KEYFILE",
"GOOGLEADS_CREDENTIALS_JSON",
"GOOGLEADS_KEYFILE_JSON"
]
end
end
end
end
end
end
end
| 28.581395 | 74 | 0.664768 |
ab67b95214bd0bc6182437fbbff470f10af2f83d | 121 | class AddUserIdToEvents < ActiveRecord::Migration[4.2]
def change
add_column :events, :user_id, :integer
end
end
| 20.166667 | 54 | 0.743802 |
1c4ddb01e79f3977085c8292cef8a02951dc0bf7 | 1,600 | #!/usr/bin/env ruby
require 'retrospectives'
require_relative '../utils/load_jira_auth.rb'
include Retrospectives
(0..2).each do |index|
if(ARGV[index].to_s.empty?)
puts("Usage: ruby #{__FILE__} sprint_index time_start time_end. Example :")
abort("\nruby #{__FILE__} 1 20170216 20170228")
end
end
# this is index of sprint sheet in sprint plans sheet (index starts from are from 0)
SPRINT_INDEX = ARGV[0].to_i
jira_options = {
username: JiraAuth::USERNAME,
password: JiraAuth::PASSWORD,
site: JiraAuth::SITE
context_path: '',
auth_type: :basic
}
members = [{name: 'Gagan', username: 'gagandeep.singh', sheet_key: '1bitkGbG_o5XbmTFD385Yn61d6oM6p8vJcondhh1pFjM'},
{name: 'Neelakshi', username: 'Neelakshi', sheet_key: '1iYqA1irBBpktV3ssvxeZRuzkzAZ9RFqYcqI26kJUrSI'},
{name: 'Dinesh', username: 'DineshYadav', sheet_key: '1qwx--iJ14ZI9hUgumdixove9aeoQU-oZibKi80QLICQ'}]
{name: 'SwetaSharma', sheet_key: '1SyX2-62EQxSjvehcYMSknXM0HsPuoOv4_e-s2LBkbJU'}]
#
total_hours_spent_per_person = Hash.new(0)
retro = RetroSetup.new
retro.authenticate_google_drive(ENV['HOME'] + '/google_auth.json')
retro.authenticate_jira(jira_options)
retro.time_frame = "#{ARGV[1]} - #{ARGV[2]}"
retro.members = members
sheet = retro.get_sheet('1UCBgSJkOJvMBZfAqAtlyQWakxkCqZ7kLO1nTCFX-GYA', SPRINT_INDEX)
retro.get_tickets(sheet)
FetchHours.from_jira(retro)
retro.members.each do |member|
total_hours_spent_per_person[member.name] = member.hours_spent_jira.values.inject(:+)
end
total_hours_spent_per_person.each do |k, v|
v ||= 0
puts "Hours spent by #{k} on JIRA : #{v.round(2)}"
end
| 30.769231 | 115 | 0.7525 |
5d1213161c22260dd39fb7983ab68a2a66b657a3 | 1,435 | # cookies_api
#
# This file was automatically generated by APIMATIC v2.0
# ( https://apimatic.io ).
module CookiesApi
# Asset linked to a managed brand.
class BrandAsset < BaseModel
SKIP = Object.new
private_constant :SKIP
# Rasterized asset.
# @return [RasterGraphic]
attr_accessor :raster
# Vector asset, if available.
# @return [MediaItem]
attr_accessor :vector
# A mapping from model property names to API property names.
def self.names
@_hash = {} if @_hash.nil?
@_hash['raster'] = 'raster'
@_hash['vector'] = 'vector'
@_hash
end
# An array for optional fields
def optionals
%w[
raster
vector
]
end
# An array for nullable fields
def nullables
[]
end
def initialize(raster = nil,
vector = nil)
@raster = raster unless raster == SKIP
@vector = vector unless vector == SKIP
end
# Creates an instance of the object from a hash.
def self.from_hash(hash)
return nil unless hash
# Extract variables from the hash.
raster = RasterGraphic.from_hash(hash['raster']) if hash['raster']
vector = MediaItem.from_hash(hash['vector']) if hash['vector']
# Create object from extracted values.
BrandAsset.new(raster,
vector)
end
end
end
| 23.52459 | 73 | 0.58676 |
ff8c085367305813e5596d74d9b9b30e57a64524 | 912 | require 'test_helper'
class MicropostsControllerTest < ActionDispatch::IntegrationTest
def setup
@micropost = microposts(:orange)
@user = users(:bryan)
end
test "should redirect create when not logged in" do
assert_no_difference 'Micropost.count' do
post microposts_path, params: { micropost: { content: "Lorem ipsum" } }
end
assert_redirected_to login_url
end
test "should redirect destroy when not logged in" do
assert_no_difference 'Micropost.count' do
delete micropost_path(@micropost)
end
assert_redirected_to login_url
end
test "should redirect destroy for wrong micropost" do
post login_path, params:{session: {email:@user.email,password:'password',remember_me: '1'}}
micropost = microposts(:ants)
assert_no_difference 'Micropost.count' do
delete micropost_path(micropost)
end
assert_redirected_to root_url
end
end
| 28.5 | 95 | 0.733553 |
792925ce4e60284c612b63555ccf906d3fd56809 | 88 | # :NODOC:
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
| 17.6 | 44 | 0.772727 |
79862e607af4260aafc76dd79052e41b646a5a58 | 2,044 | # 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::MediaServices::Mgmt::V2018_07_01
module Models
#
# The class to specify one track property condition.
#
class FilterTrackPropertyCondition
include MsRestAzure
# @return [FilterTrackPropertyType] The track property type. Possible
# values include: 'Unknown', 'Type', 'Name', 'Language', 'FourCC',
# 'Bitrate'
attr_accessor :property
# @return [String] The track property value.
attr_accessor :value
# @return [FilterTrackPropertyCompareOperation] The track property
# condition operation. Possible values include: 'Equal', 'NotEqual'
attr_accessor :operation
#
# Mapper for FilterTrackPropertyCondition class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'FilterTrackPropertyCondition',
type: {
name: 'Composite',
class_name: 'FilterTrackPropertyCondition',
model_properties: {
property: {
client_side_validation: true,
required: true,
serialized_name: 'property',
type: {
name: 'String'
}
},
value: {
client_side_validation: true,
required: true,
serialized_name: 'value',
type: {
name: 'String'
}
},
operation: {
client_side_validation: true,
required: true,
serialized_name: 'operation',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 28.388889 | 75 | 0.537182 |
ab7223dd937c8f6b866a741e9450992b9421e5ab | 9,074 | class Payment < Ohm::Model
include ActiveModel::Conversion
include ActiveModel::Validations
extend ActiveModel::Naming
PAYMENT_TYPES = %w[
CASH
CHEQUE
POSTALORDER
]
PAYMENT_TYPES_FINANCE_BASIC = %w[
BANKTRANSFER
]
PAYMENT_TYPES_FINANCE_ADMIN = %w[
WORLDPAY_MISSED
]
PAYMENT_TYPES_NONVISIBLE = %w[
WORLDPAY
WRITEOFFSMALL
WRITEOFFLARGE
REFUND
REVERSAL
]
VALID_CURRENCY_POUNDS_REGEX = /\A[-]?([0]|[1-9]+[0-9]*)(\.[0-9]{1,2})?\z/ # This is an expression for formatting currency as pounds
VALID_CURRENCY_PENCE_REGEX = /\A[-]?[0-9]+\z/ # This is an expression for formatting currency as pence
REFUND_EXTENSION = '_REFUNDED'
attribute :orderKey
attribute :amount
attribute :currency
attribute :mac_code
attribute :dateReceived
attribute :dateEntered
attribute :dateReceived_year
attribute :dateReceived_month
attribute :dateReceived_day
attribute :registrationReference
attribute :worldPayPaymentStatus
attribute :updatedByUser
attribute :comment
attribute :paymentType
attribute :manualPayment
# These are meta data fields used only in rails for storing a temporary value to determine:
# the exception detail from the services
attribute :exception
validates :amount, presence: true, format: { with: VALID_CURRENCY_POUNDS_REGEX }, :if => :isManualPayment?
validates :amount, presence: true, format: { with: VALID_CURRENCY_PENCE_REGEX }, :if => :isAutomatedPayment?
validates :dateReceived, presence: true, length: { minimum: 8 }
validate :validate_dateReceived
validates :registrationReference, presence: true
# This concatanates all the PAYMENT_TYPE lists. Ideally the user role should be checked to determine which list the user was given.
validates :paymentType, presence: true, inclusion: { in: %w[].concat(PAYMENT_TYPES).concat(PAYMENT_TYPES_FINANCE_BASIC).concat(PAYMENT_TYPES_FINANCE_ADMIN).concat(PAYMENT_TYPES_NONVISIBLE), message: I18n.t('errors.messages.invalid_selection') }
validates :comment, length: { maximum: 250 }
# Creates a new Payment object from a payment-formatted hash
#
# @param payment_hash [Hash] the payment-formatted hash
# @return [Payment] the Ohm-derived Payment object.
def self.init (payment_hash)
payment = Payment.create
payment.update_attributes(payment_hash)
payment.save
payment
end
def self.find_by_registration(registration_uuid)
result = registrations = []
url = "#{Rails.configuration.waste_exemplar_services_url}/registrations/#{registration_uuid}/payments/new.json"
begin
response = RestClient.get url
if response.code == 200
result = JSON.parse(response.body) #result should be Hash
payment = Payment.init(result)
else
Rails.logger.error "Payment.find_by_registration for #{registration_uuid} failed with a #{response.code} response from server"
end
rescue => e
Airbrake.notify(e)
Rails.logger.error e.to_s
end
payment
end
def self.payment_type_options_for_select
PAYMENT_TYPES.collect {|d| [I18n.t('payment_types.'+d), d]}
end
def self.payment_type_financeBasic_options_for_select
PAYMENT_TYPES_FINANCE_BASIC.collect {|d| [I18n.t('payment_types.'+d), d]}
end
def self.payment_type_financeAdmin_options_for_select
PAYMENT_TYPES_FINANCE_ADMIN.collect {|d| [I18n.t('payment_types.'+d), d]}
end
# Represents the minimum balance needed for a finance basic user to make a write off
def self.basicMinimum
-500
end
# Represents the maximum balance needed for a finance basic user to make a write off
def self.basicMaximum
500
end
# Represents the maximum balance needed for a finance admin user to make a write off
def self.adminMaximum
10000000000
end
# Returns true if balance is in range for a small write off, otherwise returns an
# error message representing why it failed.
def self.isSmallWriteOff(balance)
Rails.logger.debug 'balance: ' + balance.to_s
if balance.to_f < Payment.basicMinimum
Rails.logger.debug 'Balance is paid or overpaid'
I18n.t('payment.newWriteOff.writeOffNotApplicable')
elsif balance.to_f > Payment.basicMaximum
Rails.logger.debug 'Balance is too great'
I18n.t('payment.newWriteOff.writeOffUnavailable')
elsif balance.to_f == 0.to_f
I18n.t('payment.newWriteOff.writeOffNotApplicable')
else
true
end
end
# Returns true if balance is in range for a large write off, otherwise returns an
# error message representing why it failed.
def self.isLargeWriteOff(balance)
Rails.logger.debug 'balance: ' + balance.to_s
if balance.to_f > Payment.adminMaximum
Rails.logger.debug 'Balance is too great for even a finance admin'
I18n.t('payment.newWriteOff.writeOffNotAvailable')
else
true
end
end
# Returns the payment from the registration matching the orderCode
def self.getPayment(registration, orderCode)
foundPayment = nil
registration.finance_details.first.payments.each do |payment|
Rails.logger.debug 'Payment getPayment '
if orderCode == payment.orderKey
Rails.logger.debug 'Payment getPayment foundPayment'
foundPayment = payment
end
end
foundPayment
end
def to_hash
self.attributes.to_hash
end
# returns a JSON Java/DropWizard API compatible representation of the Payment object
#
# @param none
# @return [String] the payment object in JSON form
def to_json
attributes.to_json
end
# POSTs payment to Java/Dropwizard service
#
# @param none
# @return [Boolean] true if Post is successful (200), false if not
def save!(registration_uuid)
raise ArgumentError, 'Registration uuid cannot be nil' unless registration_uuid
url = "#{Rails.configuration.waste_exemplar_services_url}/registrations/#{registration_uuid}/payments.json"
if isManualPayment?
multiplyAmount #pounds to pennies
end
commited = true
begin
response = RestClient.post url,
to_json,
:content_type => :json,
:accept => :json
result = JSON.parse(response.body)
save
Rails.logger.debug "Commited payment to service"
rescue => e
Airbrake.notify(e)
Rails.logger.error e.to_s
if e.try(:http_code)
if e.http_code == 422
# Get actual error from services
htmlDoc = Nokogiri::HTML(e.http_body)
messageFromServices = htmlDoc.at_css("body ul li").content
Rails.logger.error messageFromServices
# Update order with a exception message
self.exception = messageFromServices
elsif e.http_code == 400
# Get actual error from services
htmlDoc = Nokogiri::HTML(e.http_body)
messageFromServices = htmlDoc.at_css("body pre").content
Rails.logger.error messageFromServices
# Update order with a exception message
self.exception = messageFromServices
end
end
commited = false
end
if isManualPayment?
divideAmount #pennies to pounds
end
commited
end
def isManualPayment?
if !self.manualPayment.nil?
self.manualPayment
else
false
end
end
def isAutomatedPayment?
!isManualPayment?
end
def makeRefund
self.orderKey = self.orderKey + REFUND_EXTENSION
end
# Ensures if a reversal payment type is selected, then the amount entered is negated
def negateAmount
if self.paymentType == "REVERSAL"
if self.manualPayment
self.amount = -self.amount.to_f.abs
else
self.amount = -self.amount.to_i.abs
end
end
end
def isRefundableType?
refundable = false
PAYMENT_TYPES.each do |type|
if type == self.paymentType
refundable = true
end
end
PAYMENT_TYPES_FINANCE_BASIC.each do |type|
if type == self.paymentType
refundable = true
end
end
PAYMENT_TYPES_FINANCE_ADMIN.each do |type|
if type == self.paymentType
refundable = true
end
end
refundable
end
private
# This multiplies the amount up from pounds to pence
def multiplyAmount
self.amount = (Float(self.amount)*100).to_i
Rails.logger.debug 'multiplyAmount result:' + self.amount.to_s
end
# This divides the amount down from pence back to pounds
def divideAmount
self.amount = (Float(self.amount)/100).to_s
Rails.logger.debug 'divideAmount result:' + self.amount.to_s
end
# Converts the three data input fields from a manual payment into an overal date
def convert_dateReceived
begin
self.dateReceived = Date.civil(self.dateReceived_year.to_i, self.dateReceived_month.to_i, self.dateReceived_day.to_i)
rescue ArgumentError
false
end
end
def validate_dateReceived
if (!PAYMENT_TYPES_NONVISIBLE.include? paymentType)
errors.add(:dateReceived, I18n.t('errors.messages.invalid') ) unless convert_dateReceived
end
end
end
| 30.146179 | 246 | 0.705312 |
38cb80878a4f0d1dcb0a9d55a610354023075e36 | 2,363 | module Webcast
class Merged < UserSpecificModel
include Cache::CachedFeed
def initialize(uid, course_policy, term_yr, term_cd, ccn_list, options = {})
super(uid.nil? ? nil : uid.to_i, options)
@term_yr = term_yr.to_i unless term_yr.nil?
@term_cd = term_cd
@ccn_list = ccn_list
@options = options
@course_policy = course_policy
end
def get_feed_internal
logger.warn "Webcast merged feed where year=#{@term_yr}, term=#{@term_cd}, ccn_list=#{@ccn_list.to_s}, course_policy=#{@course_policy.to_s}"
@academics = MyAcademics::Teaching.new(@uid)
get_media_feed
end
private
def get_media_feed
media = get_media
if media.any?
media_hash = {
:media => media,
:videos => merge(media, :videos)
}
else
{}
end
end
def get_media
feed = []
if @term_yr && @term_cd
media_per_ccn = Webcast::CourseMedia.new(@term_yr, @term_cd, @ccn_list, @options).get_feed
if media_per_ccn.any?
courses = @academics.courses_list_from_ccns(@term_yr, @term_cd, media_per_ccn.keys)
courses.each do |course|
course[:classes].each do |next_class|
next_class[:sections].each do |section|
ccn = section[:ccn]
section_metadata = {
termYr: @term_yr,
termCd: @term_cd,
ccn: ccn,
deptName: next_class[:dept],
catalogId: next_class[:courseCatalog],
instructionFormat: section[:instruction_format],
sectionNumber: section[:section_number]
}
media = media_per_ccn[ccn.to_i]
feed << media.merge(section_metadata) if media
end
end
end
end
end
feed
end
def instance_key
if @term_yr && @term_cd
"#{Webcast::CourseMedia.id_per_ccn(@term_yr, @term_cd, @ccn_list.to_s)}/#{@uid}"
else
@uid
end
end
def merge(media_per_ccn, media_type)
all_recordings = Set.new
media_per_ccn.each do |section|
recordings = section[media_type]
recordings.each { |r| all_recordings << r } if recordings
end
all_recordings.to_a
end
end
end
| 28.817073 | 146 | 0.572154 |
e8dad9bb02136aacbb57103879765f8dfeb688b0 | 1,903 | class Telnet < Formula
desc "User interface to the TELNET protocol (built from macOS Sierra sources)"
homepage "https://opensource.apple.com/"
url "https://opensource.apple.com/tarballs/remote_cmds/remote_cmds-54.50.1.tar.gz"
sha256 "156ddec946c81af1cbbad5cc6e601135245f7300d134a239cda45ff5efd75930"
bottle do
cellar :any_skip_relocation
rebuild 1
sha256 "f68d8152cca7ae73a3c598d55d58083ef4795f1ace88794ea949baa21a75c975" => :high_sierra
sha256 "62d5a07da6030b6006f16572ad3b1d17aee0a09d03c8690ffaed964c6bd089ae" => :sierra
sha256 "13911a70794917c973d7cd56450f02ec376819542053a5954cb6264ca31c21f5" => :el_capitan
end
keg_only :provided_pre_high_sierra
depends_on :xcode => :build
conflicts_with "inetutils", :because => "both install 'telnet' binaries"
resource "libtelnet" do
url "https://opensource.apple.com/tarballs/libtelnet/libtelnet-13.tar.gz"
sha256 "e7d203083c2d9fa363da4cc4b7377d4a18f8a6f569b9bcf58f97255941a2ebd1"
end
def install
resource("libtelnet").stage do
ENV["SDKROOT"] = MacOS.sdk_path
ENV["MACOSX_DEPLOYMENT_TARGET"] = MacOS.version
xcodebuild "SYMROOT=build"
libtelnet_dst = buildpath/"telnet.tproj/build/Products"
libtelnet_dst.install "build/Release/libtelnet.a"
libtelnet_dst.install "build/Release/usr/local/include/libtelnet/"
end
system "make",
"-C", "telnet.tproj",
"OBJROOT=build/Intermediates",
"SYMROOT=build/Products",
"DSTROOT=build/Archive",
"CFLAGS=$(CC_Flags) -isystembuild/Products/",
"LDFLAGS=$(LD_Flags) -Lbuild/Products/",
"install"
bin.install "telnet.tproj/build/Archive/usr/bin/telnet"
man.install "telnet.tproj/build/Archive/usr/share/man/man1/"
end
test do
output = shell_output("#{bin}/telnet 94.142.241.111 666", 1)
assert_match "Connected to towel.blinkenlights.nl.", output
end
end
| 34.6 | 93 | 0.739359 |
bfcedfd0becbf22566ee01d045c132a14b9cdc3b | 3,394 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[7.0].define(version: 2022_03_21_210538) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "foods", force: :cascade do |t|
t.string "name"
t.string "measurement_unit"
t.decimal "price"
t.bigint "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_foods_on_user_id"
end
create_table "inventories", force: :cascade do |t|
t.string "name"
t.bigint "user_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_inventories_on_user_id"
end
create_table "inventory_foods", force: :cascade do |t|
t.integer "quantity"
t.bigint "inventory_id", null: false
t.bigint "food_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["food_id"], name: "index_inventory_foods_on_food_id"
t.index ["inventory_id"], name: "index_inventory_foods_on_inventory_id"
end
create_table "recipe_foods", force: :cascade do |t|
t.integer "quantity"
t.bigint "recipe_id", null: false
t.bigint "food_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["food_id"], name: "index_recipe_foods_on_food_id"
t.index ["recipe_id"], name: "index_recipe_foods_on_recipe_id"
end
create_table "recipes", force: :cascade do |t|
t.string "name"
t.integer "preparation_time"
t.integer "cooking_time"
t.text "description"
t.boolean "public"
t.bigint "user_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_recipes_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "foods", "users"
add_foreign_key "inventories", "users"
add_foreign_key "inventory_foods", "foods"
add_foreign_key "inventory_foods", "inventories"
add_foreign_key "recipe_foods", "foods"
add_foreign_key "recipe_foods", "recipes"
add_foreign_key "recipes", "users"
end
| 38.568182 | 95 | 0.721273 |
7a77ee5f0f3db1f322382ce046c4443bbee70f3a | 17,045 | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2020 the OpenProject GmbH
#
# 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-2017 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 docs/COPYRIGHT.rdoc for more details.
#++
require 'spec_helper'
describe 'Search', type: :feature, js: true, with_settings: { per_page_options: '5' }, with_mail: false do
include ::Components::NgSelectAutocompleteHelpers
using_shared_fixtures :admin
let(:user) { admin }
let(:project) { FactoryBot.create :project }
let(:searchable) { true }
let(:is_filter) { true }
let!(:work_packages) do
(1..12).map do |n|
Timecop.freeze("2016-11-21 #{n}:00".to_datetime) do
subject = "Subject No. #{n} WP"
FactoryBot.create :work_package,
subject: subject,
project: project
end
end
end
let(:custom_field_text_value) { 'cf text value' }
let!(:custom_field_text) do
FactoryBot.create(:text_wp_custom_field,
is_filter: is_filter,
searchable: searchable).tap do |custom_field|
project.work_package_custom_fields << custom_field
work_packages.first.type.custom_fields << custom_field
FactoryBot.create(:work_package_custom_value,
custom_field: custom_field,
customized: work_packages[0],
value: custom_field_text_value)
end
end
let(:custom_field_string_value) { 'cf string value' }
let!(:custom_field_string) do
FactoryBot.create(:string_wp_custom_field,
is_for_all: true,
is_filter: is_filter,
searchable: searchable).tap do |custom_field|
custom_field.save
work_packages.first.type.custom_fields << custom_field
FactoryBot.create(:work_package_custom_value,
custom_field: custom_field,
customized: work_packages[1],
value: custom_field_string_value)
end
end
let(:global_search) { ::Components::GlobalSearch.new }
let(:query) { 'Subject' }
let(:params) { [project, { q: query }] }
let(:run_visit) { true }
def expect_range(a, b)
(a..b).each do |n|
expect(page).to have_content("No. #{n} WP")
expect(page).to have_selector("a[href*='#{work_package_path(work_packages[n - 1].id)}']")
end
end
before do
project.reload
login_as user
visit search_path(*params) if run_visit
end
describe 'autocomplete' do
let!(:other_work_package) { FactoryBot.create(:work_package, subject: 'Other work package', project: project) }
it 'provides suggestions' do
global_search.search(query, submit: false)
# Suggestions shall show latest WPs first.
global_search.expect_work_package_option(work_packages[11])
# and show maximum 10 suggestions.
global_search.expect_work_package_option(work_packages[2])
global_search.expect_no_work_package_option(work_packages[1])
# and unrelated work packages shall not get suggested
global_search.expect_no_work_package_option(other_work_package)
target_work_package = work_packages.last
# If no direct match is available, the first option is marked
global_search.expect_in_project_and_subproject_scope_marked
# Expect redirection when WP is selected from results
global_search.search(target_work_package.subject, submit: false)
# Even though there is a work package named the same, we did not search by id
# and thus the work package is not selected.
global_search.expect_in_project_and_subproject_scope_marked
# But we can open it by clicking
global_search.click_work_package(target_work_package)
expect(page)
.to have_selector('.subject', text: target_work_package.subject)
expect(current_path).to eql project_work_package_path(target_work_package.project, target_work_package, state: 'activity')
first_wp = work_packages.first
# Typing a work package id shall find that work package
global_search.search(first_wp.id.to_s, submit: false)
# And it shall be marked as the direct hit.
global_search.expect_work_package_marked(first_wp)
# And the direct hit is opened when enter is pressed
global_search.submit_with_enter
expect(page)
.to have_selector('.subject', text: first_wp.subject)
expect(current_path).to eql project_work_package_path(first_wp.project, first_wp, state: 'activity')
# Typing a hash sign before an ID shall only suggest that work package and (no hits within the subject)
global_search.search("##{first_wp.id}", submit: false)
global_search.expect_work_package_marked(first_wp)
# Expect to have 3 project scope selecting menu entries
global_search.expect_scope('In this project β΅')
global_search.expect_scope('In this project + subprojects β΅')
global_search.expect_scope('In all projects β΅')
# Selection project scope 'In all projects' redirects away from current project.
global_search.submit_in_global_scope
expect(current_path).to match(/\/search/)
expect(current_url).to match(/\/search\?q=#{"%23#{first_wp.id}"}&work_packages=1&scope=all$/)
end
end
describe 'work package search' do
context 'search in all projects' do
let(:params) { [project, { q: query, work_packages: 1 }] }
context 'custom fields not searchable' do
let(:searchable) { false }
it "does not find WP via custom fields" do
select_autocomplete(page.find('.top-menu-search--input'),
query: "text",
select_text: "In all projects β΅")
table = Pages::EmbeddedWorkPackagesTable.new(find('.work-packages-embedded-view--container'))
table.ensure_work_package_not_listed!(work_packages[0])
table.ensure_work_package_not_listed!(work_packages[1])
end
end
context 'custom fields are no filters' do
let(:is_filter) { false }
it "does not find WP via custom fields" do
select_autocomplete(page.find('.top-menu-search--input'),
query: "text",
select_text: "In all projects β΅")
table = Pages::EmbeddedWorkPackagesTable.new(find('.work-packages-embedded-view--container'))
table.ensure_work_package_not_listed!(work_packages[0])
table.ensure_work_package_not_listed!(work_packages[1])
end
end
context 'custom fields searchable' do
it "finds WP global custom fields" do
select_autocomplete(page.find('.top-menu-search--input'),
query: "string",
select_text: "In all projects β΅")
table = Pages::EmbeddedWorkPackagesTable.new(find('.work-packages-embedded-view--container'))
table.ensure_work_package_not_listed!(work_packages[0])
table.expect_work_package_subject(work_packages[1].subject)
end
end
end
context 'project search' do
let(:subproject) { FactoryBot.create :project, parent: project }
let!(:other_work_package) do
FactoryBot.create(:work_package, subject: 'Other work package', project: subproject)
end
let(:filters) { ::Components::WorkPackages::Filters.new }
let(:columns) { ::Components::WorkPackages::Columns.new }
let(:top_menu) { ::Components::Projects::TopMenu.new }
it 'shows a work package table with correct results' do
# Search without subprojects
global_search.search query
global_search.submit_in_current_project
# Expect that the "All" tab is selected.
expect(page).to have_selector('[tab-id="all"].selected')
# Expect that the project scope is set to current_project and no module (this is the "all" tab) is requested.
expect(current_url).to match(/\/#{project.identifier}\/search\?q=#{query}&scope=current_project$/)
# Select "Work packages" tab
page.find('[tab-id="work_packages"]').click
# Expect that the project scope is set to current_project and the module "work_packages" is requested.
expect(current_url).to match(/\/search\?q=#{query}&work_packages=1&scope=current_project$/)
# Expect that the "Work packages" tab is selected.
expect(page).to have_selector('[tab-id="work_packages"].selected')
table = Pages::EmbeddedWorkPackagesTable.new(find('.work-packages-embedded-view--container'))
table.expect_work_package_count(5) # because we set the page size to this
# Expect order to be from newest to oldest.
table.expect_work_package_listed(*work_packages[7..12]) # This line ensures that the table is completely rendered.
table.expect_work_package_order(*work_packages[7..12].map { |wp| wp.id.to_s }.reverse)
# Expect that "Advanced filters" can refine the search:
filters.expect_closed
page.find('.advanced-filters--toggle').click
filters.expect_open
# As the project has a subproject, the filter for subprojectId is expected to be active.
filters.expect_filter_by 'subprojectId', 'none', nil, 'subprojectId'
filters.add_filter_by('Subject',
'contains',
[work_packages.last.subject],
'subject')
table.expect_work_package_listed(work_packages.last)
filters.remove_filter('subject')
page.find('#filter-by-text-input').set(work_packages[5].subject)
table.expect_work_package_subject(work_packages[5].subject)
table.ensure_work_package_not_listed!(work_packages.last)
# clearing the text filter and searching by a just a custom field works
page.find('#filter-by-text-input').set('')
filters.add_filter_by(custom_field_string.name,
'is',
[custom_field_string_value],
"customField#{custom_field_string.id}")
table.expect_work_package_subject(work_packages[1].subject)
# Expect that changing the advanced filters will not affect the global search input.
expect(global_search.input.value).to eq query
# Expect that a fresh global search will reset the advanced filters, i.e. that they are closed
global_search.search work_packages[6].subject, submit: true
expect(page).to have_text "Search for \"#{work_packages[6].subject}\" in #{project.name}"
table.ensure_work_package_not_listed!(work_packages[5])
table.expect_work_package_subject(work_packages[6].subject)
filters.expect_closed
# ...and that advanced filter shall have copied the global search input value.
page.find('.advanced-filters--toggle').click
filters.expect_open
# Expect that changing the search term without using the autocompleter will leave the project scope unchanged
# at current_project.
global_search.search other_work_package.subject, submit: true
expect(page).to have_text "Search for \"#{other_work_package.subject}\" in #{project.name}"
# and expect that subproject's work packages will not be found
table.ensure_work_package_not_listed! other_work_package
expect(current_url).to match(/\/#{project.identifier}\/search\?q=Other%20work%20package&work_packages=1&scope=current_project$/)
# Expect to find custom field values
# ...for type: text
global_search.search custom_field_text_value, submit: true
table.ensure_work_package_not_listed! work_packages[1]
table.expect_work_package_subject(work_packages[0].subject)
# ... for type: string
global_search.search custom_field_string_value, submit: true
table.ensure_work_package_not_listed! work_packages[0]
table.expect_work_package_subject(work_packages[1].subject)
# Change to project scope to include subprojects
global_search.search other_work_package.subject
global_search.submit_in_project_and_subproject_scope
# Expect that the "Work packages" tab is selected.
expect(page).to have_selector('[tab-id="work_packages"].selected')
expect(page).to have_text "Search for \"#{other_work_package.subject}\" in #{project.name} and all subprojects"
# Expect that the project scope is not set and work_packages module continues to stay selected.
expect(current_url).to match(/\/#{project.identifier}\/search\?q=Other%20work%20package&work_packages=1$/)
table = Pages::EmbeddedWorkPackagesTable.new(find('.work-packages-embedded-view--container'))
table.expect_work_package_count(1)
table.expect_work_package_subject(other_work_package.subject)
# Change project context to subproject
top_menu.toggle
top_menu.expect_open
top_menu.search_and_select subproject.name
top_menu.expect_current_project subproject.name
select_autocomplete(page.find('.top-menu-search--input'),
query: query,
select_text: 'In this project β΅')
filters.expect_closed
page.find('.advanced-filters--toggle').click
filters.expect_open
# As the current project (the subproject) has no subprojects, the filter for subprojectId is expected to be unavailable.
filters.expect_no_filter_by 'subprojectId', 'subprojectId'
end
end
end
describe 'pagination' do
context 'project wide search' do
it 'works' do
expect_range 3, 12
click_on 'Next', match: :first
expect_range 1, 2
expect(current_path).to match "/projects/#{project.identifier}/search"
click_on 'Previous', match: :first
expect_range 3, 12
expect(current_path).to match "/projects/#{project.identifier}/search"
end
end
context 'global "All" search' do
before do
login_as user
visit "/search?q=#{query}"
end
it 'works' do
expect_range 3, 12
click_on 'Next', match: :first
expect_range 1, 2
click_on 'Previous', match: :first
expect_range 3, 12
end
end
end
describe 'params escaping' do
let(:wp_1) { FactoryBot.create :work_package, subject: "Foo && Bar", project: project }
let(:wp_2) { FactoryBot.create :work_package, subject: "Foo # Bar", project: project }
let(:wp_3) { FactoryBot.create :work_package, subject: "Foo &# Bar", project: project }
let!(:work_packages) { [wp_1, wp_2, wp_3] }
let(:table) { Pages::EmbeddedWorkPackagesTable.new(find('.work-packages-embedded-view--container')) }
let(:run_visit) { false }
before do
visit home_path
end
it 'properly transmits parameters used in URL query' do
global_search.search "Foo &"
# Bug in ng-select causes highlights to break up entities
global_search.find_option "Foo && Bar"
global_search.find_option "Foo &# Bar"
global_search.expect_global_scope_marked
global_search.submit_in_global_scope
table.ensure_work_package_not_listed! wp_2
table.expect_work_package_listed(wp_1, wp_3)
global_search.search "# Bar"
global_search.find_option "Foo # Bar"
global_search.find_option "Foo &# Bar"
global_search.submit_in_global_scope
table.ensure_work_package_not_listed! wp_1
table.expect_work_package_listed(wp_2)
global_search.search "&"
# Bug in ng-select causes highlights to break up entities
global_search.find_option "Foo && Bar"
global_search.find_option "Foo &# Bar"
global_search.submit_in_global_scope
table.ensure_work_package_not_listed! wp_2
table.expect_work_package_listed(wp_1, wp_3)
end
end
end
| 40.583333 | 136 | 0.67621 |
5dd8ae73a01dbf4239bc575f7d0b9e47b7384b18 | 5,248 | require 'uri'
class Munin
DUMMY_MUNIN_URL = 'http://munin.example.com/'
DUMMY_GRAPH_PATH = '/assets/dummy-graph-for-development.png'
class Error < StandardError; end
attr_accessor :service
def initialize (service = nil)
@service = service
end
def dummy?
Rails.env.development? && (service && service.munin_url.blank?)
end
def activated?
dummy? || (service && service.munin_url.present?)
end
def root
raise Error, 'No service defined' if !dummy? && !service
raise Error, 'No munin_url defined' if !dummy? && !service.munin_url.present?
if dummy?
URI.parse(DUMMY_MUNIN_URL)
else
URI.parse(service.munin_url)
end
end
def service_url
url = root
url += URI.escape(service.name)
url
end
def url_for (args)
host = args[:host]
role = args[:role] || host.roles.first
self.service ||= find_service_that_has_munin_url_by(host)
url = root
path = [service, role, host].map { |p| URI.escape(p.name) }.join('/')
url += path
end
def graph_url_for (args)
if dummy?
URI.parse(DUMMY_GRAPH_PATH)
else
host = args[:host]
role = args[:role]
url = url_for(role: role, host: host)
options = { type: :load, span: :day}.merge(args[:options] || {})
path = [url.path, URI.escape("#{options[:type].to_s}-#{options[:span].to_s}.png")].join('/')
url += path
end
end
def find_service_that_has_munin_url_by (host)
found = nil
if service && service.munin_url.present?
found = service
else
host.services.each do |service|
if service.munin_url.present?
found = service
break
end
end
end
found
end
def categories
CATEGORIES
end
CATEGORIES = [
{
name: 'Disk',
sub_categories: [
{
name: 'Disk IOs per device',
type: 'diskstats_iops'
},
{
name: 'Disk latency per device',
type: 'diskstats_latency',
},
{
name: 'Disk throughput per device',
type: 'diskstats_throughput',
},
{
name: 'Disk usage in percent',
type: 'df',
},
{
name: 'Disk utilization per device',
type: 'diskstats_utilization',
},
{
name: 'Filesystem usage (in bytes)',
type: 'df_abs',
},
{
name: 'Inode usage in percent',
type: 'df_inode',
},
{
name: 'IO Service time',
type: 'iostat_ios',
},
{
name: 'IOstat',
type: 'iostat',
},
],
},
{
name: 'Network',
sub_categories: [
{
name: 'eth0 errors',
type: 'if_err_eth0',
},
{
name: 'eth0 traffic',
type: 'if_eth0',
},
{
name: 'Firewall Throughput',
type: 'fw_packets',
},
{
name: 'HTTP loadtime of a page',
type: 'http_loadtime',
},
{
name: 'Netstat',
type: 'netstat',
},
],
},
{
name: 'Processes',
sub_categories: [
{
name: 'Fork rate',
type: 'forks',
},
{
name: 'Number of threads',
type: 'threads',
},
{
name: 'Processes',
type: 'processes',
},
{
name: 'Processes priority',
type: 'proc_pri',
},
{
name: 'VMstat',
type: 'vmstat',
},
],
},
{
name: 'System',
sub_categories: [
{
name: 'Available entropy',
type: 'entropy',
},
{
name: 'CPU usage',
type: 'cpu',
},
{
name: 'Extended memory usage',
type: 'memory_ext',
},
{
name: 'File table usage',
type: 'open_files',
},
{
name: 'Individual interrupts',
type: 'irqstats',
},
{
name: 'Inode table usage',
type: 'open_inodes',
},
{
name: 'Interrupts and context switches',
type: 'interrupts',
},
{
name: 'Load average',
type: 'load',
},
{
name: 'Logged in users',
type: 'users',
},
{
name: 'Memory usage',
type: 'memory',
},
{
name: 'Swap in/out',
type: 'swap',
},
{
name: 'Uptime',
type: 'uptime',
},
]
},
{
name: 'time',
sub_categories: [
{
name: 'NTP kernel PLL estimated error (secs)',
type: 'ntp_kernel_err',
},
{
name: 'NTP kernel PLL frequency (ppm + 0)',
type: 'ntp_kernel_pll_freq',
},
{
name: 'NTP kernel PLL offset (secs)',
type: 'ntp_kernel_pll_off',
},
{
name: 'NTP timing statistics for system peer',
type: 'ntp_offset',
}
],
},
]
end
| 20.743083 | 98 | 0.457317 |
f76d1de7ee7c5ded520ce09a92cf987b5988f65f | 641 | cask 'autopano-pro' do
version '4.2.3'
sha256 '07fb35d00fa7f8926e00ede0031ef1c56a6e0e89d1f3d7485b4fa00da765fb99'
url 'http://download.kolor.com/app/stable/macleopard'
name 'Autopano Pro'
homepage 'http://www.kolor.com/panorama-software-autopano-pro.html'
pkg "Autopano Pro #{version.major_minor}.pkg"
uninstall pkgutil: [
'com.kolor.pkg.AutopanoPro.*',
'com.kolor.pkg.Aperture_plugin',
'com.kolor.pkg.Bridge_plugin',
'com.kolor.pkg.Lightroom_plugin',
'com.kolor.pkg.plugin.picasa',
]
end
| 33.736842 | 75 | 0.599064 |
7aa7d861edfc603092078a127596cedf203ade65 | 88 | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'app_market_scraper'
| 29.333333 | 58 | 0.761364 |
916a55a5bccd9c7a63bfd5baed3077f85948fa90 | 222 | project_path = File.dirname(__FILE__)
http_path = '/'
output_style = :compressed
sass_dir = 'content/style'
css_dir = 'output/style'
images_dir = 'content/static/images'
sass_options = {
:syntax => :scss
}
| 22.2 | 38 | 0.68018 |
1d5654a65cfa56de36b4e8533c1b7accbb6440bf | 3,976 | # encoding: utf-8
require 'set'
require 'forwardable'
require 'adamantium'
require 'equalizer'
require 'abstract_type'
require 'concord'
require 'lupo'
# Substation can be thought of as a domain level request router. It assumes
# that every usecase in your application has a name and is implemented in a
# dedicated class that will be referred to as an *action* in the context of
# substation. The only protocol such actions must support is `#call(request)`.
#
# The contract for actions specifies that when invoked, actions can
# receive arbitrary input data which will be available in `request.input`.
# Additionally, `request.env` contains an arbitrary object that
# represents your application environment and will typically provide access
# to useful things like a logger or a storage engine abstraction.
#
# The contract further specifies that every action must return an instance
# of either `Substation::Response::Success` or `Substation::Response::Failure`.
# Again, arbitrary data can be associated with any kind of response, and will
# be available in `response.data`. In addition to that, `response.success?` is
# available and will indicate wether invoking the action was successful or not.
#
# `Substation::Dispatcher` stores a mapping of action names to the actual
# objects implementing the action. Clients can use
# `Substation::Dispatcher#call(name, input, env)` to dispatch to any
# registered action. For example, a web application could map an http
# route to a specific action name and pass relevant http params on to the
# action.
module Substation
# Represent an undefined argument
Undefined = Object.new.freeze
# An empty frozen array useful for (default) parameters
EMPTY_ARRAY = [].freeze
# An empty frozen hash useful for (default) parameters
EMPTY_HASH = {}.freeze
# Base class for substation errors
class Error < StandardError
def self.msg(object)
self::MSG % object.inspect
end
def initialize(object)
super(self.class.msg(object))
end
end # Error
# Error raised when trying to access an unknown processor
class UnknownProcessor < Error
MSG = 'No processor named %s is registered'.freeze
end # UnknownProcessor
# Raised when trying to dispatch to an unregistered action
class UnknownActionError < Error
MSG = 'No action named %s is registered'.freeze
end # UnknownActionError
# Raised when an object is already registered under the a given name
class AlreadyRegisteredError < Error
MSG = '%s is already registered'.freeze
end # AlreadyRegisteredError
# Raised when a reserved method is being given
class ReservedNameError < Error
MSG = '%s is a reserved name'.freeze
end # ReservedNameError
# Raised when a duplicate {Processor} should be registered within a {Chain}
class DuplicateProcessorError < Error
MSG = 'The following processors already exist within this chain: %s'.freeze
end # DuplicateProcessorError
end # Substation
require 'substation/request'
require 'substation/response'
require 'substation/response/api'
require 'substation/response/success'
require 'substation/response/failure'
require 'substation/response/exception'
require 'substation/response/exception/output'
require 'substation/processor'
require 'substation/processor/builder'
require 'substation/processor/config'
require 'substation/processor/executor'
require 'substation/processor/evaluator'
require 'substation/processor/evaluator/result'
require 'substation/processor/evaluator/handler'
require 'substation/processor/transformer'
require 'substation/processor/wrapper'
require 'substation/processor/nest'
require 'substation/dsl/guard'
require 'substation/dsl/registry'
require 'substation/chain/definition'
require 'substation/chain'
require 'substation/chain/dsl'
require 'substation/chain/dsl/config'
require 'substation/chain/dsl/module_builder'
require 'substation/environment'
require 'substation/environment/dsl'
require 'substation/dispatcher'
| 35.81982 | 79 | 0.777666 |
f7b99ddbfd2c272d83be0bc5c6317daa6d219c28 | 8,950 | class Assay < ApplicationRecord
include Seek::Rdf::RdfGeneration
include Seek::Ontologies::AssayOntologyTypes
include Seek::Taggable
include Seek::ProjectHierarchies::ItemsProjectsExtension if Seek::Config.project_hierarchy_enabled
# needs to before acts_as_isa - otherwise auto_index=>false is overridden by Seek::Search::CommonFields
if Seek::Config.solr_enabled
searchable(auto_index: false) do
text :organism_terms, :human_disease_terms, :assay_type_label, :technology_type_label
text :strains do
strains.compact.map(&:title)
end
end
end
# needs to be declared before acts_as_isa, else ProjectAssociation module gets pulled in
belongs_to :study
has_many :projects, through: :study
has_filter :project
acts_as_isa
acts_as_snapshottable
belongs_to :institution
belongs_to :assay_class
has_many :assay_organisms, dependent: :destroy, inverse_of: :assay
has_many :organisms, through: :assay_organisms, inverse_of: :assays
has_many :assay_human_diseases, dependent: :destroy, inverse_of: :assay
has_many :human_diseases, through: :assay_human_diseases, inverse_of: :assays
has_filter :organism
has_filter :human_disease
has_many :strains, through: :assay_organisms
has_many :tissue_and_cell_types, through: :assay_organisms
before_save { assay_assets.each(&:set_version) }
has_many :assay_assets, dependent: :destroy, inverse_of: :assay, autosave: true
has_many :data_files, through: :assay_assets, source: :asset, source_type: 'DataFile', inverse_of: :assays
has_many :sops, through: :assay_assets, source: :asset, source_type: 'Sop', inverse_of: :assays
has_many :models, through: :assay_assets, source: :asset, source_type: 'Model', inverse_of: :assays
has_many :samples, through: :assay_assets, source: :asset, source_type: 'Sample', inverse_of: :assays
has_many :documents, through: :assay_assets, source: :asset, source_type: 'Document', inverse_of: :assays
has_one :investigation, through: :study
has_one :external_asset, as: :seek_entity, dependent: :destroy
validates :assay_type_uri, presence:true
validates_with AssayTypeUriValidator
validates :technology_type_uri, absence:true, if: :is_modelling?
validates_with TechnologyTypeUriValidator
validates_presence_of :contributor
validates_presence_of :assay_class
validates :study, presence: { message: ' must be selected and valid' }, projects: true
before_validation :default_assay_and_technology_type
# a temporary store of added assets - see AssayReindexer
attr_reader :pending_related_assets
has_filter :assay_class, :assay_type, :technology_type
enforce_authorization_on_association :study, :view
def default_contributor
User.current_user.try :person
end
def short_description
type = assay_type_label.nil? ? 'No type' : assay_type_label
"#{title} (#{type})"
end
def state_allows_delete?(*args)
assets.empty? && publications.empty? && super
end
# returns true if this is a modelling class of assay
def is_modelling?
assay_class && assay_class.is_modelling?
end
# returns true if this is an experimental class of assay
def is_experimental?
!assay_class.nil? && assay_class.key == 'EXP'
end
# Create or update relationship of this assay to another, with a specific relationship type and version
def associate(asset, options = {})
if asset.is_a?(Organism)
associate_organism(asset)
elsif asset.is_a?(HumanDisease)
associate_human_disease(asset)
else
assay_asset = assay_assets.detect { |aa| aa.asset == asset }
if assay_asset.nil?
assay_asset = assay_assets.build
end
assay_asset.asset = asset
assay_asset.version = asset.version if asset && asset.respond_to?(:version)
r_type = options.delete(:relationship)
assay_asset.relationship_type = r_type unless r_type.nil?
direction = options.delete(:direction)
assay_asset.direction = direction unless direction.nil?
assay_asset.save if assay_asset.changed?
@pending_related_assets ||= []
@pending_related_assets << asset
assay_asset
end
end
def self.simple_associated_asset_types
[:models, :sops, :publications, :documents]
end
# Associations where there is additional metadata on the association, i.e. `direction`
def self.complex_associated_asset_types
[:data_files, :samples]
end
def assets
(self.class.complex_associated_asset_types + self.class.simple_associated_asset_types).inject([]) do |assets, type|
assets + send(type)
end
end
def incoming
assay_assets.incoming.collect(&:asset)
end
def outgoing
assay_assets.outgoing.collect(&:asset)
end
def validation_assets
assay_assets.validation.collect(&:asset)
end
def construction_assets
assay_assets.construction.collect(&:asset)
end
def simulation_assets
assay_assets.simulation.collect(&:asset)
end
def avatar_key
type = is_modelling? ? 'modelling' : 'experimental'
"assay_#{type}_avatar"
end
def clone_with_associations
new_object = dup
new_object.policy = policy.deep_copy
new_object.assay_assets = assay_assets.select { |aa| self.class.complex_associated_asset_types.include?(aa.asset_type.underscore.pluralize.to_sym) }.map(&:dup)
self.class.simple_associated_asset_types.each do |type|
new_object.send("#{type}=", try(type))
end
new_object.assay_organisms = try(:assay_organisms)
new_object.assay_human_diseases = try(:assay_human_diseases)
new_object
end
def organism_terms
organisms.collect(&:searchable_terms).flatten
end
def human_disease_terms
human_diseases.collect(&:searchable_terms).flatten
end
def self.user_creatable?
Seek::Config.assays_enabled
end
# Associates and organism with the assay
# organism may be either an ID or Organism instance
# strain_id should be the id of the strain
# culture_growth should be the culture growth instance
def associate_organism(organism, strain_id = nil, culture_growth_type = nil, tissue_and_cell_type_id = nil, tissue_and_cell_type_title = nil)
organism = Organism.find(organism) if organism.is_a?(Numeric) || organism.is_a?(String)
strain = organism.strains.find_by_id(strain_id)
tissue_and_cell_type = nil
if tissue_and_cell_type_id.present?
tissue_and_cell_type = TissueAndCellType.find_by_id(tissue_and_cell_type_id)
elsif tissue_and_cell_type_title.present?
tissue_and_cell_type = TissueAndCellType.where(title: tissue_and_cell_type_title).first_or_create!
end
unless AssayOrganism.exists_for?(self, organism, strain, culture_growth_type, tissue_and_cell_type)
assay_organism = AssayOrganism.new(assay: self, organism: organism, culture_growth_type: culture_growth_type,
strain: strain, tissue_and_cell_type: tissue_and_cell_type)
assay_organisms << assay_organism
end
end
# Associates a human disease with the assay
# human disease may be either an ID or HumanDisease instance
def associate_human_disease(human_disease)
human_disease = HumanDisease.find(human_disease) if human_disease.is_a?(Numeric) || human_disease.is_a?(String)
assay_human_disease = AssayHumanDisease.new(assay: self, human_disease: human_disease)
unless AssayHumanDisease.exists_for?(human_disease, self)
assay_human_diseases << assay_human_disease
end
end
# overides that from Seek::RDF::RdfGeneration, as Assay entity depends upon the AssayClass (modelling, or experimental) of the Assay
def rdf_type_entity_fragment
{ 'EXP' => 'Experimental_assay', 'MODEL' => 'Modelling_analysis' }[assay_class.key]
end
def external_asset_search_terms
external_asset ? external_asset.search_terms : []
end
def samples_attributes= attributes
set_assay_assets_for('Sample', attributes)
end
def data_files_attributes= attributes
set_assay_assets_for('DataFile', attributes)
end
def self.filter_by_projects(projects)
joins(:projects).where(studies: { investigations: { investigations_projects: { project_id: projects } } })
end
private
def set_assay_assets_for(type, attributes)
type_assay_assets, other_assay_assets = self.assay_assets.partition { |aa| aa.asset_type == type }
new_type_assay_assets = []
attributes.each do |attrs|
attrs.merge!(asset_type: type)
existing = type_assay_assets.detect { |aa| aa.asset_id.to_s == attrs['asset_id'] }
if existing
new_type_assay_assets << existing.tap { |e| e.assign_attributes(attrs) }
else
aa = self.assay_assets.build(attrs)
if aa.asset && aa.asset.can_view?
new_type_assay_assets << aa
end
end
end
self.assay_assets = (other_assay_assets + new_type_assay_assets)
self.assay_assets
end
def related_publication_ids
publication_ids
end
end
| 33.773585 | 163 | 0.745698 |
262566f81de4bd5b346d8037c71fc4d4b5c12ea8 | 99 | # desc "Explaining what the task does"
# task :sgas_rails_middleware do
# # Task goes here
# end
| 19.8 | 38 | 0.717172 |
7ac604427d2cb24e265d3ac896125654d666a480 | 2,269 | module Elasticsearch
module Persistence
module Repository
# The default repository class, to be used either directly, or as a gateway in a custom repository class
#
# @example Standalone use
#
# repository = Elasticsearch::Persistence::Repository::Class.new
# # => #<Elasticsearch::Persistence::Repository::Class ...>
# repository.save(my_object)
# # => {"_index"=> ... }
#
# @example Shortcut use
#
# repository = Elasticsearch::Persistence::Repository.new
# # => #<Elasticsearch::Persistence::Repository::Class ...>
#
# @example Configuration via a block
#
# repository = Elasticsearch::Persistence::Repository.new do
# index 'my_notes'
# end
#
# # => #<Elasticsearch::Persistence::Repository::Class ...>
# # > repository.save(my_object)
# # => {"_index"=> ... }
#
# @example Accessing the gateway in a custom class
#
# class MyRepository
# include Elasticsearch::Persistence::Repository
# end
#
# repository = MyRepository.new
#
# repository.gateway.client.info
# # => {"status"=>200, "name"=>"Venom", ... }
#
class Class
include Elasticsearch::Persistence::Client::ClassMethods
include Elasticsearch::Persistence::Repository::Naming
include Elasticsearch::Persistence::Repository::Serialize
include Elasticsearch::Persistence::Repository::Store
include Elasticsearch::Persistence::Repository::Find
include Elasticsearch::Persistence::Repository::Search
include Elasticsearch::Model::Indexing::ClassMethods
attr_reader :options
def initialize(options={}, &block)
@options = options
index_name options.delete(:index)
block.arity < 1 ? instance_eval(&block) : block.call(self) if block_given?
end
# Return the "host" class, if this repository is a gateway hosted in another class
#
# @return [nil, Class]
#
# @api private
#
def host
options[:host]
end
end
end
end
end
| 31.513889 | 110 | 0.57955 |
6af0cfee54a291f8b4124d95b25771b4a80f7300 | 41 | module SimpleView
VERSION = "0.6.5"
end | 13.666667 | 19 | 0.707317 |
62c3742952ca8ac6cd2e8f542dbcb373e4935120 | 5,765 | require 'rails_helper'
RSpec.describe '/api/v1/widget/messages', type: :request do
let(:account) { create(:account) }
let(:web_widget) { create(:channel_widget, account: account) }
let(:contact) { create(:contact, account: account, email: nil) }
let(:contact_inbox) { create(:contact_inbox, contact: contact, inbox: web_widget.inbox) }
let(:conversation) { create(:conversation, contact: contact, account: account, inbox: web_widget.inbox, contact_inbox: contact_inbox) }
let(:payload) { { source_id: contact_inbox.source_id, inbox_id: web_widget.inbox.id } }
let(:token) { ::Widget::TokenService.new(payload: payload).generate_token }
before do
2.times.each { create(:message, account: account, inbox: web_widget.inbox, conversation: conversation) }
end
describe 'GET /api/v1/widget/messages' do
context 'when get request is made' do
it 'returns messages in conversation' do
get api_v1_widget_messages_url,
params: { website_token: web_widget.website_token },
headers: { 'X-Auth-Token' => token },
as: :json
expect(response).to have_http_status(:success)
json_response = JSON.parse(response.body)
# 2 messages created + 3 messages by the template hook
expect(json_response.length).to eq(5)
end
end
end
describe 'POST /api/v1/widget/messages' do
context 'when post request is made' do
it 'creates message in conversation' do
conversation.destroy # Test all params
message_params = { content: 'hello world', timestamp: Time.current }
post api_v1_widget_messages_url,
params: { website_token: web_widget.website_token, message: message_params },
headers: { 'X-Auth-Token' => token },
as: :json
expect(response).to have_http_status(:success)
json_response = JSON.parse(response.body)
expect(json_response['content']).to eq(message_params[:content])
end
it 'creates attachment message in conversation' do
file = fixture_file_upload(Rails.root.join('spec/assets/avatar.png'), 'image/png')
message_params = { content: 'hello world', timestamp: Time.current, attachments: [file] }
post api_v1_widget_messages_url,
params: { website_token: web_widget.website_token, message: message_params },
headers: { 'X-Auth-Token' => token }
expect(response).to have_http_status(:success)
json_response = JSON.parse(response.body)
expect(json_response['content']).to eq(message_params[:content])
expect(conversation.messages.last.attachments.first.file.present?).to eq(true)
expect(conversation.messages.last.attachments.first.file_type).to eq('image')
end
end
end
describe 'PUT /api/v1/widget/messages' do
context 'when put request is made with non existing email' do
it 'updates message in conversation and creates a new contact' do
message = create(:message, content_type: 'input_email', account: account, inbox: web_widget.inbox, conversation: conversation)
email = Faker::Internet.email
contact_params = { email: email }
put api_v1_widget_message_url(message.id),
params: { website_token: web_widget.website_token, contact: contact_params },
headers: { 'X-Auth-Token' => token },
as: :json
expect(response).to have_http_status(:success)
message.reload
expect(message.submitted_email).to eq(email)
expect(message.conversation.contact.email).to eq(email)
end
end
context 'when put request is made with invalid email' do
it 'rescues the error' do
message = create(:message, account: account, content_type: 'input_email', inbox: web_widget.inbox, conversation: conversation)
contact_params = { email: nil }
put api_v1_widget_message_url(message.id),
params: { website_token: web_widget.website_token, contact: contact_params },
headers: { 'X-Auth-Token' => token },
as: :json
expect(response).to have_http_status(:internal_server_error)
end
end
context 'when put request is made with existing email' do
it 'updates message in conversation and deletes the current contact' do
message = create(:message, account: account, content_type: 'input_email', inbox: web_widget.inbox, conversation: conversation)
email = Faker::Internet.email
create(:contact, account: account, email: email)
contact_params = { email: email }
put api_v1_widget_message_url(message.id),
params: { website_token: web_widget.website_token, contact: contact_params },
headers: { 'X-Auth-Token' => token },
as: :json
expect(response).to have_http_status(:success)
message.reload
expect { contact.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
it 'ignores the casing of email, updates message in conversation and deletes the current contact' do
message = create(:message, content_type: 'input_email', account: account, inbox: web_widget.inbox, conversation: conversation)
email = Faker::Internet.email
create(:contact, account: account, email: email)
contact_params = { email: email.upcase }
put api_v1_widget_message_url(message.id),
params: { website_token: web_widget.website_token, contact: contact_params },
headers: { 'X-Auth-Token' => token },
as: :json
expect(response).to have_http_status(:success)
message.reload
expect { contact.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
end
| 44.689922 | 137 | 0.671292 |
d5131303ee76694d171c25047f150960d91a2892 | 1,241 | require 'spec_helper'
module Alf
describe AttrList, 'subset?' do
context 'when equal' do
let(:left){ AttrList[:id, :name] }
let(:right){ AttrList[:name, :id] }
it 'returns true if non proper' do
expect(left.subset?(right)).to be_truthy
end
it 'returns false if proper' do
expect(left.subset?(right, true)).to be_falsey
end
end
context 'when both empty' do
let(:left){ AttrList[] }
let(:right){ AttrList[] }
it 'returns true if non proper' do
expect(left.subset?(right)).to be_truthy
end
it 'returns false if proper' do
expect(left.subset?(right, true)).to be_falsey
end
end
context 'when disjoint' do
let(:left){ AttrList[:status] }
let(:right){ AttrList[:name, :id] }
it 'returns false' do
expect(left.subset?(right)).to be_falsey
expect(left.subset?(right, true)).to be_falsey
end
end
context 'when a proper subset' do
let(:left){ AttrList[:name] }
let(:right){ AttrList[:id, :name] }
it 'returns true' do
expect(left.subset?(right)).to be_truthy
expect(left.subset?(right, true)).to be_truthy
end
end
end
end
| 24.333333 | 54 | 0.592264 |
01bca6c5495f35f0d1688e9c8d0f9052d47efc80 | 617 | class TimelineEntry::WhitehallImportedEntry < ApplicationRecord
enum entry_type: {
archived: "archived",
document_updated: "document_updated",
fact_check_request: "fact_check_request",
fact_check_response: "fact_check_response",
first_created: "first_created",
imported_from_whitehall: "imported_from_whitehall",
internal_note: "internal_note",
new_edition: "new_edition",
published: "published",
rejected: "rejected",
removed: "removed",
scheduled: "scheduled",
submitted: "submitted",
withdrawn: "withdrawn",
}
def readonly?
!new_record?
end
end
| 26.826087 | 63 | 0.71637 |
b9dd1c7807d63f503917bcebde06967b2de82c80 | 1,937 | # frozen_string_literal: true
require 'spec_helper'
describe 'osquery::ubuntu' do
include_context 'converged recipe'
let(:node_attributes_extra) do
{}
end
let(:node_attributes) do
{
'osquery' => {
'version' => '2.3.0',
'packs' => %w[chefspec]
}
}.merge(node_attributes_extra)
end
let(:platform) do
{ platform: 'ubuntu', version: '14.04', step_into: ['osquery_install'] }
end
before do
allow_any_instance_of(Chef::Resource).to receive(:rsyslog_legacy).and_return(Chef::Version.new('7.4.4'))
end
it 'converges without error' do
expect { chef_run }.not_to raise_error
end
context 'specific version' do
it 'installs osquery' do
expect(chef_run).to install_osquery_ubuntu('2.3.0')
end
it 'installs osquery package' do
expect(chef_run).to install_package('osquery').with(version: '2.3.0-1.linux')
end
end
context 'upgrade' do
let(:node_attributes_extra) do
{
'osquery' => {
'repo' => {
'package_upgrade' => true
}
}
}
end
it 'installs osquery' do
expect(chef_run).to install_osquery_ubuntu('4.5.1')
end
it 'installs/upgrades osquery package' do
expect(chef_run).to upgrade_package('osquery').with(version: '4.5.1-1.linux')
end
end
it 'sets up syslog for osquery' do
expect(chef_run).to create_osquery_syslog('/etc/rsyslog.d/60-osquery.conf')
end
it 'adds osquery apt repo' do
expect(chef_run).to add_apt_repository('osquery')
end
it 'creates osquery config' do
expect(chef_run).to create_osquery_config('/etc/osquery/osquery.conf')
.with(
pack_source: 'osquery',
packs: %w[chefspec],
decorators: {}
)
end
it 'starts and enables osquery service' do
expect(chef_run).to enable_service('osqueryd')
expect(chef_run).to start_service('osqueryd')
end
end
| 22.788235 | 108 | 0.639133 |
39de9de8b970832b1bb99d4bc4873140c3b0750f | 23,565 | # frozen_string_literal: true
require 'cucumber/cli/profile_loader'
require 'cucumber/formatter/ansicolor'
require 'cucumber/glue/registry_and_more'
require 'cucumber/project_initializer'
require 'cucumber/core/test/result'
module Cucumber
module Cli
class Options
INDENT = ' ' * 53
# rubocop:disable Layout/MultilineOperationIndentation
BUILTIN_FORMATS = {
'html' => ['Cucumber::Formatter::Html', 'Generates a nice looking HTML report.'],
'pretty' => ['Cucumber::Formatter::Pretty', 'Prints the feature as is - in colours.'],
'progress' => ['Cucumber::Formatter::Progress', 'Prints one character per scenario.'],
'rerun' => ['Cucumber::Formatter::Rerun', 'Prints failing files with line numbers.'],
'usage' => ['Cucumber::Formatter::Usage', "Prints where step definitions are used.\n" +
"#{INDENT}The slowest step definitions (with duration) are\n" +
"#{INDENT}listed first. If --dry-run is used the duration\n" +
"#{INDENT}is not shown, and step definitions are sorted by\n" +
"#{INDENT}filename instead."],
'stepdefs' => ['Cucumber::Formatter::Stepdefs', "Prints All step definitions with their locations. Same as\n" +
"#{INDENT}the usage formatter, except that steps are not printed."],
'junit' => ['Cucumber::Formatter::Junit', 'Generates a report similar to Ant+JUnit.'],
'json' => ['Cucumber::Formatter::Json', 'Prints the feature as JSON'],
'json_pretty' => ['Cucumber::Formatter::JsonPretty', 'Prints the feature as prettified JSON'],
'summary' => ['Cucumber::Formatter::Summary', 'Summary output of feature and scenarios']
}
# rubocop:enable Layout/MultilineOperationIndentation
max = BUILTIN_FORMATS.keys.map(&:length).max
FORMAT_HELP_MSG = [
'Use --format rerun --out rerun.txt to write out failing',
'features. You can rerun them with cucumber @rerun.txt.',
'FORMAT can also be the fully qualified class name of',
"your own custom formatter. If the class isn't loaded,",
'Cucumber will attempt to require a file with a relative',
'file name that is the underscore name of the class name.',
'Example: --format Foo::BarZap -> Cucumber will look for',
'foo/bar_zap.rb. You can place the file with this relative',
'path underneath your features/support directory or anywhere',
"on Ruby's LOAD_PATH, for example in a Ruby gem."
]
FORMAT_HELP = (BUILTIN_FORMATS.keys.sort.map do |key|
" #{key}#{' ' * (max - key.length)} : #{BUILTIN_FORMATS[key][1]}"
end) + FORMAT_HELP_MSG
PROFILE_SHORT_FLAG = '-p'
NO_PROFILE_SHORT_FLAG = '-P'
PROFILE_LONG_FLAG = '--profile'
NO_PROFILE_LONG_FLAG = '--no-profile'
FAIL_FAST_FLAG = '--fail-fast'
RETRY_FLAG = '--retry'
OPTIONS_WITH_ARGS = [
'-r', '--require', '--i18n-keywords', '-f', '--format', '-o',
'--out', '-t', '--tags', '-n', '--name', '-e', '--exclude',
PROFILE_SHORT_FLAG, PROFILE_LONG_FLAG, RETRY_FLAG, '-l',
'--lines', '--port', '-I', '--snippet-type'
]
ORDER_TYPES = %w{defined random}
TAG_LIMIT_MATCHER = /(?<tag_name>\@\w+):(?<limit>\d+)/x
def self.parse(args, out_stream, error_stream, options = {})
new(out_stream, error_stream, options).parse!(args)
end
def initialize(out_stream = STDOUT, error_stream = STDERR, options = {})
@out_stream = out_stream
@error_stream = error_stream
@default_profile = options[:default_profile]
@profiles = options[:profiles] || []
@overridden_paths = []
@options = default_options.merge(options)
@profile_loader = options[:profile_loader]
@options[:skip_profile_information] = options[:skip_profile_information]
@disable_profile_loading = nil
end
def [](key)
@options[key]
end
def []=(key, value)
@options[key] = value
end
def parse!(args) # rubocop:disable Metrics/AbcSize
@args = args
@expanded_args = @args.dup
@args.extend(::OptionParser::Arguable)
@args.options do |opts|
opts.banner = banner
opts.on('-r LIBRARY|DIR', '--require LIBRARY|DIR', *require_files_msg) { |lib| require_files(lib) }
if Cucumber::JRUBY
opts.on('-j DIR', '--jars DIR', 'Load all the jars under DIR') { |jars| load_jars(jars) }
end
opts.on("#{RETRY_FLAG} ATTEMPTS", *retry_msg) { |v| set_option :retry, v.to_i }
opts.on('--i18n-languages', *i18n_languages_msg) { list_languages_and_exit }
opts.on('--i18n-keywords LANG', *i18n_keywords_msg) { |lang| language lang }
opts.on(FAIL_FAST_FLAG, 'Exit immediately following the first failing scenario') { set_option :fail_fast }
opts.on('-f FORMAT', '--format FORMAT', *format_msg, *FORMAT_HELP) do |v|
add_option :formats, [*parse_formats(v), @out_stream]
end
opts.on('--init', *init_msg) { |v| initialize_project }
opts.on('-o', '--out [FILE|DIR]', *out_msg) { |v| out_stream v }
opts.on('-t TAG_EXPRESSION', '--tags TAG_EXPRESSION', *tags_msg) { |v| add_tag v }
opts.on('-n NAME', '--name NAME', *name_msg) { |v| add_option :name_regexps, /#{v}/ }
opts.on('-e', '--exclude PATTERN', *exclude_msg) { |v| add_option :excludes, Regexp.new(v) }
opts.on(PROFILE_SHORT_FLAG, "#{PROFILE_LONG_FLAG} PROFILE", *profile_short_flag_msg) { |v| add_profile v }
opts.on(NO_PROFILE_SHORT_FLAG, NO_PROFILE_LONG_FLAG, *no_profile_short_flag_msg) { |v| disable_profile_loading }
opts.on('-c', '--[no-]color', *color_msg) { |v| color v }
opts.on('-d', '--dry-run', *dry_run_msg) { set_dry_run_and_duration }
opts.on('-m', '--no-multiline', "Don't print multiline strings and tables under steps.") { set_option :no_multiline }
opts.on('-s', '--no-source', "Don't print the file and line of the step definition with the steps.") { set_option :source, false }
opts.on('-i', '--no-snippets', "Don't print snippets for pending steps.") { set_option :snippets, false }
opts.on('-I', '--snippet-type TYPE', *snippet_type_msg) { |v| set_option :snippet_type, v.to_sym }
opts.on('-q', '--quiet', 'Alias for --no-snippets --no-source.') { shut_up }
opts.on('--no-duration', "Don't print the duration at the end of the summary") { set_option :duration, false }
opts.on('-b', '--backtrace', 'Show full backtrace for all errors.') { Cucumber.use_full_backtrace = true }
opts.on('-S', '--[no-]strict', *strict_msg) { |setting| set_strict(setting) }
opts.on('--[no-]strict-undefined', 'Fail if there are any undefined results.') { |setting| set_strict(setting, :undefined) }
opts.on('--[no-]strict-pending', 'Fail if there are any pending results.') { |setting| set_strict(setting, :pending) }
opts.on('--[no-]strict-flaky', 'Fail if there are any flaky results.') { |setting| set_strict(setting, :flaky) }
opts.on('-w', '--wip', 'Fail if there are any passing scenarios.') { set_option :wip }
opts.on('-v', '--verbose', 'Show the files and features loaded.') { set_option :verbose }
opts.on('-g', '--guess', 'Guess best match for Ambiguous steps.') { set_option :guess }
opts.on('-l', '--lines LINES', *lines_msg) { |lines| set_option :lines, lines }
opts.on('-x', '--expand', 'Expand Scenario Outline Tables in output.') { set_option :expand }
opts.on('--order TYPE[:SEED]', 'Run examples in the specified order. Available types:',
*<<-TEXT.split("\n")) do |order|
[defined] Run scenarios in the order they were defined (default).
[random] Shuffle scenarios before running.
Specify SEED to reproduce the shuffling from a previous run.
e.g. --order random:5738
TEXT
@options[:order], @options[:seed] = *order.split(':')
unless ORDER_TYPES.include?(@options[:order])
fail "'#{@options[:order]}' is not a recognised order type. Please use one of #{ORDER_TYPES.join(", ")}."
end
end
opts.on_tail('--version', 'Show version.') { exit_ok(Cucumber::VERSION) }
opts.on_tail('-h', '--help', "You're looking at it.") { exit_ok(opts.help) }
end.parse!
@args.map! { |a| "#{a}:#{@options[:lines]}" } if @options[:lines]
extract_environment_variables
@options[:paths] = @args.dup # whatver is left over
check_formatter_stream_conflicts()
merge_profiles
self
end
def custom_profiles
@profiles - [@default_profile]
end
def filters
@options[:filters] ||= []
end
def check_formatter_stream_conflicts()
streams = @options[:formats].uniq.map { |(_, _, stream)| stream }
return if streams == streams.uniq
raise 'All but one formatter must use --out, only one can print to each stream (or STDOUT)'
end
def to_hash
Hash(@options)
end
protected
attr_reader :options, :profiles, :expanded_args
protected :options, :profiles, :expanded_args
private
def color_msg
[
'Whether or not to use ANSI color in the output. Cucumber decides',
'based on your platform and the output destination if not specified.'
]
end
def dry_run_msg
[
'Invokes formatters without executing the steps.',
'This also omits the loading of your support/env.rb file if it exists.'
]
end
def exclude_msg
["Don't run feature files or require ruby files matching PATTERN"]
end
def format_msg
['How to format features (Default: pretty). Available formats:']
end
def i18n_languages_msg
[
'List all available languages'
]
end
def i18n_keywords_msg
[
'List keywords for in a particular language',
%{Run with "--i18n help" to see all languages}
]
end
def init_msg
[
'Initializes folder structure and generates conventional files for',
'a Cucumber project.'
]
end
def lines_msg
['Run given line numbers. Equivalent to FILE:LINE syntax']
end
def no_profile_short_flag_msg
[
"Disables all profile loading to avoid using the 'default' profile."
]
end
def profile_short_flag_msg
[
'Pull commandline arguments from cucumber.yml which can be defined as',
"strings or arrays. When a 'default' profile is defined and no profile",
'is specified it is always used. (Unless disabled, see -P below.)',
'When feature files are defined in a profile and on the command line',
'then only the ones from the command line are used.'
]
end
def retry_msg
['Specify the number of times to retry failing tests (default: 0)']
end
def name_msg
[
'Only execute the feature elements which match part of the given name.',
'If this option is given more than once, it will match against all the',
'given names.'
]
end
def strict_msg
[
'Fail if there are any strict affected results ',
'(that is undefined, pending or flaky results).'
]
end
def parse_formats(v)
formatter, *formatter_options = v.split(',')
options_hash = Hash[formatter_options.map { |s| s.split('=') }]
[formatter, options_hash]
end
def out_stream(v)
@options[:formats] << ['pretty', {}, nil] if @options[:formats].empty?
@options[:formats][-1][2] = v
end
def tags_msg
[
'Only execute the features or scenarios with tags matching TAG_EXPRESSION.',
'Scenarios inherit tags declared on the Feature level. The simplest',
'TAG_EXPRESSION is simply a tag. Example: --tags @dev. To represent',
"boolean NOT preceed the tag with 'not '. Example: --tags 'not @dev'.",
'A tag expression can have several tags separated by an or which represents',
"logical OR. Example: --tags '@dev or @wip'. The --tags option can be specified",
'A tag expression can have several tags separated by an and which represents',
"logical AND. Example: --tags '@dev and @wip'. The --tags option can be specified",
'several times, and this also represents logical AND.',
"Example: --tags '@foo or not @bar' --tags @zap. This represents the boolean",
'expression (@foo || !@bar) && @zap.',
"\n",
'Beware that if you want to use several negative tags to exclude several tags',
"you have to use logical AND: --tags 'not @fixme and not @buggy'.",
"\n",
'Tags can be given a threshold to limit the number of occurrences.',
'Example: --tags @qa:3 will fail if there are more than 3 occurrences of the @qa tag.',
'This can be practical if you are practicing Kanban or CONWIP.'
]
end
def out_msg
[
'Write output to a file/directory instead of STDOUT. This option',
'applies to the previously specified --format, or the',
'default format if no format is specified. Check the specific',
"formatter's docs to see whether to pass a file or a dir."
]
end
def require_files_msg
[
'Require files before executing the features. If this',
'option is not specified, all *.rb files that are',
'siblings or below the features will be loaded auto-',
'matically. Automatic loading is disabled when this',
'option is specified, and all loading becomes explicit.',
'Files under directories named "support" are always',
'loaded first.',
'This option can be specified multiple times.'
]
end
def snippet_type_msg
[
'Use different snippet type (Default: cucumber_expression). Available types:',
Cucumber::Glue::RegistryAndMore.cli_snippet_type_options
].flatten
end
def banner
[
'Usage: cucumber [options] [ [FILE|DIR|URL][:LINE[:LINE]*] ]+', '',
'Examples:',
'cucumber examples/i18n/en/features',
'cucumber @rerun.txt (See --format rerun)',
'cucumber examples/i18n/it/features/somma.feature:6:98:113',
'cucumber -s -i http://rubyurl.com/eeCl', '', ''
].join("\n")
end
def require_files(v)
@options[:require] << v
return unless Cucumber::JRUBY && File.directory?(v)
require 'java'
$CLASSPATH << v
end
def require_jars(jars)
Dir["#{jars}/**/*.jar"].each { |jar| require jar }
end
def language(lang)
require 'gherkin/dialect'
return indicate_invalid_language_and_exit(lang) unless ::Gherkin::DIALECTS.keys.include? lang
list_keywords_and_exit(lang)
end
def disable_profile_loading
@disable_profile_loading = true
end
def non_stdout_formats
@options[:formats].select { |_, _, output| output != @out_stream }
end
def add_option(option, value)
@options[option] << value
end
def add_tag(value)
warn("Deprecated: Found tags option '#{value}'. Support for '~@tag' will be removed from the next release of Cucumber. Please use 'not @tag' instead.") if value.include?('~')
warn("Deprecated: Found tags option '#{value}'. Support for '@tag1,@tag2' will be removed from the next release of Cucumber. Please use '@tag or @tag2' instead.") if value.include?(',')
@options[:tag_expressions] << value.gsub(/(@\w+)(:\d+)?/, '\1')
add_tag_limits(value)
end
def add_tag_limits(value)
value.split(/[, ]/).map { |part| TAG_LIMIT_MATCHER.match(part) }.compact.each do |matchdata|
add_tag_limit(@options[:tag_limits], matchdata[:tag_name], matchdata[:limit].to_i)
end
end
def add_tag_limit(tag_limits, tag_name, limit)
if tag_limits[tag_name] && tag_limits[tag_name] != limit
raise "Inconsistent tag limits for #{tag_name}: #{tag_limits[tag_name]} and #{limit}"
end
tag_limits[tag_name] = limit
end
def color(color)
Cucumber::Term::ANSIColor.coloring = color
end
def initialize_project
ProjectInitializer.new.run && Kernel.exit(0)
end
def add_profile(p)
@profiles << p
end
def set_option(option, value = nil)
@options[option] = value.nil? ? true : value
end
def set_dry_run_and_duration
@options[:dry_run] = true
@options[:duration] = false
end
def exit_ok(text)
@out_stream.puts text
Kernel.exit(0)
end
def shut_up
@options[:snippets] = false
@options[:source] = false
@options[:duration] = false
end
def set_strict(setting, type = nil)
@options[:strict].set_strict(setting, type)
end
def stdout_formats
@options[:formats].select { |_, _, output| output == @out_stream }
end
def extract_environment_variables
@args.delete_if do |arg|
if arg =~ /^(\w+)=(.*)$/
@options[:env_vars][$1] = $2
true
end
end
end
def disable_profile_loading?
@disable_profile_loading
end
def merge_profiles
if @disable_profile_loading
@out_stream.puts 'Disabling profiles...'
return
end
@profiles << @default_profile if default_profile_should_be_used?
@profiles.each do |profile|
merge_with_profile(profile)
end
@options[:profiles] = @profiles
end
def merge_with_profile(profile)
profile_args = profile_loader.args_from(profile)
profile_options = Options.parse(
profile_args, @out_stream, @error_stream,
:skip_profile_information => true,
:profile_loader => profile_loader
)
reverse_merge(profile_options)
end
def default_profile_should_be_used?
@profiles.empty? &&
profile_loader.cucumber_yml_defined? &&
profile_loader.has_profile?(@default_profile)
end
def profile_loader
@profile_loader ||= ProfileLoader.new
end
def reverse_merge(other_options)
@options = other_options.options.merge(@options)
@options[:require] += other_options[:require]
@options[:excludes] += other_options[:excludes]
@options[:name_regexps] += other_options[:name_regexps]
@options[:tag_expressions] += other_options[:tag_expressions]
merge_tag_limits(@options[:tag_limits], other_options[:tag_limits])
@options[:env_vars] = other_options[:env_vars].merge(@options[:env_vars])
if @options[:paths].empty?
@options[:paths] = other_options[:paths]
else
@overridden_paths += (other_options[:paths] - @options[:paths])
end
@options[:source] &= other_options[:source]
@options[:snippets] &= other_options[:snippets]
@options[:duration] &= other_options[:duration]
@options[:strict] = other_options[:strict].merge!(@options[:strict])
@options[:dry_run] |= other_options[:dry_run]
@profiles += other_options.profiles
@expanded_args += other_options.expanded_args
if @options[:formats].empty?
@options[:formats] = other_options[:formats]
else
@options[:formats] += other_options[:formats]
@options[:formats] = stdout_formats[0..0] + non_stdout_formats
end
@options[:retry] = other_options[:retry] if @options[:retry] == 0
self
end
def merge_tag_limits(option_limits, other_limits)
other_limits.each { |key, value| add_tag_limit(option_limits, key, value) }
end
def indicate_invalid_language_and_exit(lang)
@out_stream.write("Invalid language '#{lang}'. Available languages are:\n")
list_languages_and_exit
end
def list_keywords_and_exit(lang)
require 'gherkin/dialect'
language = ::Gherkin::Dialect.for(lang)
data = Cucumber::MultilineArgument::DataTable.from(
[
['feature', to_keywords_string(language.feature_keywords)],
['background', to_keywords_string(language.background_keywords)],
['scenario', to_keywords_string(language.scenario_keywords)],
['scenario_outline', to_keywords_string(language.scenario_outline_keywords)],
['examples', to_keywords_string(language.examples_keywords)],
['given', to_keywords_string(language.given_keywords)],
['when', to_keywords_string(language.when_keywords)],
['then', to_keywords_string(language.then_keywords)],
['and', to_keywords_string(language.and_keywords)],
['but', to_keywords_string(language.but_keywords)],
['given (code)', to_code_keywords_string(language.given_keywords)],
['when (code)', to_code_keywords_string(language.when_keywords)],
['then (code)', to_code_keywords_string(language.then_keywords)],
['and (code)', to_code_keywords_string(language.and_keywords)],
['but (code)', to_code_keywords_string(language.but_keywords)]
]
)
@out_stream.write(data.to_s({ color: false, prefixes: Hash.new('') }))
Kernel.exit(0)
end
def list_languages_and_exit
require 'gherkin/dialect'
data = Cucumber::MultilineArgument::DataTable.from(
::Gherkin::DIALECTS.keys.map do |key|
[key, ::Gherkin::DIALECTS[key].fetch('name'), ::Gherkin::DIALECTS[key].fetch('native')]
end
)
@out_stream.write(data.to_s({ color: false, prefixes: Hash.new('') }))
Kernel.exit(0)
end
def to_keywords_string(list)
list.map { |item| "\"#{item}\"" }.join(', ')
end
def to_code_keywords_string(list)
to_keywords_string(Cucumber::Gherkin::I18n.code_keywords_for(list))
end
def default_options
{
:strict => Cucumber::Core::Test::Result::StrictConfiguration.new,
:require => [],
:dry_run => false,
:formats => [],
:excludes => [],
:tag_expressions => [],
:tag_limits => {},
:name_regexps => [],
:env_vars => {},
:diff_enabled => true,
:snippets => true,
:source => true,
:duration => true,
:retry => 0
}
end
end
end
end
| 39.738617 | 193 | 0.59478 |
625194c37a8f4f360ab7bc29edf29e8f58f48b84 | 1,957 | class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:show, :index]
load_and_authorize_resource
# GET /users
# GET /users.json
def index
@users = User.all
end
# GET /users/1
# GET /users/1.json
def show
end
# GET /users/new
def new
@user = User.new
end
# GET /users/1/edit
def edit
end
# POST /users
# POST /users.json
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
@user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:first_name, :last_name)
end
end
| 25.415584 | 89 | 0.621359 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.