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
|
---|---|---|---|---|---|
7949563a1dc84c2ad60f297c5d129d8e501f0f9e | 3,230 | # frozen_string_literal: true
require 'asana'
module Integrations
class Asana < Integration
include ActionView::Helpers::UrlHelper
prop_accessor :api_key, :restrict_to_branch
validates :api_key, presence: true, if: :activated?
def title
'Asana'
end
def description
s_('AsanaService|Add commit messages as comments to Asana tasks.')
end
def help
docs_link = link_to _('Learn more.'), Rails.application.routes.url_helpers.help_page_url('user/project/integrations/asana'), target: '_blank', rel: 'noopener noreferrer'
s_('Add commit messages as comments to Asana tasks. %{docs_link}').html_safe % { docs_link: docs_link.html_safe }
end
def self.to_param
'asana'
end
def fields
[
{
type: 'text',
name: 'api_key',
title: 'API key',
help: s_('AsanaService|User Personal Access Token. User must have access to the task. All comments are attributed to this user.'),
# Example Personal Access Token from Asana docs
placeholder: '0/68a9e79b868c6789e79a124c30b0',
required: true
},
{
type: 'text',
name: 'restrict_to_branch',
title: 'Restrict to branch (optional)',
help: s_('AsanaService|Comma-separated list of branches to be automatically inspected. Leave blank to include all branches.')
}
]
end
def self.supported_events
%w(push)
end
def client
@_client ||= begin
::Asana::Client.new do |c|
c.authentication :access_token, api_key
end
end
end
def execute(data)
return unless supported_events.include?(data[:object_kind])
# check the branch restriction is poplulated and branch is not included
branch = Gitlab::Git.ref_name(data[:ref])
branch_restriction = restrict_to_branch.to_s
if branch_restriction.present? && branch_restriction.index(branch).nil?
return
end
user = data[:user_name]
project_name = project.full_name
data[:commits].each do |commit|
push_msg = s_("AsanaService|%{user} pushed to branch %{branch} of %{project_name} ( %{commit_url} ):") % { user: user, branch: branch, project_name: project_name, commit_url: commit[:url] }
check_commit(commit[:message], push_msg)
end
end
def check_commit(message, push_msg)
# matches either:
# - #1234
# - https://app.asana.com/0/{project_gid}/{task_gid}
# optionally preceded with:
# - fix/ed/es/ing
# - close/s/d
# - closing
issue_finder = %r{(fix\w*|clos[ei]\w*+)?\W*(?:https://app\.asana\.com/\d+/\w+/(\w+)|#(\w+))}i
message.scan(issue_finder).each do |tuple|
# tuple will be
# [ 'fix', 'id_from_url', 'id_from_pound' ]
taskid = tuple[2] || tuple[1]
begin
task = ::Asana::Resources::Task.find_by_id(client, taskid)
task.add_comment(text: "#{push_msg} #{message}")
if tuple[0]
task.update(completed: true)
end
rescue StandardError => e
log_error(e.message)
next
end
end
end
end
end
| 29.363636 | 197 | 0.610217 |
3967ad0394aaf6d6786149eb8619b19fba2d8fe4 | 2,145 | require 'spec_helper'
describe 'Wildcarding' do
let(:permissions_hash) { {} }
let(:permissions) { Sanction.build(permissions_hash) }
let(:predicates) { [] }
let(:permission) { Sanction::Permission.new(permissions, *predicates)}
describe 'whitelist' do
let(:permissions_hash) { {
mode: 'whitelist',
scope: ['manage', 'read'],
resources: ['bookcase', 'user'],
subjects: [
{
id: 1,
type: 'bookcase',
scope: ['read']
},
{
id: '*',
mode: 'blacklist',
type: 'user',
scope: ['manage', 'read'],
subjects: [
{
id: '*',
type: 'bookcase',
subjects: [
id: '1',
type: 'pack'
]
}
]
}
]
} }
let(:user) { User.new(7) }
let(:predicates) { [user] }
it 'should be permitted' do
permission.permitted?.must_equal true
end
it 'should have the scope of manage' do
permission.permitted_with_scope?(:manage).must_equal true
end
describe 'nested block' do
let(:bookcase) { Bookcase.new(121) }
let(:predicates) { [user, bookcase] }
it 'should not be permitted' do
permission.permitted?.must_equal false
end
describe 'with a pack' do
let(:pack) { Pack.new(1) }
let(:predicates) { [user, bookcase, pack] }
it 'should not be permitted' do
permission.permitted?.must_equal false
end
end
end
end
describe 'blacklist' do
let(:permissions_hash) { {
mode: 'blacklist',
scope: ['manage', 'read'],
resources: ['bookcase'],
subjects: [
{
id: 1,
type: 'bookcase',
scope: ['read']
},
{
id: '*',
type: 'user',
scope: ['manage', 'read']
}
]
} }
let(:user) { User.new(7) }
let(:predicates) { [user] }
it 'should not be permitted' do
permission.permitted?.must_equal false
end
end
end | 22.578947 | 79 | 0.486247 |
01004d0efd60080bf6f8355deff077d27c443fed | 1,467 | =begin
Ruby InsightVM API Client
OpenAPI spec version: 3
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.3.0
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for Rapid7VmConsole::VulnerabilityValidationSource
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'VulnerabilityValidationSource' do
before do
# run before each test
@instance = Rapid7VmConsole::VulnerabilityValidationSource.new
end
after do
# run after each test
end
describe 'test an instance of VulnerabilityValidationSource' do
it 'should create an instance of VulnerabilityValidationSource' do
expect(@instance).to be_instance_of(Rapid7VmConsole::VulnerabilityValidationSource)
end
end
describe 'test attribute "key"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
#validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["metasploit", "other"])
#validator.allowable_values.each do |value|
# expect { @instance.name = value }.not_to raise_error
#end
end
end
end
| 28.764706 | 103 | 0.740286 |
5d5e912c9d13a816d11c464a25a26e3917a2a000 | 25,066 | # Copyright 2017 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.
require "helper"
describe Google::Cloud::Firestore::Client, :transaction, :mock_firestore do
let(:transaction_id) { "transaction123" }
let(:transaction_opt) do
Google::Firestore::V1::TransactionOptions.new(
read_write: Google::Firestore::V1::TransactionOptions::ReadWrite.new
)
end
let(:transaction_opt) do
Google::Firestore::V1::TransactionOptions.new(
read_write: Google::Firestore::V1::TransactionOptions::ReadWrite.new
)
end
let(:read_time) { Time.now }
let :query_results_enum do
[
Google::Firestore::V1::RunQueryResponse.new(
transaction: transaction_id,
read_time: Google::Cloud::Firestore::Convert.time_to_timestamp(read_time),
document: Google::Firestore::V1::Document.new(
name: "projects/#{project}/databases/(default)/documents/users/mike",
fields: { "name" => Google::Firestore::V1::Value.new(string_value: "Mike") },
create_time: Google::Cloud::Firestore::Convert.time_to_timestamp(read_time),
update_time: Google::Cloud::Firestore::Convert.time_to_timestamp(read_time)
)),
Google::Firestore::V1::RunQueryResponse.new(
read_time: Google::Cloud::Firestore::Convert.time_to_timestamp(read_time),
document: Google::Firestore::V1::Document.new(
name: "projects/#{project}/databases/(default)/documents/users/chris",
fields: { "name" => Google::Firestore::V1::Value.new(string_value: "Chris") },
create_time: Google::Cloud::Firestore::Convert.time_to_timestamp(read_time),
update_time: Google::Cloud::Firestore::Convert.time_to_timestamp(read_time)
))
].to_enum
end
let(:document_path) { "users/mike" }
let(:database_path) { "projects/#{project}/databases/(default)" }
let(:documents_path) { "#{database_path}/documents" }
let(:commit_time) { Time.now }
let :create_writes do
[Google::Firestore::V1::Write.new(
update: Google::Firestore::V1::Document.new(
name: "#{documents_path}/#{document_path}",
fields: Google::Cloud::Firestore::Convert.hash_to_fields({ name: "Mike" })),
current_document: Google::Firestore::V1::Precondition.new(
exists: false)
)]
end
let :set_writes do
[Google::Firestore::V1::Write.new(
update: Google::Firestore::V1::Document.new(
name: "#{documents_path}/#{document_path}",
fields: Google::Cloud::Firestore::Convert.hash_to_fields({ name: "Mike" }))
)]
end
let :update_writes do
[Google::Firestore::V1::Write.new(
update: Google::Firestore::V1::Document.new(
name: "#{documents_path}/#{document_path}",
fields: Google::Cloud::Firestore::Convert.hash_to_fields({ name: "Mike" })),
update_mask: Google::Firestore::V1::DocumentMask.new(
field_paths: ["name"]
),
current_document: Google::Firestore::V1::Precondition.new(
exists: true)
)]
end
let :delete_writes do
[Google::Firestore::V1::Write.new(
delete: "#{documents_path}/#{document_path}")]
end
let :begin_tx_resp do
Google::Firestore::V1::BeginTransactionResponse.new(
transaction: transaction_id
)
end
let :empty_commit_resp do
Google::Firestore::V1::CommitResponse.new(
commit_time: Google::Cloud::Firestore::Convert.time_to_timestamp(commit_time),
)
end
let :write_commit_resp do
Google::Firestore::V1::CommitResponse.new(
commit_time: Google::Cloud::Firestore::Convert.time_to_timestamp(commit_time),
write_results: [Google::Firestore::V1::WriteResult.new(
update_time: Google::Cloud::Firestore::Convert.time_to_timestamp(commit_time))]
)
end
it "runs a simple query" do
expected_query = Google::Firestore::V1::StructuredQuery.new(
select: Google::Firestore::V1::StructuredQuery::Projection.new(
fields: [Google::Firestore::V1::StructuredQuery::FieldReference.new(field_path: "name")]),
from: [Google::Firestore::V1::StructuredQuery::CollectionSelector.new(collection_id: "users", all_descendants: false)]
)
firestore_mock.expect :run_query, query_results_enum, ["projects/#{project}/databases/(default)/documents", structured_query: expected_query, new_transaction: transaction_opt, options: default_options]
firestore_mock.expect :commit, empty_commit_resp, [database_path, [], transaction: transaction_id, options: default_options]
firestore.transaction do |tx|
results_enum = tx.get firestore.col(:users).select(:name)
assert_results_enum results_enum
end
end
it "runs a complex query" do
expected_query = Google::Firestore::V1::StructuredQuery.new(
select: Google::Firestore::V1::StructuredQuery::Projection.new(
fields: [Google::Firestore::V1::StructuredQuery::FieldReference.new(field_path: "name")]),
from: [Google::Firestore::V1::StructuredQuery::CollectionSelector.new(collection_id: "users", all_descendants: false)],
offset: 3,
limit: Google::Protobuf::Int32Value.new(value: 42),
order_by: [
Google::Firestore::V1::StructuredQuery::Order.new(
field: Google::Firestore::V1::StructuredQuery::FieldReference.new(field_path: "name"),
direction: :ASCENDING),
Google::Firestore::V1::StructuredQuery::Order.new(
field: Google::Firestore::V1::StructuredQuery::FieldReference.new(field_path: "__name__"),
direction: :DESCENDING)],
start_at: Google::Firestore::V1::Cursor.new(values: [Google::Cloud::Firestore::Convert.raw_to_value("foo")], before: false),
end_at: Google::Firestore::V1::Cursor.new(values: [Google::Cloud::Firestore::Convert.raw_to_value("bar")], before: true)
)
firestore_mock.expect :run_query, query_results_enum, ["projects/#{project}/databases/(default)/documents", structured_query: expected_query, new_transaction: transaction_opt, options: default_options]
firestore_mock.expect :commit, empty_commit_resp, [database_path, [], transaction: transaction_id, options: default_options]
firestore.transaction do |tx|
results_enum = tx.get firestore.col(:users).select(:name).offset(3).limit(42).order(:name).order(firestore.document_id, :desc).start_after(:foo).end_before(:bar)
assert_results_enum results_enum
end
end
it "runs multiple queries" do
first_query = Google::Firestore::V1::StructuredQuery.new(
select: Google::Firestore::V1::StructuredQuery::Projection.new(
fields: [Google::Firestore::V1::StructuredQuery::FieldReference.new(field_path: "name")]),
from: [Google::Firestore::V1::StructuredQuery::CollectionSelector.new(collection_id: "users", all_descendants: false)]
)
second_query = Google::Firestore::V1::StructuredQuery.new(
select: Google::Firestore::V1::StructuredQuery::Projection.new(
fields: [Google::Firestore::V1::StructuredQuery::FieldReference.new(field_path: "name")]),
from: [Google::Firestore::V1::StructuredQuery::CollectionSelector.new(collection_id: "users", all_descendants: false)],
offset: 3,
limit: Google::Protobuf::Int32Value.new(value: 42),
order_by: [
Google::Firestore::V1::StructuredQuery::Order.new(
field: Google::Firestore::V1::StructuredQuery::FieldReference.new(field_path: "name"),
direction: :ASCENDING),
Google::Firestore::V1::StructuredQuery::Order.new(
field: Google::Firestore::V1::StructuredQuery::FieldReference.new(field_path: "__name__"),
direction: :DESCENDING)],
start_at: Google::Firestore::V1::Cursor.new(values: [Google::Cloud::Firestore::Convert.raw_to_value("foo")], before: false),
end_at: Google::Firestore::V1::Cursor.new(values: [Google::Cloud::Firestore::Convert.raw_to_value("bar")], before: true)
)
firestore_mock.expect :run_query, query_results_enum, ["projects/#{project}/databases/(default)/documents", structured_query: first_query, new_transaction: transaction_opt, options: default_options]
firestore_mock.expect :run_query, query_results_enum, ["projects/#{project}/databases/(default)/documents", structured_query: second_query, transaction: transaction_id, options: default_options]
firestore_mock.expect :commit, empty_commit_resp, [database_path, [], transaction: transaction_id, options: default_options]
firestore.transaction do |tx|
results_enum = tx.get firestore.col(:users).select(:name)
assert_results_enum results_enum
results_enum = tx.get firestore.col(:users).select(:name).offset(3).limit(42).order(:name).order(firestore.document_id, :desc).start_after(:foo).end_before(:bar)
assert_results_enum results_enum
end
end
it "that does nothing makes no calls" do
firestore.transaction do |tx|
# no op
end
end
it "creates a new document using string path" do
firestore_mock.expect :begin_transaction, begin_tx_resp, [database_path, options_: transaction_opt, options: default_options]
firestore_mock.expect :commit, write_commit_resp, [database_path, create_writes, transaction: transaction_id, options: default_options]
resp = firestore.transaction do |tx|
tx.create(document_path, { name: "Mike" })
end
resp.must_be_kind_of Google::Cloud::Firestore::CommitResponse
resp.commit_time.must_equal commit_time
end
it "creates a new document using doc ref" do
firestore_mock.expect :begin_transaction, begin_tx_resp, [database_path, options_: transaction_opt, options: default_options]
firestore_mock.expect :commit, write_commit_resp, [database_path, create_writes, transaction: transaction_id, options: default_options]
doc = firestore.doc document_path
resp = firestore.transaction do |tx|
tx.create(doc, { name: "Mike" })
end
resp.must_be_kind_of Google::Cloud::Firestore::CommitResponse
resp.commit_time.must_equal commit_time
end
it "raises if create is not given a Hash" do
error = expect do
firestore.transaction do |tx|
tx.create document_path, "not a hash"
end
end.must_raise ArgumentError
error.message.must_equal "data is required"
end
it "sets a new document using string path" do
firestore_mock.expect :begin_transaction, begin_tx_resp, [database_path, options_: transaction_opt, options: default_options]
firestore_mock.expect :commit, write_commit_resp, [database_path, set_writes, transaction: transaction_id, options: default_options]
resp = firestore.transaction do |tx|
tx.set(document_path, { name: "Mike" })
end
resp.must_be_kind_of Google::Cloud::Firestore::CommitResponse
resp.commit_time.must_equal commit_time
end
it "sets a new document using doc ref" do
firestore_mock.expect :begin_transaction, begin_tx_resp, [database_path, options_: transaction_opt, options: default_options]
firestore_mock.expect :commit, write_commit_resp, [database_path, set_writes, transaction: transaction_id, options: default_options]
doc = firestore.doc document_path
resp = firestore.transaction do |tx|
tx.set(doc, { name: "Mike" })
end
resp.must_be_kind_of Google::Cloud::Firestore::CommitResponse
resp.commit_time.must_equal commit_time
end
it "raises if set is not given a Hash" do
error = expect do
firestore.transaction do |tx|
tx.set document_path, "not a hash"
end
end.must_raise ArgumentError
error.message.must_equal "data is required"
end
it "updates a new document using string path" do
firestore_mock.expect :begin_transaction, begin_tx_resp, [database_path, options_: transaction_opt, options: default_options]
firestore_mock.expect :commit, write_commit_resp, [database_path, update_writes, transaction: transaction_id, options: default_options]
resp = firestore.transaction do |tx|
tx.update(document_path, { name: "Mike" })
end
resp.must_be_kind_of Google::Cloud::Firestore::CommitResponse
resp.commit_time.must_equal commit_time
end
it "updates a new document using doc ref" do
firestore_mock.expect :begin_transaction, begin_tx_resp, [database_path, options_: transaction_opt, options: default_options]
firestore_mock.expect :commit, write_commit_resp, [database_path, update_writes, transaction: transaction_id, options: default_options]
doc = firestore.doc document_path
resp = firestore.transaction do |tx|
tx.update(doc, { name: "Mike" })
end
resp.must_be_kind_of Google::Cloud::Firestore::CommitResponse
resp.commit_time.must_equal commit_time
end
it "raises if update is not given a Hash" do
error = expect do
firestore.transaction do |tx|
tx.update document_path, "not a hash"
end
end.must_raise ArgumentError
error.message.must_equal "data is required"
end
it "deletes a document using string path" do
firestore_mock.expect :begin_transaction, begin_tx_resp, [database_path, options_: transaction_opt, options: default_options]
firestore_mock.expect :commit, write_commit_resp, [database_path, delete_writes, transaction: transaction_id, options: default_options]
resp = firestore.transaction do |tx|
tx.delete document_path
end
resp.must_be_kind_of Google::Cloud::Firestore::CommitResponse
resp.commit_time.must_equal commit_time
end
it "deletes a document using doc ref" do
firestore_mock.expect :begin_transaction, begin_tx_resp, [database_path, options_: transaction_opt, options: default_options]
firestore_mock.expect :commit, write_commit_resp, [database_path, delete_writes, transaction: transaction_id, options: default_options]
doc = firestore.doc document_path
resp = firestore.transaction do |tx|
tx.delete doc
end
resp.must_be_kind_of Google::Cloud::Firestore::CommitResponse
resp.commit_time.must_equal commit_time
end
it "returns nil when no work is done in the transaction" do
resp = firestore.transaction do |tx|
# no op
end
resp.commit_time.must_be :nil?
end
it "performs multiple writes in the same commit (string)" do
all_writes = create_writes + set_writes + update_writes + delete_writes
firestore_mock.expect :begin_transaction, begin_tx_resp, [database_path, options_: transaction_opt, options: default_options]
firestore_mock.expect :commit, write_commit_resp, [database_path, all_writes, transaction: transaction_id, options: default_options]
resp = firestore.transaction do |tx|
tx.create(document_path, { name: "Mike" })
tx.set(document_path, { name: "Mike" })
tx.update(document_path, { name: "Mike" })
tx.delete document_path
end
resp.must_be_kind_of Google::Cloud::Firestore::CommitResponse
resp.commit_time.must_equal commit_time
end
it "performs multiple writes in the same commit (doc ref)" do
all_writes = create_writes + set_writes + update_writes + delete_writes
firestore_mock.expect :begin_transaction, begin_tx_resp, [database_path, options_: transaction_opt, options: default_options]
firestore_mock.expect :commit, write_commit_resp, [database_path, all_writes, transaction: transaction_id, options: default_options]
doc_ref = firestore.doc document_path
doc_ref.must_be_kind_of Google::Cloud::Firestore::DocumentReference
resp = firestore.transaction do |tx|
tx.create(doc_ref, { name: "Mike" })
tx.set(doc_ref, { name: "Mike" })
tx.update(doc_ref, { name: "Mike" })
tx.delete doc_ref
end
resp.must_be_kind_of Google::Cloud::Firestore::CommitResponse
resp.commit_time.must_equal commit_time
end
it "closed transactions cannot make changes" do
doc_ref = firestore.doc document_path
doc_ref.must_be_kind_of Google::Cloud::Firestore::DocumentReference
outside_transaction_obj = nil
resp = firestore.transaction do |tx|
tx.wont_be :closed?
tx.firestore.must_equal firestore
outside_transaction_obj = tx
end
resp.commit_time.must_be :nil?
outside_transaction_obj.must_be :closed?
error = expect do
firestore.batch do |b|
outside_transaction_obj.create(doc_ref, { name: "Mike" })
end
end.must_raise RuntimeError
error.message.must_equal "transaction is closed"
end
describe :retry do
it "retries when an unavailable error is raised" do
# Unable to use mocks to define the responses, so stub the methods instead
def firestore_mock.begin_transaction path, options_: nil, options: nil
if @first_begin_transaction.nil?
@first_begin_transaction = true
raise "bad first begin_transaction" unless options_.read_write.retry_transaction.empty?
return Google::Firestore::V1::BeginTransactionResponse.new(transaction: "transaction123")
end
raise "bad second begin_transaction" unless options_.read_write.retry_transaction == "transaction123"
Google::Firestore::V1::BeginTransactionResponse.new(transaction: "new_transaction_xyz")
end
def firestore_mock.commit database, writes, transaction: nil, options: nil
if @first_commit.nil?
@first_commit = true
raise "bad first commit" unless transaction == "transaction123"
gax_error = Google::Gax::GaxError.new "unavailable"
gax_error.instance_variable_set :@cause, GRPC::BadStatus.new(14, "unavailable")
raise gax_error
end
raise "bad second commit" unless transaction == "new_transaction_xyz"
Google::Firestore::V1::CommitResponse.new(
commit_time: Google::Cloud::Firestore::Convert.time_to_timestamp(Time.now),
write_results: [Google::Firestore::V1::WriteResult.new(
update_time: Google::Cloud::Firestore::Convert.time_to_timestamp(Time.now))]
)
end
def firestore.set_sleep_mock sleep_mock
@sleep_mock = sleep_mock
end
def firestore.sleep num
@sleep_mock.sleep num
end
sleep_mock = Minitest::Mock.new
sleep_mock.expect :sleep, nil, [1.0]
firestore.set_sleep_mock sleep_mock
firestore.transaction do |tx|
tx.create(document_path, { name: "Mike" })
tx.set(document_path, { name: "Mike" })
tx.update(document_path, { name: "Mike" })
tx.delete document_path
end
sleep_mock.verify
end
it "retries multiple times when an unavailable error is raised" do
# Unable to use mocks to define the responses, so stub the methods instead
def firestore_mock.begin_transaction path, options_: nil, options: nil
@begin_retries ||= 0
@begin_retries += 1
if @begin_retries < 4
return Google::Firestore::V1::BeginTransactionResponse.new(transaction: "transaction_#{@begin_retries}")
end
raise "bad final begin_transaction" unless options_.read_write.retry_transaction == "transaction_3"
Google::Firestore::V1::BeginTransactionResponse.new(transaction: "new_transaction_xyz")
end
def firestore_mock.commit database, writes, transaction: nil, options: nil
@commit_retries ||= 0
@commit_retries += 1
if @commit_retries < 4
raise "bad commit" unless transaction.start_with?("transaction_")
gax_error = Google::Gax::GaxError.new "unavailable"
gax_error.instance_variable_set :@cause, GRPC::BadStatus.new(14, "unavailable")
raise gax_error
end
raise "bad final commit" unless transaction == "new_transaction_xyz"
Google::Firestore::V1::CommitResponse.new(
commit_time: Google::Cloud::Firestore::Convert.time_to_timestamp(Time.now),
write_results: [Google::Firestore::V1::WriteResult.new(
update_time: Google::Cloud::Firestore::Convert.time_to_timestamp(Time.now))]
)
end
def firestore.set_sleep_mock sleep_mock
@sleep_mock = sleep_mock
end
def firestore.sleep num
@sleep_mock.sleep num
end
sleep_mock = Minitest::Mock.new
sleep_mock.expect :sleep, nil, [1.0]
sleep_mock.expect :sleep, nil, [1.3]
sleep_mock.expect :sleep, nil, [1.3*1.3]
firestore.set_sleep_mock sleep_mock
firestore.transaction do |tx|
tx.create(document_path, { name: "Mike" })
tx.set(document_path, { name: "Mike" })
tx.update(document_path, { name: "Mike" })
tx.delete document_path
end
sleep_mock.verify
end
it "retries when unavailable, succeeds if invalid arg raised after" do
# Unable to use mocks to define the responses, so stub the methods instead
def firestore_mock.begin_transaction path, options_: nil, options: nil
if @first_begin_transaction.nil?
@first_begin_transaction = true
raise "bad first begin_transaction" unless options_.read_write.retry_transaction.empty?
return Google::Firestore::V1::BeginTransactionResponse.new(transaction: "transaction123")
end
raise "bad second begin_transaction" unless options_.read_write.retry_transaction == "transaction123"
Google::Firestore::V1::BeginTransactionResponse.new(transaction: "new_transaction_xyz")
end
def firestore_mock.commit database, writes, transaction: nil, options: nil
if @first_commit.nil?
@first_commit = true
raise "bad first commit" unless transaction == "transaction123"
gax_error = Google::Gax::GaxError.new "unavailable"
gax_error.instance_variable_set :@cause, GRPC::BadStatus.new(14, "unavailable")
raise gax_error
end
raise "bad second commit" unless transaction == "new_transaction_xyz"
gax_error = Google::Gax::GaxError.new "invalid"
gax_error.instance_variable_set :@cause, GRPC::BadStatus.new(3, "invalid")
raise gax_error
end
def firestore.set_sleep_mock sleep_mock
@sleep_mock = sleep_mock
end
def firestore.sleep num
@sleep_mock.sleep num
end
sleep_mock = Minitest::Mock.new
sleep_mock.expect :sleep, nil, [1.0]
firestore.set_sleep_mock sleep_mock
firestore.transaction do |tx|
tx.create(document_path, { name: "Mike" })
tx.set(document_path, { name: "Mike" })
tx.update(document_path, { name: "Mike" })
tx.delete document_path
end
sleep_mock.verify
end
it "does not retry when an unsupported error is raised" do
firestore_mock.expect :begin_transaction, begin_tx_resp, [database_path, options_: transaction_opt, options: default_options]
firestore_mock.expect :rollback, nil, ["projects/#{project}/databases/(default)", transaction_id, options: default_options]
# Unable to use mocks to raise an error, so stub the method instead
def firestore_mock.commit database, writes, transaction: nil, options: nil
raise "unsupported"
end
error = expect do
firestore.transaction do |tx|
tx.create(document_path, { name: "Mike" })
tx.set(document_path, { name: "Mike" })
tx.update(document_path, { name: "Mike" })
tx.delete document_path
end
end.must_raise RuntimeError
error.message.must_equal "unsupported"
end
end
def assert_results_enum enum
enum.must_be_kind_of Enumerator
results = enum.to_a
results.count.must_equal 2
results.each do |result|
result.must_be_kind_of Google::Cloud::Firestore::DocumentSnapshot
result.ref.must_be_kind_of Google::Cloud::Firestore::DocumentReference
result.ref.client.must_equal firestore
result.parent.must_be_kind_of Google::Cloud::Firestore::CollectionReference
result.parent.collection_id.must_equal "users"
result.parent.collection_path.must_equal "users"
result.parent.path.must_equal "projects/projectID/databases/(default)/documents/users"
result.parent.client.must_equal firestore
end
results.first.data.must_be_kind_of Hash
results.first.data.must_equal({ name: "Mike" })
results.first.created_at.must_equal read_time
results.first.updated_at.must_equal read_time
results.first.read_at.must_equal read_time
results.last.data.must_be_kind_of Hash
results.last.data.must_equal({ name: "Chris" })
results.last.created_at.must_equal read_time
results.last.updated_at.must_equal read_time
results.last.read_at.must_equal read_time
end
end
| 42.629252 | 205 | 0.710245 |
7a322078f508a341460eb1c24e781bfcecd623a1 | 333 | require 'colorize'
require_relative 'tictactoe/game'
require_relative 'tictactoe/input'
require_relative 'tictactoe/output'
require_relative 'tictactoe/coords_provider'
input = CLIInput.new
output = CLIOutput.new
board = Board.new(output)
coords = CoordsProvider.new(input, output)
game = Game.new(board, coords, output)
game.start | 25.615385 | 44 | 0.807808 |
034ecfb33fa0cd1af21a4f656a08b8332a2a5bfe | 788 | cask "clay" do
arch = Hardware::CPU.intel? ? "" : "-arm64"
version "1.6.3"
if Hardware::CPU.intel?
sha256 "b931d44e3dd4fef1e04b4ed1791cf05f96b2759f399226d8a660184c5eab090a"
else
sha256 "04775efa3008e7f7556b97f71f2d90fbd9370cd142a523d2e65a1e6f90efbfb1"
end
url "https://assets.clay.earth/desktop/mac/Clay-#{version}#{arch}.dmg"
name "clay"
desc "Private rolodex to remember people better"
homepage "https://clay.earth/"
livecheck do
url "https://assets.clay.earth/desktop/mac/latest-mac.yml"
strategy :electron_builder
end
app "Clay.app"
zap trash: [
"~/Library/Application Support/Clay",
"~/Library/Logs/Clay",
"~/Library/Preferences/com.clay.mac.plist",
"~/Library/Saved Application State/com.clay.mac.savedState",
]
end
| 25.419355 | 77 | 0.71066 |
bb4d141c20c437c1559121cc956153678b33f94a | 756 | # frozen_string_literal: true
$:.push File.expand_path('lib', __dir__)
require 'administrate_ransack/version'
Gem::Specification.new do |spec|
spec.name = 'administrate_ransack'
spec.version = AdministrateRansack::VERSION
spec.authors = ['Mattia Roccoberton']
spec.email = ['[email protected]']
spec.homepage = 'https://github.com/blocknotes/administrate_ransack'
spec.summary = 'Administrate Ransack plugin'
spec.description = 'A plugin for Administrate to use Ransack for search filters'
spec.license = 'MIT'
spec.files = Dir['{app,config,lib}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.md']
spec.add_runtime_dependency 'administrate', '~> 0.14'
spec.add_runtime_dependency 'ransack', '~> 2.3'
end
| 34.363636 | 83 | 0.698413 |
6272950eefb5f214c814b2884b5c3a7d503e59c1 | 264 | ENV['SINATRA_ENV'] ||= "development"
require 'bundler/setup'
Bundler.require(:default, ENV['SINATRA_ENV'])
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:database => "db/#{ENV['SINATRA_ENV']}.sqlite"
)
require './app'
require_all 'models'
| 20.307692 | 48 | 0.704545 |
394c739bd12a3bae01e3660140af711d9419bdf7 | 297 | class MarkdownFilterExtension < Radiant::Extension
version "1.0"
description "Allows you to compose page parts or snippets using the Markdown or SmartyPants text filters."
url "http://daringfireball.net/projects/markdown/"
def activate
MarkdownFilter
SmartyPantsFilter
end
end | 29.7 | 108 | 0.771044 |
1a24845b71a2b97d1a65de49aa84ceacc15cd9dc | 366 | require 'phonetic'
describe String do
describe '#double_metaphone' do
it 'should return Double Metaphone code of string' do
'Gelatin'.double_metaphone.should == ['KLTN', 'JLTN']
end
end
describe '#metaphone2' do
it 'should return Double Metaphone code of string' do
'whirlpool'.metaphone2.should == ['ARLP', 'ARLP']
end
end
end
| 22.875 | 59 | 0.677596 |
91451cf4829a74c7dd6ff2a2eee1674939c1a5a9 | 5,218 | class SlideshowView < NSView
def initWithFrame(frame)
super
# preload shading bitmap to use in transitions:
# this one is for "SlideshowViewPageCurlTransitionStyle", and "SlideshowViewRippleTransitionStyle"
bundle = NSBundle.bundleForClass(self.class)
pathURL = NSURL.fileURLWithPath(bundle.pathForResource("restrictedshine", ofType:"tiff"))
@inputShadingImage = CIImage.imageWithContentsOfURL(pathURL)
# this one is for "SlideshowViewDisintegrateWithMaskTransitionStyle"
pathURL = NSURL.fileURLWithPath(bundle.pathForResource("transitionmask", ofType:"jpg"))
@inputMaskImage = CIImage.imageWithContentsOfURL(pathURL)
self
end
def updateSubviewsWithTransition(transition)
rect = self.bounds
# Use Core Animation's four built-in CATransition types,
# or an appropriately instantiated and configured Core Image CIFilter.
if transitionFilter = CIFilter.filterWithName(transition)
transitionFilter.setDefaults
end
case transition
when "CICopyMachineTransition"
transitionFilter.setValue(
CIVector.vectorWithX(rect.origin.x, Y:rect.origin.y, Z:rect.size.width, W:rect.size.height),
forKey:"inputExtent")
when "CIDisintegrateWithMaskTransition"
# scale our mask image to match the transition area size, and set the scaled result as the
# "inputMaskImage" to the transitionFilter.
maskScalingFilter = CIFilter.filterWithName("CILanczosScaleTransform")
maskScalingFilter.setDefaults
maskExtent = @inputMaskImage.extent
xScale = rect.size.width / maskExtent.size.width;
yScale = rect.size.height / maskExtent.size.height;
maskScalingFilter.setValue(yScale, forKey:"inputScale")
maskScalingFilter.setValue(xScale / yScale, forKey:"inputAspectRatio")
maskScalingFilter.setValue(@inputMaskImage, forKey:"inputImage")
transitionFilter.setValue(maskScalingFilter.valueForKey("outputImage"), forKey:"inputMaskImage")
when "CIFlashTransition"
transitionFilter.setValue(CIVector.vectorWithX(NSMidX(rect), Y:NSMidY(rect)), forKey:"inputCenter")
transitionFilter.setValue(CIVector.vectorWithX(rect.origin.x, Y:rect.origin.y, Z:rect.size.width, W:rect.size.height), forKey:"inputExtent")
when "CIModTransition"
transitionFilter.setValue(CIVector.vectorWithX(NSMidX(rect), Y:NSMidY(rect)), forKey:"inputCenter")
when "CIPageCurlTransition"
transitionFilter.setValue(-Math::PI/4, forKey:"inputAngle")
transitionFilter.setValue(@inputShadingImage, forKey:"inputShadingImage")
transitionFilter.setValue(@inputShadingImage, forKey:"inputBacksideImage")
transitionFilter.setValue(CIVector.vectorWithX(rect.origin.x, Y:rect.origin.y, Z:rect.size.width, W:rect.size.height), forKey:"inputExtent")
when "CIRippleTransition"
transitionFilter.setValue(CIVector.vectorWithX(NSMidX(rect), Y:NSMidY(rect)), forKey:"inputCenter")
transitionFilter.setValue(CIVector.vectorWithX(rect.origin.x, Y:rect.origin.y, Z:rect.size.width, W:rect.size.height), forKey:"inputExtent")
transitionFilter.setValue(@inputShadingImage, forKey:"inputShadingImage")
end
# construct a new CATransition that describes the transition effect we want.
newTransition = CATransition.animation
if transitionFilter
# we want to build a CIFilter-based CATransition.
# When an CATransition's "filter" property is set, the CATransition's "type" and "subtype" properties are ignored,
# so we don't need to bother setting them.
newTransition.setFilter(transitionFilter)
else
# we want to specify one of Core Animation's built-in transitions.
newTransition.setType(transition)
newTransition.setSubtype(KCATransitionFromLeft)
end
# specify an explicit duration for the transition.
newTransition.setDuration(1.0)
# associate the CATransition we've just built with the "subviews" key for this SlideshowView instance,
# so that when we swap ImageView instances in our -transitionToImage: method below (via -replaceSubview:with:).
self.setAnimations(NSDictionary.dictionaryWithObject(newTransition, forKey:"subviews"))
end
def isOpaque
# we're opaque, since we fill with solid black in our -drawRect: method, below.
true
end
def drawRect(rect)
# draw a solid black background by default
NSColor.blackColor.set
NSRectFill(rect)
end
def transitionToImage(newImage)
# create a new NSImageView and swap it into the view in place of our previous NSImageView.
# this will trigger the transition animation we've wired up in -updateSubviewsTransition,
# which fires on changes in the "subviews" property.
@newImageView = NSImageView.alloc.initWithFrame(self.bounds)
@newImageView.setImage(newImage)
@newImageView.setAutoresizingMask(NSViewWidthSizable|NSViewHeightSizable)
if @currentImageView && @newImageView
self.animator.replaceSubview(@currentImageView, with:@newImageView)
else
@currentImageView.animator.removeFromSuperview if @currentImageView
self.animator.addSubview(@newImageView) if @newImageView
end
@currentImageView = @newImageView
end
end | 47.009009 | 146 | 0.753354 |
1ae9e3b53071f1ef9e5d632d453828783cd96760 | 1,388 | class Torchvision < Formula
desc "Datasets, transforms, and models for computer vision"
homepage "https://github.com/pytorch/vision"
url "https://github.com/pytorch/vision/archive/v0.7.0.tar.gz"
sha256 "fa0a6f44a50451115d1499b3f2aa597e0092a07afce1068750260fa7dd2c85cb"
license "BSD-3-Clause"
revision 1
bottle do
cellar :any
sha256 "161fb00bdb69732b97969ecc3131d8d4f78d624091191ad17c8905018786a72d" => :catalina
sha256 "3d348ed59f04bda1e4dccffd531307714cbc596007b7daf96d4ac49e661db68e" => :mojave
sha256 "03e0932e274d856c1d57938d6e4d76a5edbedcc8c7d785141b1a1177494340d2" => :high_sierra
end
depends_on "cmake" => :build
depends_on "[email protected]" => :build
depends_on "libtorch"
def install
mkdir "build" do
system "cmake", "..", *std_cmake_args
system "make"
system "make", "install"
end
pkgshare.install "examples"
end
test do
cp pkgshare/"examples/cpp/hello_world/main.cpp", testpath
libtorch = Formula["libtorch"]
system ENV.cxx, "-std=c++14", "main.cpp", "-o", "test",
"-I#{libtorch.opt_include}",
"-I#{libtorch.opt_include}/torch/csrc/api/include",
"-L#{libtorch.opt_lib}", "-ltorch", "-ltorch_cpu", "-lc10",
"-L#{lib}", "-ltorchvision"
assert_match "[ CPUFloatType{1,1000} ]", shell_output("./test")
end
end
| 34.7 | 93 | 0.673631 |
21e035c21cea7eea830ac9a58c0dc42e59eeed26 | 310 | require 'spec_helper'
describe Locomotive::LiquidExtensions::Filters::Math do
include Locomotive::LiquidExtensions::Filters::Math
describe '#mod' do
it 'it returns correct number modulus' do
mod(4, 4).should eq(0)
mod(4, 8).should eq(4)
mod(8, 4).should eq(0)
end
end
end
| 17.222222 | 55 | 0.664516 |
b90a331d28b00df78fab561594e89244258ebb6f | 745 | # frozen_string_literal: true
module Bundler
# SourceList object to be used while parsing the Gemfile, setting the
# approptiate options to be used with Source classes for plugin installation
module Plugin
class SourceList < Bundler::SourceList
def add_git_source(options = {})
add_source_to_list Plugin::Installer::Git.new(options), git_sources
end
def add_rubygems_source(options = {})
add_source_to_list Plugin::Installer::Rubygems.new(options), @rubygems_sources
end
def all_sources
path_sources + git_sources + rubygems_sources + [metadata_source]
end
private
def rubygems_aggregate_class
Plugin::Installer::Rubygems
end
end
end
end
| 26.607143 | 86 | 0.704698 |
4a55ce1d700ef7a9c6334bfe1804f0dd08357e41 | 3,192 | #
# Author:: Adam Edwards (<[email protected]>)
#
# Copyright:: Copyright 2014-2016, 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 "chef/dsl/powershell"
class Chef
class Resource
class DscResource < Chef::Resource
provides :dsc_resource, os: "windows"
# This class will check if the object responds to
# to_text. If it does, it will call that as opposed
# to inspect. This is useful for properties that hold
# objects such as PsCredential, where we do not want
# to dump the actual ivars
class ToTextHash < Hash
def to_text
descriptions = self.map do |(property, obj)|
obj_text = if obj.respond_to?(:to_text)
obj.to_text
else
obj.inspect
end
"#{property}=>#{obj_text}"
end
"{#{descriptions.join(', ')}}"
end
end
include Chef::DSL::Powershell
default_action :run
def initialize(name, run_context)
super
@properties = ToTextHash.new
@resource = nil
@reboot_action = :nothing
end
def resource(value = nil)
if value
@resource = value
else
@resource
end
end
def module_name(value = nil)
if value
@module_name = value
else
@module_name
end
end
def property(property_name, value = nil)
if not property_name.is_a?(Symbol)
raise TypeError, "A property name of type Symbol must be specified, '#{property_name}' of type #{property_name.class} was given"
end
if value.nil?
value_of(@properties[property_name])
else
@properties[property_name] = value
end
end
def properties
@properties.reduce({}) do |memo, (k, v)|
memo[k] = value_of(v)
memo
end
end
# This property takes the action message for the reboot resource
# If the set method of the DSC resource indicate that a reboot
# is necessary, reboot_action provides the mechanism for a reboot to
# be requested.
def reboot_action(value = nil)
if value
@reboot_action = value
else
@reboot_action
end
end
def timeout(arg = nil)
set_or_return(
:timeout,
arg,
:kind_of => [ Integer ],
)
end
private
def value_of(value)
if value.is_a?(DelayedEvaluator)
value.call
else
value
end
end
end
end
end
| 26.163934 | 138 | 0.58396 |
4a907e5d090e5cf8b5e60ae503c72119c949636f | 777 | require "language/node"
class Cdk8s < Formula
desc "Define k8s native apps and abstractions using object-oriented programming"
homepage "https://cdk8s.io/"
url "https://registry.npmjs.org/cdk8s-cli/-/cdk8s-cli-1.0.9.tgz"
sha256 "736297d3ced8510821f53c95834a9c226d53a1b089a955f0b8ccb147d24a21da"
license "Apache-2.0"
bottle do
sha256 cellar: :any_skip_relocation, all: "c29ada5a0a5a1d3263700733152de8bed9ae90071c28814525b0418773ed8ea0"
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
assert_match "Cannot initialize a project in a non-empty directory",
shell_output("#{bin}/cdk8s init python-app 2>&1", 1)
end
end
| 29.884615 | 112 | 0.747748 |
e2491dfdb13404960c1475f0ee68a023d4726447 | 1,327 | $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
require "sql_builder"
require "minitest/autorun"
require "active_record"
class Minitest::Test
# Config
db_config = YAML::load(File.open('test/config/database.yml'))
db_config_admin = db_config.merge({'database' => 'postgres', 'schema_search_path' => 'public'})
# Delete DB
ActiveRecord::Base.establish_connection(db_config_admin)
ActiveRecord::Base.connection.drop_database(db_config["database"])
puts "Database deleted."
# Create DB
ActiveRecord::Base.establish_connection(db_config_admin)
ActiveRecord::Base.connection.create_database(db_config["database"])
puts "Database created."
# ~LOCATIONS Table~
# Columns
# +-------------------+-------------------+---------------+
# | id | int | primary key |
# | name | text | |
# +-------------------+-------------------+---------------+
# Populate DB
ActiveRecord::Base.establish_connection(db_config)
create_table = 'CREATE TABLE locations ( id int primary key, name text)'
ActiveRecord::Base.connection.execute(create_table)
0.upto(100) do |i|
ActiveRecord::Base.connection.execute("INSERT INTO locations (id, name) VALUES (#{i}, 'location_#{i}');")
end
puts "Database populated."
end
| 35.864865 | 109 | 0.619442 |
e99512d59c2c2b8b137152aa309af5fb989f580c | 2,944 | # frozen_string_literal: true
module Bullet
module Dependency
def mongoid?
@mongoid ||= defined? ::Mongoid
end
def active_record?
@active_record ||= defined? ::ActiveRecord
end
def rails?
@rails ||= defined? ::Rails
end
def active_record_version
@active_record_version ||= begin
if active_record40?
'active_record4'
elsif active_record41?
'active_record41'
elsif active_record42?
'active_record42'
elsif active_record50?
'active_record5'
elsif active_record51?
'active_record5'
elsif active_record52?
'active_record52'
else
raise "Bullet does not support active_record #{::ActiveRecord::VERSION::STRING} yet"
end
end
end
def mongoid_version
@mongoid_version ||= begin
if mongoid4x?
'mongoid4x'
elsif mongoid5x?
'mongoid5x'
elsif mongoid6x?
'mongoid6x'
elsif mongoid7x?
'mongoid7x'
else
raise "Bullet does not support mongoid #{::Mongoid::VERSION} yet"
end
end
end
def active_record4?
active_record? && ::ActiveRecord::VERSION::MAJOR == 4
end
def active_record5?
active_record? && ::ActiveRecord::VERSION::MAJOR == 5
end
def active_record40?
active_record4? && ::ActiveRecord::VERSION::MINOR == 0
end
def active_record41?
active_record4? && ::ActiveRecord::VERSION::MINOR == 1
end
def active_record42?
active_record4? && ::ActiveRecord::VERSION::MINOR == 2
end
def active_record50?
active_record5? && ::ActiveRecord::VERSION::MINOR == 0
end
def active_record51?
active_record5? && ::ActiveRecord::VERSION::MINOR == 1
end
def active_record52?
true
# active_record5? && ::ActiveRecord::VERSION::MINOR == 2
end
def mongoid4x?
mongoid? && ::Mongoid::VERSION =~ /\A4/
end
def mongoid5x?
mongoid? && ::Mongoid::VERSION =~ /\A5/
end
def mongoid6x?
mongoid? && ::Mongoid::VERSION =~ /\A6/
end
def mongoid7x?
mongoid? && ::Mongoid::VERSION =~ /\A7/
end
end
end
| 28.582524 | 121 | 0.450408 |
26c7fd1a8e6fc405dd12d77f216e21211ec44eb8 | 1,777 | =begin
#Fatture in Cloud API v2 - API Reference
#Connect your software with Fatture in Cloud, the invoicing platform chosen by more than 400.000 businesses in Italy. The Fatture in Cloud API is based on REST, and makes possible to interact with the user related data prior authorization via OAuth2 protocol.
The version of the OpenAPI document: 2.0.7
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.3.0
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for FattureInCloud_Ruby_Sdk::CompanyInfoAccessInfo
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe FattureInCloud_Ruby_Sdk::CompanyInfoAccessInfo do
instance = FattureInCloud_Ruby_Sdk::CompanyInfoAccessInfo.new
describe 'test an instance of CompanyInfoAccessInfo' do
it 'should create an instance of CompanyInfoAccessInfo' do
expect(instance).to be_instance_of(FattureInCloud_Ruby_Sdk::CompanyInfoAccessInfo)
instance.role = "master"
instance.through_accountant = false
instance.permissions = {
fic_situation: "read",
fic_clients: "write",
fic_suppliers: "write",
fic_products: "write",
fic_issued_documents: "detailed"
}
end
end
describe 'test attribute "role"' do
it 'should work' do
expect(instance.role).to be_a_kind_of(String)
end
end
describe 'test attribute "permissions"' do
it 'should work' do
expect(instance.permissions).to be_a_kind_of(Object)
end
end
describe 'test attribute "through_accountant"' do
it 'should work' do
expect(instance.through_accountant).to be(true).or be(false)
end
end
end
| 31.732143 | 261 | 0.73776 |
33534aa8e60b86f71a7df80414a97a1b7004648e | 331 | # typed: strict
# frozen_string_literal: true
require "simplecov"
require "simplecov-cobertura"
require "sorbet-runtime"
SimpleCov.start do
T.bind(self, T.class_of(SimpleCov))
formatter SimpleCov::Formatter::CoberturaFormatter
end
$LOAD_PATH.unshift File.expand_path("../lib", __dir__)
require "kapsule"
require "test-unit"
| 20.6875 | 54 | 0.779456 |
031402848d2f4bd758f5ff0e23463175299d208b | 331 | class CreateDeposits < ActiveRecord::Migration[5.1]
def change
create_table :deposits do |t|
t.string :type
t.string :amount
t.string :status
t.string :depositors_name
t.datetime :date
t.integer :account_id
t.references :user, foreign_key: true
t.timestamps
end
end
end
| 20.6875 | 51 | 0.646526 |
1c02058ebf9ae132801aecf065ad0a9da0e13d5e | 421 | class ReviewsController < ApplicationController
def create
@mixtape = Mixtape.find(params[:mixtape_id])
@review = @mixtape.reviews.new(review_params)
if @review.save
redirect_to mixtape_path(@mixtape)
else
flash[:notice] = "Please fill in your review"
redirect_to mixtape_path(@mixtape)
end
end
private
def review_params
params.require(:review).permit(:content)
end
end
| 23.388889 | 51 | 0.707838 |
7addd20a8652fa0efd03889347eb6fd5b8d00182 | 147 | # -*- encoding : utf-8 -*-
class HallOfFamesController < ApplicationController
def show
# wird intern mit fragment-cache gecached
end
end | 18.375 | 51 | 0.721088 |
f7852e617607e499443c6507e92de03b92039e52 | 93 | # coding: utf-8
# vim: et ts=2 sw=2
RSpec.describe HrrRbSsh::Error::ClosedConnection do
end
| 15.5 | 51 | 0.731183 |
ab867ba17983278a819ec0d7afc9093a156a56c3 | 97 | status :draft
multiple_choice :q1? do
option yes: :done
option no: :done
end
outcome :done
| 10.777778 | 23 | 0.71134 |
abddb73c7a98d54f5b2d0279ba1a0653654ccf53 | 3,858 | require 'manageiq-api-client'
module InterRegionApiMethodRelay
class InterRegionApiMethodRelayError < RuntimeError; end
INITIAL_INSTANCE_WAIT = 1.second
MAX_INSTANCE_WAIT = 1.minute
def self.extended(klass)
unless klass.const_defined?("InstanceMethodRelay")
instance_relay = klass.const_set("InstanceMethodRelay", Module.new)
klass.prepend(instance_relay)
end
unless klass.const_defined?("ClassMethodRelay")
class_relay = klass.const_set("ClassMethodRelay", Module.new)
klass.singleton_class.prepend(class_relay)
end
end
def api_relay_method(method, action = method)
relay = const_get("InstanceMethodRelay")
collection_name = collection_for_class
relay.class_eval do
define_method(method) do |*meth_args, &meth_block|
api_args = yield(*meth_args) if block_given?
if in_current_region?
super(*meth_args, &meth_block)
else
InterRegionApiMethodRelay.exec_api_call(region_number, collection_name, action, api_args, id)
end
end
end
end
def api_relay_class_method(method, action = method)
relay = const_get("ClassMethodRelay")
collection_name = collection_for_class
raise ArgumentError, "A block is required to determine target object region and API arguments" unless block_given?
relay.class_eval do
define_method(method) do |*meth_args, &meth_block|
record_id, api_args = yield(*meth_args)
if record_id.nil? || id_in_current_region?(record_id)
super(*meth_args, &meth_block)
else
InterRegionApiMethodRelay.exec_api_call(id_to_region(record_id), collection_name, action, api_args)
end
end
end
end
def self.api_client_connection_for_region(region_number, user = User.current_userid)
region = MiqRegion.find_by(:region => region_number)
url = region.remote_ws_url
if url.nil?
_log.error("The remote region [#{region_number}] does not have a web service address.")
raise "Failed to establish API connection to region #{region_number}"
end
ManageIQ::API::Client.new(
:url => url,
:miqtoken => region.api_system_auth_token(user),
:ssl => {:verify => false}
)
end
def self.exec_api_call(region, collection_name, action, api_args = nil, id = nil)
api_args ||= {}
collection = api_client_connection_for_region(region).public_send(collection_name)
collection_or_instance = id ? collection.find(id) : collection
result = collection_or_instance.public_send(action, api_args)
case result
when ManageIQ::API::Client::ActionResult
raise InterRegionApiMethodRelayError, result.message if result.failed?
result.attributes
when ManageIQ::API::Client::Resource
instance_for_resource(result)
when Hash
# Some of API invocation returning Hash object
# Example: retire_resource for Service
_log.warn("remote API invocation returned Hash object")
result
else
raise InterRegionApiMethodRelayError, "Got unexpected API result object #{result.class}"
end
end
def self.instance_for_resource(resource)
klass = Api::CollectionConfig.new.klass(resource.collection.name)
wait = INITIAL_INSTANCE_WAIT
while wait < MAX_INSTANCE_WAIT
instance = klass.find_by(:id => resource.id)
return instance if instance
sleep(wait)
wait *= 2
end
raise InterRegionApiMethodRelayError, "Failed to retrieve #{klass} instance with id #{resource.id}"
end
private
def collection_for_class
collection_name = Api::CollectionConfig.new.name_for_klass(self)
unless collection_name
_log.error("No API endpoint found for class #{name}")
raise NotImplementedError, "No API endpoint found for class #{name}"
end
collection_name
end
end
| 32.694915 | 118 | 0.712545 |
87b4278dbf59644fb0078bd763dd203b61710cbd | 2,455 | module ActsAsFerret #:nodoc:
# this class is not threadsafe
class MultiIndex
def initialize(model_classes, options = {})
@model_classes = model_classes
# ensure all models indexes exist
@model_classes.each { |m| m.aaf_index.ensure_index_exists }
default_fields = @model_classes.inject([]) do |fields, c|
fields + c.aaf_configuration[:ferret][:default_field]
end
@options = {
:default_field => default_fields
}.update(options)
end
def search(query, options={})
#puts "querystring: #{query.to_s}"
query = process_query(query)
#puts "parsed query: #{query.to_s}"
searcher.search(query, options)
end
def search_each(query, options = {}, &block)
query = process_query(query)
searcher.search_each(query, options, &block)
end
# checks if all our sub-searchers still are up to date
def latest?
return false unless @reader
# segfaults with 0.10.4 --> TODO report as bug @reader.latest?
@sub_readers.each do |r|
return false unless r.latest?
end
true
end
def searcher
ensure_searcher
@searcher
end
def doc(i)
searcher[i]
end
alias :[] :doc
def query_parser
@query_parser ||= Ferret::QueryParser.new(@options)
end
def process_query(query)
query = query_parser.parse(query) if query.is_a?(String)
return query
end
def close
@searcher.close if @searcher
@reader.close if @reader
end
protected
def ensure_searcher
unless latest?
@sub_readers = @model_classes.map { |clazz|
begin
reader = Ferret::Index::IndexReader.new(clazz.aaf_configuration[:index_dir])
rescue Exception
puts "error opening #{clazz.aaf_configuration[:index_dir]}: #{$!}"
end
reader
}
close
@reader = Ferret::Index::IndexReader.new(@sub_readers)
@searcher = Ferret::Search::Searcher.new(@reader)
end
end
end # of class MultiIndex
end
| 28.882353 | 94 | 0.526273 |
4a10fcd5a694e9f602b3cbeb2839acdba14a991a | 1,437 | # -*- coding: utf-8 -*-
#
#--
# Copyright (C) 2009-2014 Thomas Leitner <[email protected]>
#
# This file is part of kramdown which is licensed under the MIT.
#++
#
require 'kramdown/parser/kramdown/block_boundary'
module Kramdown
module Parser
class Kramdown
BLOCK_MATH_START = /^#{OPT_SPACE}(\\)?\$\$(.*?)\$\$(\s*?\n)?/m
# Parse the math block at the current location.
def parse_block_math
start_line_number = @src.current_line_number
if !after_block_boundary?
return false
elsif @src[1]
@src.scan(/^#{OPT_SPACE}\\/) if @src[3]
return false
end
orig_pos = @src.pos
@src.pos += @src.matched_size
data = @src[2]
if before_block_boundary?
@tree.children << new_block_el(:math, data, nil, :category => :block, :location => start_line_number)
true
else
@src.pos = orig_pos
false
end
end
define_parser(:block_math, BLOCK_MATH_START)
INLINE_MATH_START = /\$\$(.*?)\$\$/m
# Parse the inline math at the current location.
def parse_inline_math
start_line_number = @src.current_line_number
@src.pos += @src.matched_size
@tree.children << Element.new(:math, @src[1], nil, :category => :span, :location => start_line_number)
end
define_parser(:inline_math, INLINE_MATH_START, '\$')
end
end
end
| 26.127273 | 111 | 0.597077 |
e81ab95f643aae4a87e11cb81bd0ffe3654cd12d | 1,061 | class UsersController < ApplicationController
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
#Can't create a user without a privilege
#def new
# @user = User.new
#end
#def create
# @user = User.new(user_params)
# if @user.save
# flash[:success] = "Welcome to the Class Portal!"
# redirect_to @user
# else
# render 'new'
# end
#end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
flash[:success] = "Welcome to the Class Portal!"
redirect_to @user
else
render 'new'
end
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
flash[:success] = "Edited!"
redirect_to @user
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end
| 18.293103 | 60 | 0.584354 |
08a67290ff5cfeac060ab244f1bbb8f35cd0c469 | 274 | class ChangeConversationCachesToText < ActiveRecord::Migration
def change
change_column :conversations, :message_summary_cache, :text
change_column :conversations, :participant_names_cache, :text
change_column :conversations, :muter_ids_cache, :text
end
end
| 34.25 | 65 | 0.80292 |
186799b654b565480680463b1a8c38ee2a26891b | 330 | class FontTradeWinds < Formula
head "https://github.com/google/fonts/raw/main/ofl/tradewinds/TradeWinds-Regular.ttf", verified: "github.com/google/fonts/"
desc "Trade Winds"
homepage "https://fonts.google.com/specimen/Trade+Winds"
def install
(share/"fonts").install "TradeWinds-Regular.ttf"
end
test do
end
end
| 30 | 125 | 0.739394 |
1c376c393df9312d907069b3d144aa44966dfdf4 | 1,975 | class Htmlcleaner < Formula
desc "HTML parser written in Java"
homepage "https://htmlcleaner.sourceforge.io"
url "https://downloads.sourceforge.net/project/htmlcleaner/htmlcleaner/htmlcleaner%20v2.24/htmlcleaner-2.24-src.zip"
sha256 "ee476c1f31eabcbd56c174ec482910e1b19907ad3e57dff9a4d0a2f456c9cd42"
license "BSD-3-Clause"
revision 1
bottle do
rebuild 1
sha256 cellar: :any_skip_relocation, arm64_big_sur: "f589e5b99a7d2443607e863555978b07e7c6fe30d9e7c8b536583dfcf87713e4"
sha256 cellar: :any_skip_relocation, big_sur: "e2d3b97f42d5d1442dc129bc32f56db6319caf5a58c54946f498862cf03b474f"
sha256 cellar: :any_skip_relocation, catalina: "1676af315722a63de9c45daf78e747fd2653e72682bf6c8cb3a22c5262f762d4"
sha256 cellar: :any_skip_relocation, mojave: "112f63a58175f8ab10dc077490a4704a18cefe190fb617f511a441f391cdbeac"
sha256 cellar: :any_skip_relocation, high_sierra: "af704dd8dba231d424e0145132f4dab9c93c94d8699267eb3eace5fe90e57623"
sha256 cellar: :any_skip_relocation, x86_64_linux: "901fee537dbb530c527662eba13e0f32a20642911d5adcec7ab58ff7ae1b7f89"
end
depends_on "maven" => :build
depends_on "openjdk"
def install
ENV["JAVA_HOME"] = Formula["openjdk"].opt_prefix
inreplace "pom.xml" do |s|
# Homebrew's OpenJDK no longer accepts Java 5 source
s.gsub! "<source>1.5</source>", "<source>1.7</source>"
s.gsub! "<target>1.5</target>", "<target>1.7</target>"
# OpenJDK >14 doesn't support older maven-javadoc-plugin versions
s.gsub! "<version>2.9</version>", "<version>3.2.0</version>"
end
system "mvn", "clean", "package", "-DskipTests=true", "-Dmaven.javadoc.skip=true"
libexec.install Dir["target/htmlcleaner-*.jar"]
bin.write_jar_script libexec/"htmlcleaner-#{version}.jar", "htmlcleaner"
end
test do
path = testpath/"index.html"
path.write "<html>"
assert_match "</html>", shell_output("#{bin}/htmlcleaner src=#{path}")
end
end
| 44.886364 | 122 | 0.748354 |
87dd6eb28e5cdac669ac17f5c22fe22d73981670 | 55 | json.partial! "documents/document", document: @document | 55 | 55 | 0.8 |
bf160121ea09359f2d0f21527d961d8e7d92dc36 | 1,053 | # frozen_string_literal: true
class Schools::BaseController < ApplicationController
include Pundit
before_action :authenticate_user!
before_action :ensure_school_user
before_action :set_paper_trail_whodunnit
after_action :verify_authorized
after_action :verify_policy_scoped
layout "school_cohort"
private
def ensure_school_user
raise Pundit::NotAuthorizedError, "Forbidden" unless current_user.induction_coordinator?
authorize(active_school, :show?) if active_school.present?
end
def active_school
return if params[:school_id].blank?
School.friendly.find(params[:school_id])
end
def active_cohort
return if params[:cohort_id].blank?
Cohort.find_by(start_year: params[:cohort_id])
end
def set_school_cohort
@school = active_school
@cohort = active_cohort
@school_cohort = policy_scope(SchoolCohort).find_by(
cohort: @cohort,
school: @school,
)
redirect_to schools_choose_programme_path(cohort_id: Cohort.current.start_year) unless @school_cohort
end
end
| 22.891304 | 105 | 0.767331 |
1a2b90310e87489d7c9ab8a6f558c4819dad07ac | 2,371 | require 'r10k/logging'
require 'r10k/puppetfile'
require 'r10k/git/working_dir'
# This class implements an environment based on a Git branch.
#
# @since 1.3.0
class R10K::Environment::Git < R10K::Environment::Base
include R10K::Logging
# @!attribute [r] remote
# @return [String] The URL to the remote git repository
attr_reader :remote
# @!attribute [r] ref
# @return [String] The git reference to use for this environment
attr_reader :ref
# @!attribute [r] working_dir
# @api private
# @return [R10K::Git::WorkingDir] The git working directory backing this environment
attr_reader :working_dir
# @!attribute [r] puppetfile
# @api public
# @return [R10K::Puppetfile] The puppetfile instance associated with this environment
attr_reader :puppetfile
# Initialize the given SVN environment.
#
# @param name [String] The unique name describing this environment.
# @param basedir [String] The base directory where this environment will be created.
# @param dirname [String] The directory name for this environment.
# @param options [Hash] An additional set of options for this environment.
#
# @param options [String] :remote The URL to the remote git repository
# @param options [String] :ref The git reference to use for this environment
def initialize(name, basedir, dirname, options = {})
super
@remote = options[:remote]
@ref = options[:ref]
@working_dir = R10K::Git::WorkingDir.new(@ref, @remote, @basedir, @dirname)
@puppetfile = R10K::Puppetfile.new(@full_path)
end
# Clone or update the given Git environment.
#
# If the environment is being created for the first time, it will
# automatically update all modules to ensure that the environment is complete.
#
# @api public
# @return [void]
def sync
recursive_needed = !(@working_dir.cloned?)
@working_dir.sync
if recursive_needed
logger.debug "Environment #{@full_path} is a fresh clone; automatically updating modules."
sync_modules
end
end
# @api private
def sync_modules
modules.each do |mod|
logger.debug "Deploying module #{mod.name}"
mod.sync
end
end
# @return [Array<R10K::Module::Base>] All modules defined in the Puppetfile
# associated with this environment.
def modules
@puppetfile.load
@puppetfile.modules
end
end
| 29.6375 | 96 | 0.703922 |
f84f2c21cdacfa8579cb017c9a755f41feab6259 | 10,418 | module Csvlint
class Validator
include Csvlint::ErrorCollector
attr_reader :encoding, :content_type, :extension, :headers, :line_breaks, :dialect, :csv_header, :schema, :data
ERROR_MATCHERS = {
"Missing or stray quote" => :stray_quote,
"Illegal quoting" => :whitespace,
"Unclosed quoted field" => :unclosed_quote,
}
def initialize(source, dialect = nil, schema = nil, options = {})
@source = source
@formats = []
@schema = schema
@supplied_dialect = dialect != nil
@dialect = {
"header" => true,
"delimiter" => ",",
"skipInitialSpace" => true,
"lineTerminator" => :auto,
"quoteChar" => '"'
}.merge(dialect || {})
@csv_header = @dialect["header"]
@limit_lines = options[:limit_lines]
@limit_errors = options[:limit_errors]
@use_data = options[:use_data].nil? ? true : options[:use_data]
@csv_options = dialect_to_csv_options(@dialect)
@extension = parse_extension(source)
reset
validate
end
def validate
single_col = false
io = nil
begin
io = @source.respond_to?(:gets) ? @source : open(@source, :allow_redirections=>:all)
validate_metadata(io)
parse_csv(io)
sum = @col_counts.inject(:+)
unless sum.nil?
build_warnings(:title_row, :structure) if @col_counts.first < (sum / @col_counts.size.to_f)
end
build_warnings(:check_options, :structure) if @expected_columns == 1
check_consistency
rescue OpenURI::HTTPError, Errno::ENOENT
build_errors(:not_found)
ensure
io.close if io && io.respond_to?(:close)
end
end
def validate_metadata(io)
@encoding = io.charset rescue nil
@content_type = io.content_type rescue nil
@headers = io.meta rescue nil
assumed_header = undeclared_header = !@supplied_dialect
if @headers
if @headers["content-type"] =~ /text\/csv/
@csv_header = true
undeclared_header = false
assumed_header = true
end
if @headers["content-type"] =~ /header=(present|absent)/
@csv_header = true if $1 == "present"
@csv_header = false if $1 == "absent"
undeclared_header = false
assumed_header = false
end
if @headers["content-type"] !~ /charset=/
build_warnings(:no_encoding, :context)
else
build_warnings(:encoding, :context) if @encoding != "utf-8"
end
build_warnings(:no_content_type, :context) if @content_type == nil
build_warnings(:excel, :context) if @content_type == nil && @extension =~ /.xls(x)?/
build_errors(:wrong_content_type, :context) unless (@content_type && @content_type =~ /text\/csv/)
if undeclared_header
build_errors(:undeclared_header, :structure)
assumed_header = false
end
end
build_info_messages(:assumed_header, :structure) if assumed_header
end
def parse_csv(io)
@expected_columns = 0
current_line = 0
reported_invalid_encoding = false
@col_counts = []
@csv_options[:encoding] = @encoding
begin
wrapper = WrappedIO.new( io )
csv = CSV.new( wrapper, @csv_options )
@data = []
@line_breaks = csv.row_sep
if @line_breaks != "\r\n"
build_info_messages(:nonrfc_line_breaks, :structure)
end
row = nil
loop do
current_line += 1
if (@limit_lines && current_line > @limit_lines) || (@limit_errors && @errors.size >= @limit_errors)
break
end
begin
wrapper.reset_line
row = csv.shift
if @use_data
@data << row
end
if row
if current_line == 1 && header?
row = row.reject {|r| r.blank? }
validate_header(row)
@col_counts << row.size
else
build_formats(row)
@col_counts << row.reject {|r| r.blank? }.size
@expected_columns = row.size unless @expected_columns != 0
build_errors(:blank_rows, :structure, current_line, nil, wrapper.line) if row.reject{ |c| c.nil? || c.empty? }.size == 0
if @schema
@schema.validate_row(row, current_line)
@errors += @schema.errors
@warnings += @schema.warnings
else
build_errors(:ragged_rows, :structure, current_line, nil, wrapper.line) if !row.empty? && row.size != @expected_columns
end
end
else
break
end
rescue CSV::MalformedCSVError => e
type = fetch_error(e)
if type == :stray_quote && !wrapper.line.match(csv.row_sep)
build_errors(:line_breaks, :structure)
else
build_errors(type, :structure, current_line, nil, wrapper.line)
end
end
end
rescue ArgumentError => ae
build_errors(:invalid_encoding, :structure, current_line, wrapper.line) unless reported_invalid_encoding
reported_invalid_encoding = true
end
end
def validate_header(header)
names = Set.new
header.each_with_index do |name,i|
build_warnings(:empty_column_name, :schema, nil, i+1) if name == ""
if names.include?(name)
build_warnings(:duplicate_column_name, :schema, nil, i+1)
else
names << name
end
end
if @schema
@schema.validate_header(header)
@errors += @schema.errors
@warnings += @schema.warnings
end
return valid?
end
def header?
@csv_header
end
def fetch_error(error)
e = error.message.match(/^([a-z ]+) (i|o)n line ([0-9]+)\.?$/i)
message = e[1] rescue nil
ERROR_MATCHERS.fetch(message, :unknown_error)
end
def dialect_to_csv_options(dialect)
skipinitialspace = dialect["skipInitialSpace"] || true
delimiter = dialect["delimiter"]
delimiter = delimiter + " " if !skipinitialspace
return {
:col_sep => delimiter,
:row_sep => dialect["lineTerminator"],
:quote_char => dialect["quoteChar"],
:skip_blanks => false
}
end
def build_formats(row)
row.each_with_index do |col, i|
next if col.blank?
@formats[i] ||= Hash.new(0)
format = if col.strip[FORMATS[:numeric]]
if col[FORMATS[:date_number]] && date_format?(Date, col, '%Y%m%d')
:date_number
elsif col[FORMATS[:dateTime_number]] && date_format?(Time, col, '%Y%m%d%H%M%S')
:dateTime_number
elsif col[FORMATS[:dateTime_nsec]] && date_format?(Time, col, '%Y%m%d%H%M%S%N')
:dateTime_nsec
else
:numeric
end
elsif uri?(col)
:uri
elsif col[FORMATS[:date_db]] && date_format?(Date, col, '%Y-%m-%d')
:date_db
elsif col[FORMATS[:date_short]] && date_format?(Date, col, '%e %b')
:date_short
elsif col[FORMATS[:date_rfc822]] && date_format?(Date, col, '%e %b %Y')
:date_rfc822
elsif col[FORMATS[:date_long]] && date_format?(Date, col, '%B %e, %Y')
:date_long
elsif col[FORMATS[:dateTime_time]] && date_format?(Time, col, '%H:%M')
:dateTime_time
elsif col[FORMATS[:dateTime_hms]] && date_format?(Time, col, '%H:%M:%S')
:dateTime_hms
elsif col[FORMATS[:dateTime_db]] && date_format?(Time, col, '%Y-%m-%d %H:%M:%S')
:dateTime_db
elsif col[FORMATS[:dateTime_iso8601]] && date_format?(Time, col, '%Y-%m-%dT%H:%M:%SZ')
:dateTime_iso8601
elsif col[FORMATS[:dateTime_short]] && date_format?(Time, col, '%d %b %H:%M')
:dateTime_short
elsif col[FORMATS[:dateTime_long]] && date_format?(Time, col, '%B %d, %Y %H:%M')
:dateTime_long
else
:string
end
@formats[i][format] += 1
end
end
def check_consistency
@formats.each_with_index do |format,i|
if format
total = format.values.reduce(:+).to_f
if format.none?{|_,count| count / total >= 0.9}
build_warnings(:inconsistent_values, :schema, nil, i + 1)
end
end
end
end
private
def parse_extension(source)
case source
when File
return File.extname( source.path )
when IO
return ""
when StringIO
return ""
when Tempfile
return ""
else
parsed = URI.parse(source)
File.extname(parsed.path)
end
end
def uri?(value)
if value.strip[FORMATS[:uri]]
uri = URI.parse(value)
uri.kind_of?(URI::HTTP) || uri.kind_of?(URI::HTTPS)
end
rescue URI::InvalidURIError
false
end
def date_format?(klass, value, format)
klass.strptime(value, format).strftime(format) == value
rescue ArgumentError # invalid date
false
end
FORMATS = {
:string => nil,
:numeric => /\A[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?\z/,
:uri => /\Ahttps?:/,
:date_db => /\A\d{4,}-\d\d-\d\d\z/,
:date_long => /\A(?:#{Date::MONTHNAMES.join('|')}) [ \d]\d, \d{4,}\z/,
:date_number => /\A\d{8}\z/,
:date_rfc822 => /\A[ \d]\d (?:#{Date::ABBR_MONTHNAMES.join('|')}) \d{4,}\z/,
:date_short => /\A[ \d]\d (?:#{Date::ABBR_MONTHNAMES.join('|')})\z/,
:dateTime_db => /\A\d{4,}-\d\d-\d\d \d\d:\d\d:\d\d\z/,
:dateTime_hms => /\A\d\d:\d\d:\d\d\z/,
:dateTime_iso8601 => /\A\d{4,}-\d\d-\d\dT\d\d:\d\d:\d\dZ\z/,
:dateTime_long => /\A(?:#{Date::MONTHNAMES.join('|')}) \d\d, \d{4,} \d\d:\d\d\z/,
:dateTime_nsec => /\A\d{23}\z/,
:dateTime_number => /\A\d{14}\z/,
:dateTime_short => /\A\d\d (?:#{Date::ABBR_MONTHNAMES.join('|')}) \d\d:\d\d\z/,
:dateTime_time => /\A\d\d:\d\d\z/,
}.freeze
end
end
| 33.391026 | 136 | 0.540603 |
2160b3136d1dd0375757843d18264039345e4df3 | 230 | class Reminder < ApplicationRecord
validates_presence_of :body
belongs_to :user , :foreign_key => 'sender'
belongs_to :to_user, :class_name=>"User",:foreign_key => 'recipient'
cattr_reader :per_page
@@per_page = 12
end
| 25.555556 | 70 | 0.73913 |
2848e1b66895bf8622ff844092bac4a5b702264f | 78 | require 'multitagger'
puts Multitagger.tagger(:clarifai).tag("/tmp/cat.jpg")
| 19.5 | 54 | 0.75641 |
b985579bce41437d6dc5c89189823389ea2b75d4 | 6,172 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Capybara::Server do
it "should spool up a rack server" do
@app = proc { |env| [200, {}, ["Hello Server!"]]}
@server = Capybara::Server.new(@app).boot
@res = Net::HTTP.start(@server.host, @server.port) { |http| http.get('/') }
expect(@res.body).to include('Hello Server')
end
it "should do nothing when no server given" do
expect do
@server = Capybara::Server.new(nil).boot
end.not_to raise_error
end
it "should bind to the specified host" do
begin
app = proc { |env| [200, {}, ['Hello Server!']] }
Capybara.server_host = '127.0.0.1'
server = Capybara::Server.new(app).boot
res = Net::HTTP.get(URI("http://127.0.0.1:#{server.port}"))
expect(res).to eq('Hello Server!')
Capybara.server_host = '0.0.0.0'
server = Capybara::Server.new(app).boot
res = Net::HTTP.get(URI("http://127.0.0.1:#{server.port}"))
expect(res).to eq('Hello Server!')
ensure
Capybara.server_host = nil
end
end unless ENV['TRAVIS'] and (RUBY_ENGINE == 'jruby') #TODO travis with jruby in container mode has an issue with this test
it "should use specified port" do
Capybara.server_port = 22789
@app = proc { |env| [200, {}, ["Hello Server!"]]}
@server = Capybara::Server.new(@app).boot
@res = Net::HTTP.start(@server.host, 22789) { |http| http.get('/') }
expect(@res.body).to include('Hello Server')
Capybara.server_port = nil
end
it "should use given port" do
@app = proc { |env| [200, {}, ["Hello Server!"]]}
@server = Capybara::Server.new(@app, 22790).boot
@res = Net::HTTP.start(@server.host, 22790) { |http| http.get('/') }
expect(@res.body).to include('Hello Server')
Capybara.server_port = nil
end
it "should find an available port" do
@app1 = proc { |env| [200, {}, ["Hello Server!"]]}
@app2 = proc { |env| [200, {}, ["Hello Second Server!"]]}
@server1 = Capybara::Server.new(@app1).boot
@server2 = Capybara::Server.new(@app2).boot
@res1 = Net::HTTP.start(@server1.host, @server1.port) { |http| http.get('/') }
expect(@res1.body).to include('Hello Server')
@res2 = Net::HTTP.start(@server2.host, @server2.port) { |http| http.get('/') }
expect(@res2.body).to include('Hello Second Server')
end
context "When Capybara.reuse_server is true" do
before do
@old_reuse_server = Capybara.reuse_server
Capybara.reuse_server = true
end
after do
Capybara.reuse_server = @old_reuse_server
end
it "should use the existing server if it already running" do
@app = proc { |env| [200, {}, ["Hello Server!"]]}
@server1 = Capybara::Server.new(@app).boot
@server2 = Capybara::Server.new(@app).boot
res = Net::HTTP.start(@server1.host, @server1.port) { |http| http.get('/') }
expect(res.body).to include('Hello Server')
res = Net::HTTP.start(@server2.host, @server2.port) { |http| http.get('/') }
expect(res.body).to include('Hello Server')
expect(@server1.port).to eq(@server2.port)
end
it "detects and waits for all reused server sessions pending requests" do
done = false
app = proc do |env|
request = Rack::Request.new(env)
sleep request.params['wait_time'].to_f
done = true
[200, {}, ["Hello Server!"]]
end
server1 = Capybara::Server.new(app).boot
server2 = Capybara::Server.new(app).boot
start_request(server1, 0.5)
start_request(server2, 1.0)
expect {
server1.wait_for_pending_requests
}.to change{done}.from(false).to(true)
expect(server2.send(:pending_requests?)).to eq(false)
end
end
context "When Capybara.reuse_server is false" do
before do
@old_reuse_server = Capybara.reuse_server
Capybara.reuse_server = false
end
after do
Capybara.reuse_server = @old_reuse_server
end
it "should not reuse an already running server" do
@app = proc { |env| [200, {}, ["Hello Server!"]]}
@server1 = Capybara::Server.new(@app).boot
@server2 = Capybara::Server.new(@app).boot
res = Net::HTTP.start(@server1.host, @server1.port) { |http| http.get('/') }
expect(res.body).to include('Hello Server')
res = Net::HTTP.start(@server2.host, @server2.port) { |http| http.get('/') }
expect(res.body).to include('Hello Server')
expect(@server1.port).not_to eq(@server2.port)
end
it "detects and waits for only one sessions pending requests" do
done = false
app = proc do |env|
request = Rack::Request.new(env)
sleep request.params['wait_time'].to_f
done = true
[200, {}, ["Hello Server!"]]
end
server1 = Capybara::Server.new(app).boot
server2 = Capybara::Server.new(app).boot
start_request(server1, 0.5)
start_request(server2, 1.0)
expect {
server1.wait_for_pending_requests
}.to change{done}.from(false).to(true)
expect(server2.send(:pending_requests?)).to eq(true)
end
end
it "should raise server errors when the server errors before the timeout" do
begin
Capybara.server do
sleep 0.1
raise 'kaboom'
end
expect do
Capybara::Server.new(proc {|e|}).boot
end.to raise_error(RuntimeError, 'kaboom')
ensure
# TODO refactor out the defaults so it's reliant on unset state instead of
# a one-time call in capybara.rb
Capybara.server {|app, port| Capybara.run_default_server(app, port)}
end
end
it "is not #responsive? when Net::HTTP raises a SystemCallError" do
app = lambda { [200, {}, ['Hello, world']] }
server = Capybara::Server.new(app)
expect(Net::HTTP).to receive(:start).and_raise(SystemCallError.allocate)
expect(server.responsive?).to eq false
end
def start_request(server, wait_time)
# Start request, but don't wait for it to finish
socket = TCPSocket.new(server.host, server.port)
socket.write "GET /?wait_time=#{wait_time.to_s} HTTP/1.0\r\n\r\n"
socket.close
sleep 0.1
end
end
| 30.107317 | 125 | 0.626215 |
1822a7eea9f78606f7b4ea5fd39f39233d547bfc | 2,354 | module TD::Types
# Represents a filter of user chats.
#
# @attr title [TD::Types::String] The title of the filter; 1-12 characters without line feeds.
# @attr icon_name [TD::Types::String, nil] The icon name for short filter representation.
# If non-empty, must be one of "All", "Unread", "Unmuted", "Bots", "Channels", "Groups", "Private", "Custom",
# "Setup", "Cat", "Crown", "Favorite", "Flower", "Game", "Home", "Love", "Mask", "Party", "Sport", "Study", "Trade",
# "Travel", "Work".
# If empty, use getChatFilterDefaultIconName to get default icon name for the filter.
# @attr pinned_chat_ids [Array<Integer>] The chat identifiers of pinned chats in the filtered chat list.
# @attr included_chat_ids [Array<Integer>] The chat identifiers of always included chats in the filtered chat list.
# @attr excluded_chat_ids [Array<Integer>] The chat identifiers of always excluded chats in the filtered chat list.
# @attr exclude_muted [Boolean] True, if muted chats need to be excluded.
# @attr exclude_read [Boolean] True, if read chats need to be excluded.
# @attr exclude_archived [Boolean] True, if archived chats need to be excluded.
# @attr include_contacts [Boolean] True, if contacts need to be included.
# @attr include_non_contacts [Boolean] True, if non-contact users need to be included.
# @attr include_bots [Boolean] True, if bots need to be included.
# @attr include_groups [Boolean] True, if basic groups and supergroups need to be included.
# @attr include_channels [Boolean] True, if channels need to be included.
class ChatFilter < Base
attribute :title, TD::Types::String
attribute :icon_name, TD::Types::String.optional.default(nil)
attribute :pinned_chat_ids, TD::Types::Array.of(TD::Types::Coercible::Integer)
attribute :included_chat_ids, TD::Types::Array.of(TD::Types::Coercible::Integer)
attribute :excluded_chat_ids, TD::Types::Array.of(TD::Types::Coercible::Integer)
attribute :exclude_muted, TD::Types::Bool
attribute :exclude_read, TD::Types::Bool
attribute :exclude_archived, TD::Types::Bool
attribute :include_contacts, TD::Types::Bool
attribute :include_non_contacts, TD::Types::Bool
attribute :include_bots, TD::Types::Bool
attribute :include_groups, TD::Types::Bool
attribute :include_channels, TD::Types::Bool
end
end
| 63.621622 | 120 | 0.7226 |
798ad065e37cff66cefb47ad2920e366db228c0a | 1,230 | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "health-data-standards"
s.summary = "A library for generating and consuming various healthcare related formats."
s.description = "A library for generating and consuming various healthcare related formats. This includes HITSP C32, ASTM CCR and PQRI."
s.email = "[email protected]"
s.homepage = "https://github.com/projectcypress/health-data-standards"
s.authors = ["Andy Gregorowicz", "Sam Sayer", "Marc Hadley", "Rob Dingwell", "Andre Quina"]
s.license = 'APL 2.0'
s.version = '3.2.11'
s.add_dependency 'rest-client', '~>1.6.7'
s.add_dependency 'erubis', '~> 2.7.0'
s.add_dependency 'mongoid', '~> 3.1.4'
s.add_dependency 'activesupport', '~> 3.2.14'
s.add_dependency 'uuid', '~> 2.3.7'
s.add_dependency 'builder', '~> 3.0.0'
s.add_dependency 'nokogiri', '~> 1.6.0'
s.add_dependency 'rubyzip'
s.add_dependency 'log4r', '~> 1.1.10'
s.add_dependency 'memoist', '~> 0.9.1'
s.files = Dir.glob('lib/**/*.rb') + Dir.glob('templates/**/*.erb') + Dir.glob('lib/**/*.json') + Dir.glob('lib/**/*.erb') + Dir.glob('lib/health-data-standards/tasks/*.rake') +
["Gemfile", "README.md", "Rakefile", "VERSION"]
end
| 41 | 178 | 0.650407 |
91600aba1dac5af05c4c2a524efe4ef4e3a1e4d9 | 2,439 | module TaskMapper::Provider
module Fogbugz
class Project < TaskMapper::Provider::Base::Project
# Public: Creates a new Project based on passed arguments
#
# args - hash of Project values
#
# Returns a new Project
def initialize(*args)
args = args.first if args.is_a?(Array)
super args
end
def id
ixProject.to_i
end
def name
sProject
end
def description
sProject
end
# Public: Copies tickets/comments from one Project onto another.
#
# project - Project whose tickets/comments should be copied onto self
#
# Returns the updated project
def copy(project)
project.tickets.each do |ticket|
copy_ticket = self.ticket!(
:title => ticket.title,
:description => ticket.description
)
ticket.comments.each do |comment|
copy_ticket.comment!(:body => comment.body)
sleep 1
end
end
self
end
def ticket(*options)
if options.first.is_a? Fixnum
Ticket.find_by_id(self.id, options.first)
else
raise "You can only search for a single ticket based on id"
end
end
class << self
# Public: Searches all Projects, selecting those matching the provided
# hash of attributes
#
# attributes - Hash of attributes to use when searching Projects
#
# Returns an Array of matching Projects
def find_by_attributes(attributes = {})
search_by_attribute(find_all, attributes)
end
# Public: Finds a particular Project by it's ID
#
# id - ID of Project to find
#
# Returns the requested Project
def find_by_id(id)
find_by_attributes(:id => id).first
end
# Public: Finds all Projects accessible via the Fogbugz API
#
# Returns an Array containing all Projects
def find_all
api.command(:listProjects).collect do |project|
project[1]['project'].map { |p| self.new p }
end.flatten
end
private
# Private: Shortcut for accessing Fogbugz API instance
#
# Returns Fogbugz API wrapper object
def api
TaskMapper::Provider::Fogbugz.api
end
end
end
end
end
| 26.225806 | 78 | 0.573596 |
876512b12dc6c16db081f22e86039f29c1b8b46d | 129 | class UserEntity < API::Entities::UserBasic
include RequestAwareEntity
expose :path do |user|
user_path(user)
end
end
| 16.125 | 43 | 0.736434 |
ab30f4621f1aa723890e19b1f173701fa4c3f69e | 125 | class RemoveNameFromClients < ActiveRecord::Migration[5.2]
def change
remove_column :clients, :name, :string
end
end
| 20.833333 | 58 | 0.752 |
385e7fb0f0f3a8882a896067b5257fd4ca6f10e9 | 751 | cask "font-iosevka-ss14" do
version "4.1.1"
sha256 "8bd05d7fc4c32f61d40c56064315807fee767b3ae7504a5bf74308cd74c34bdf"
url "https://github.com/be5invis/Iosevka/releases/download/v#{version}/ttc-iosevka-ss14-#{version}.zip"
appcast "https://github.com/be5invis/Iosevka/releases.atom"
name "Iosevka SS14"
desc "Sans-serif, slab-serif, monospace and quasi‑proportional typeface family"
homepage "https://github.com/be5invis/Iosevka/"
font "iosevka-ss14-bold.ttc"
font "iosevka-ss14-extrabold.ttc"
font "iosevka-ss14-extralight.ttc"
font "iosevka-ss14-heavy.ttc"
font "iosevka-ss14-light.ttc"
font "iosevka-ss14-medium.ttc"
font "iosevka-ss14-regular.ttc"
font "iosevka-ss14-semibold.ttc"
font "iosevka-ss14-thin.ttc"
end
| 35.761905 | 105 | 0.757656 |
793f30660979d3f80c64f6aae3674601a79d3b87 | 1,151 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ServicePing::DevopsReport do
let_it_be(:data) { { "conv_index": {} }.to_json }
let_it_be(:subject) { ServicePing::DevopsReport.new(Gitlab::Json.parse(data)) }
let_it_be(:devops_report) { DevOpsReport::Metric.new }
describe '#execute' do
context 'when metric is persisted' do
before do
allow(DevOpsReport::Metric).to receive(:create).and_return(devops_report)
allow(devops_report).to receive(:persisted?).and_return(true)
end
it 'does not call `track_and_raise_for_dev_exception`' do
expect(Gitlab::ErrorTracking).not_to receive(:track_and_raise_for_dev_exception)
subject.execute
end
end
context 'when metric is not persisted' do
before do
allow(DevOpsReport::Metric).to receive(:create).and_return(devops_report)
allow(devops_report).to receive(:persisted?).and_return(false)
end
it 'calls `track_and_raise_for_dev_exception`' do
expect(Gitlab::ErrorTracking).to receive(:track_and_raise_for_dev_exception)
subject.execute
end
end
end
end
| 31.972222 | 88 | 0.707211 |
1c14baae73f9a2dd5ab90c69f9e9b9d80967c817 | 5,632 | =begin
#Hydrogen Integration API
#The Hydrogen Integration API
OpenAPI spec version: 1.3.1
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.21
=end
require 'date'
module IntegrationApi
class AggregationAccountTransactionResponseInternalObjectVO
attr_accessor :body
attr_accessor :message
attr_accessor :status_code
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'body' => :'body',
:'message' => :'message',
:'status_code' => :'status_code'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'body' => :'AggregationAccountTransaction',
:'message' => :'String',
:'status_code' => :'Integer'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.has_key?(:'body')
self.body = attributes[:'body']
end
if attributes.has_key?(:'message')
self.message = attributes[:'message']
end
if attributes.has_key?(:'status_code')
self.status_code = attributes[:'status_code']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
body == o.body &&
message == o.message &&
status_code == o.status_code
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[body, message, status_code].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
value
when :Date
value
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = IntegrationApi.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 28.16 | 107 | 0.615589 |
0382f52637a81f0975aa428a0c1ddc107efac6d4 | 6,628 | #-- encoding: UTF-8
#-- 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.
#++
module Type::Attributes
extend ActiveSupport::Concern
included do
# Allow plugins to define constraints
# that disable a given attribute for this type.
mattr_accessor :attribute_constraints do
{}
end
end
class_methods do
##
# Add a constraint for the given attribute
def add_constraint(attribute, callable)
unless callable.respond_to?(:call)
raise ArgumentError, "Expecting callable object for constraint #{key}"
end
attribute_constraints[attribute.to_sym] = callable
end
##
# Provides a map of all work package form attributes as seen when creating
# or updating a work package. Through this map it can be checked whether or
# not an attribute is required.
#
# E.g.
#
# ::Type.work_package_form_attributes['author'][:required] # => true
#
# @return [Hash{String => Hash}] Map from attribute names to options.
def all_work_package_form_attributes(merge_date: false)
wp_cf_cache_parts = RequestStore.fetch(:wp_cf_max_updated_at_and_count) do
WorkPackageCustomField.pluck(Arel.sql('max(updated_at), count(id)')).flatten
end
OpenProject::Cache.fetch('all_work_package_form_attributes',
*wp_cf_cache_parts,
merge_date) do
calculate_all_work_package_form_attributes(merge_date)
end
end
def translated_work_package_form_attributes(merge_date: false)
all_work_package_form_attributes(merge_date: merge_date)
.each_with_object({}) do |(k, v), hash|
hash[k] = translated_attribute_name(k, v)
end
end
def translated_attribute_name(name, attr)
if attr[:name_source]
attr[:name_source].call
else
attr[:display_name] || attr_translate(name)
end
end
private
def calculate_all_work_package_form_attributes(merge_date)
attributes = calculate_default_work_package_form_attributes
# within the form date is shown as a single entry including start and due
if merge_date
merge_date_for_form_attributes(attributes)
end
add_custom_fields_to_form_attributes(attributes)
attributes
end
def calculate_default_work_package_form_attributes
representable_config = API::V3::WorkPackages::Schema::WorkPackageSchemaRepresenter
.representable_attrs
# For reasons beyond me, Representable::Config contains the definitions
# * nested in [:definitions] in some envs, e.g. development
# * directly in other envs, e.g. test
definitions = representable_config.key?(:definitions) ? representable_config[:definitions] : representable_config
skip = ['_type', '_dependencies', 'attribute_groups', 'links', 'parent_id', 'parent', 'description']
definitions.keys
.reject { |key| skip.include?(key) || definitions[key][:required] }
.map { |key| [key, JSON::parse(definitions[key].to_json)] }.to_h
end
def merge_date_for_form_attributes(attributes)
attributes['date'] = { required: false, has_default: false }
attributes.delete 'due_date'
attributes.delete 'start_date'
end
def add_custom_fields_to_form_attributes(attributes)
WorkPackageCustomField.includes(:custom_options).all.each do |field|
attributes["custom_field_#{field.id}"] = {
required: field.is_required,
has_default: field.default_value.present?,
is_cf: true,
display_name: field.name
}
end
end
def attr_i18n_key(name)
if name == 'percentage_done'
'done_ratio'
else
name
end
end
def attr_translate(name)
if name == 'date'
I18n.t('label_date')
else
key = attr_i18n_key(name)
I18n.t("activerecord.attributes.work_package.#{key}", fallback: false, default: '')
.presence || I18n.t("attributes.#{key}")
end
end
end
##
# Get all applicable work package attributes
def work_package_attributes(merge_date: true)
all_attributes = self.class.all_work_package_form_attributes(merge_date: merge_date)
# Reject those attributes that are not available for this type.
all_attributes.select { |key, _| passes_attribute_constraint? key }
end
##
# Verify that the given attribute is applicable
# in this type instance.
# If a project context is given, that context is passed
# to the constraint validator.
def passes_attribute_constraint?(attribute, project: nil)
# Check custom field constraints
if CustomField.custom_field_attribute?(attribute) && !project.nil?
return custom_field_in_project?(attribute, project)
end
# Check other constraints (none in the core, but costs/backlogs adds constraints)
constraint = attribute_constraints[attribute.to_sym]
constraint.nil? || constraint.call(self, project: project)
end
##
# Returns the active custom_field_attributes
def active_custom_field_attributes
custom_field_ids.map { |id| "custom_field_#{id}" }
end
##
# Returns whether the custom field is active in the given project.
def custom_field_in_project?(attribute, project)
project
.all_work_package_custom_fields.pluck(:id)
.map { |id| "custom_field_#{id}" }
.include? attribute
end
end
| 33.816327 | 119 | 0.696138 |
87e54e45f1edeed970492bf7a167e0bba9d0a018 | 534 | # See https://docs.chef.io/config_rb_knife.html for more information on knife configuration options
current_dir = File.dirname(__FILE__)
log_level :info
log_location STDOUT
node_name "ksubrama"
client_key "#{current_dir}/ksubrama.pem"
validation_client_name "ksubrama-validator"
validation_key "#{current_dir}/ksubrama-validator.pem"
chef_server_url "https://api.opscode.com/organizations/ksubrama"
cookbook_path ["#{current_dir}/../cookbooks"]
| 44.5 | 99 | 0.679775 |
bf8f6dcf8e9eedd6db2483a1885db2a95eac225d | 5,506 | =begin
PureCloud Platform API
With the PureCloud Platform API, you can control all aspects of your PureCloud environment. With the APIs you can access the system configuration, manage conversations and more.
OpenAPI spec version: v2
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
License: ININ
http://www.inin.com
Terms of Service: https://developer.mypurecloud.com/tos
=end
require 'date'
module PureCloud
class Ticker
# The ticker symbol for this organization. Example: ININ, AAPL, MSFT, etc.
attr_accessor :symbol
# The exchange for this ticker symbol. Examples: NYSE, FTSE, NASDAQ, etc.
attr_accessor :exchange
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'symbol' => :'symbol',
:'exchange' => :'exchange'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'symbol' => :'String',
:'exchange' => :'String'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v}
if attributes.has_key?(:'symbol')
self.symbol = attributes[:'symbol']
end
if attributes.has_key?(:'exchange')
self.exchange = attributes[:'exchange']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properies with the reasons
def list_invalid_properties
invalid_properties = Array.new
return invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
if @symbol.nil?
return false
end
if @exchange.nil?
return false
end
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
symbol == o.symbol &&
exchange == o.exchange
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[symbol, exchange].hash
end
# build the object from hash
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
else
#TODO show warning in debug mode
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
else
# data not found in attributes(hash), not an issue as the data can be optional
end
end
self
end
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /^(true|t|yes|y|1)$/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
_model = Object.const_get("PureCloud").const_get(type).new
_model.build_from_hash(value)
end
end
def to_s
to_hash.to_s
end
# to_body is an alias to to_body (backward compatibility))
def to_body
to_hash
end
# return the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Method to output non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
def _to_hash(value)
if value.is_a?(Array)
value.compact.map{ |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 23.037657 | 177 | 0.575736 |
38d5bf620f4521e9732e95f6a52d0ba643ef4c9c | 44 | module SwingServoPi
VERSION = "0.1.0"
end
| 11 | 19 | 0.704545 |
b9cf019b8635cb400eb0cfc386b45ebc0f4a6eea | 707 | # frozen_string_literal: true
require_relative "entity"
require_relative "components/ai"
require_relative "components/fighter"
module Roguelike
class Actor < Entity
attr_reader :fighter
attr_accessor :ai
def initialize(ai_class:, fighter:, x: 0, y: 0, char: "?", color: :white, name: "<Unnamed>")
super(
x: x,
y: y,
char: char,
color: color,
name: name,
blocks_movement: true,
render_order: RenderOrder.actor
)
@ai = ai_class.new(entity: self)
@fighter = fighter
@fighter.entity = self
end
def alive?
!!@ai
end
end
end
| 21.424242 | 96 | 0.547383 |
21a61ab6a63b2e6d5561840941df38820d9ff2f1 | 91 | class Link < ActiveRecord::Base
acts_as_votable
belongs_to :user
has_many :comments
end
| 15.166667 | 31 | 0.802198 |
018c909c4813affad769f4a3b6d5941668d541f1 | 168 | module ApplicationHelper
def react_component(component_name, props = nil)
content_tag :div, '', data: { react_component: component_name, props: props }
end
end
| 28 | 81 | 0.75 |
f8817c1d1ac4060067af059982844830eab689cd | 4,365 | # frozen_string_literal: true
module Rack
class Cors
class Resource
# All CORS routes need to accept CORS simple headers at all times
# {https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers}
CORS_SIMPLE_HEADERS = %w[accept accept-language content-language content-type].freeze
attr_accessor :path, :methods, :headers, :expose, :max_age, :credentials, :pattern, :if_proc, :vary_headers
def initialize(public_resource, path, opts = {})
raise CorsMisconfigurationError if public_resource && opts[:credentials] == true
self.path = path
self.credentials = public_resource ? false : (opts[:credentials] == true)
self.max_age = opts[:max_age] || 7200
self.pattern = compile(path)
self.if_proc = opts[:if]
self.vary_headers = opts[:vary] && [opts[:vary]].flatten
@public_resource = public_resource
self.headers = case opts[:headers]
when :any then :any
when nil then nil
else
[opts[:headers]].flatten.collect(&:downcase)
end
self.methods = case opts[:methods]
when :any then %i[get head post put patch delete options]
else
ensure_enum(opts[:methods]) || [:get]
end.map(&:to_s)
self.expose = opts[:expose] ? [opts[:expose]].flatten : nil
end
def matches_path?(path)
pattern =~ path
end
def match?(path, env)
matches_path?(path) && (if_proc.nil? || if_proc.call(env))
end
def process_preflight(env, result)
headers = {}
request_method = env[Rack::Cors::HTTP_ACCESS_CONTROL_REQUEST_METHOD]
result.miss(Result::MISS_NO_METHOD) && (return headers) if request_method.nil?
result.miss(Result::MISS_DENY_METHOD) && (return headers) unless methods.include?(request_method.downcase)
request_headers = env[Rack::Cors::HTTP_ACCESS_CONTROL_REQUEST_HEADERS]
result.miss(Result::MISS_DENY_HEADER) && (return headers) if request_headers && !allow_headers?(request_headers)
result.hit = true
headers.merge(to_preflight_headers(env))
end
def to_headers(env)
h = {
'Access-Control-Allow-Origin' => origin_for_response_header(env[Rack::Cors::HTTP_ORIGIN]),
'Access-Control-Allow-Methods' => methods.collect { |m| m.to_s.upcase }.join(', '),
'Access-Control-Expose-Headers' => expose.nil? ? '' : expose.join(', '),
'Access-Control-Max-Age' => max_age.to_s
}
h['Access-Control-Allow-Credentials'] = 'true' if credentials
h
end
protected
def public_resource?
@public_resource
end
def origin_for_response_header(origin)
return '*' if public_resource?
origin
end
def to_preflight_headers(env)
h = to_headers(env)
h.merge!('Access-Control-Allow-Headers' => env[Rack::Cors::HTTP_ACCESS_CONTROL_REQUEST_HEADERS]) if env[Rack::Cors::HTTP_ACCESS_CONTROL_REQUEST_HEADERS]
h
end
def allow_headers?(request_headers)
headers = self.headers || []
return true if headers == :any
request_headers = request_headers.split(/,\s*/) if request_headers.is_a?(String)
request_headers.all? do |header|
header = header.downcase
CORS_SIMPLE_HEADERS.include?(header) || headers.include?(header)
end
end
def ensure_enum(var)
return nil if var.nil?
[var].flatten
end
def compile(path)
if path.respond_to? :to_str
special_chars = %w[. + ( )]
pattern =
path.to_str.gsub(%r{((:\w+)|/\*|[\*#{special_chars.join}])}) do |match|
case match
when '/*'
'\\/?(.*?)'
when '*'
'(.*?)'
when *special_chars
Regexp.escape(match)
else
'([^/?&#]+)'
end
end
/^#{pattern}$/
elsif path.respond_to? :match
path
else
raise TypeError, path
end
end
end
end
end
| 32.819549 | 160 | 0.569072 |
1a061ef069e66dff11b4b186fb1832ba09d619fb | 7,891 | shared_examples 'discussion comments' do |resource_name|
let(:form_selector) { '.js-main-target-form' }
let(:dropdown_selector) { "#{form_selector} .comment-type-dropdown" }
let(:toggle_selector) { "#{dropdown_selector} .dropdown-toggle" }
let(:menu_selector) { "#{dropdown_selector} .dropdown-menu" }
let(:submit_selector) { "#{form_selector} .js-comment-submit-button" }
let(:close_selector) { "#{form_selector} .btn-comment-and-close" }
let(:comments_selector) { '.timeline > .note.timeline-entry' }
it 'clicking "Comment" will post a comment' do
expect(page).to have_selector toggle_selector
find("#{form_selector} .note-textarea").send_keys('a')
find(submit_selector).click
find(comments_selector, match: :first)
new_comment = all(comments_selector).last
expect(new_comment).to have_content 'a'
expect(new_comment).not_to have_selector '.discussion'
end
if resource_name == 'issue'
it "clicking 'Comment & close #{resource_name}' will post a comment and close the #{resource_name}" do
find("#{form_selector} .note-textarea").send_keys('a')
find(close_selector).click
find(comments_selector, match: :first)
find("#{comments_selector}.system-note")
entries = all(comments_selector)
close_note = entries.last
new_comment = entries[-2]
expect(close_note).to have_content 'closed'
expect(new_comment).not_to have_selector '.discussion'
end
end
describe 'when the toggle is clicked' do
before do
find("#{form_selector} .note-textarea").send_keys('a')
find(toggle_selector).click
end
it 'has a "Comment" item (selected by default) and "Start discussion" item' do
expect(page).to have_selector menu_selector
find("#{menu_selector} li", match: :first)
items = all("#{menu_selector} li")
expect(items.first).to have_content 'Comment'
expect(items.first).to have_content "Add a general comment to this #{resource_name}."
expect(items.first).to have_selector '.fa-check'
expect(items.first['class']).to match 'droplab-item-selected'
expect(items.last).to have_content 'Start discussion'
expect(items.last).to have_content "Discuss a specific suggestion or question#{' that needs to be resolved' if resource_name == 'merge request'}."
expect(items.last).not_to have_selector '.fa-check'
expect(items.last['class']).not_to match 'droplab-item-selected'
end
it 'closes the menu when clicking the toggle or body' do
find(toggle_selector).click
expect(page).not_to have_selector menu_selector
find(toggle_selector).click
find('body').click
expect(page).not_to have_selector menu_selector
end
it 'clicking the ul padding should not change the text' do
find(menu_selector).trigger 'click'
expect(find(dropdown_selector)).to have_content 'Comment'
end
describe 'when selecting "Start discussion"' do
before do
find("#{menu_selector} li", match: :first)
all("#{menu_selector} li").last.click
end
it 'updates the submit button text, note_type input and closes the dropdown' do
expect(find(dropdown_selector)).to have_content 'Start discussion'
expect(find("#{form_selector} #note_type", visible: false).value).to eq('DiscussionNote')
expect(page).not_to have_selector menu_selector
end
if resource_name =~ /(issue|merge request)/
it 'updates the close button text' do
expect(find(close_selector)).to have_content "Start discussion & close #{resource_name}"
end
it 'typing does not change the close button text' do
find("#{form_selector} .note-textarea").send_keys('b')
expect(find(close_selector)).to have_content "Start discussion & close #{resource_name}"
end
end
it 'clicking "Start discussion" will post a discussion' do
find(submit_selector).click
find(comments_selector, match: :first)
new_comment = all(comments_selector).last
expect(new_comment).to have_content 'a'
expect(new_comment).to have_selector '.discussion'
end
if resource_name == 'issue'
it "clicking 'Start discussion & close #{resource_name}' will post a discussion and close the #{resource_name}" do
find(close_selector).click
find(comments_selector, match: :first)
find("#{comments_selector}.system-note")
entries = all(comments_selector)
close_note = entries.last
new_discussion = entries[-2]
expect(close_note).to have_content 'closed'
expect(new_discussion).to have_selector '.discussion'
end
end
describe 'when opening the menu' do
before do
find(toggle_selector).click
end
it 'should have "Start discussion" selected' do
find("#{menu_selector} li", match: :first)
items = all("#{menu_selector} li")
expect(items.first).to have_content 'Comment'
expect(items.first).not_to have_selector '.fa-check'
expect(items.first['class']).not_to match 'droplab-item-selected'
expect(items.last).to have_content 'Start discussion'
expect(items.last).to have_selector '.fa-check'
expect(items.last['class']).to match 'droplab-item-selected'
end
describe 'when selecting "Comment"' do
before do
find("#{menu_selector} li", match: :first).click
end
it 'updates the submit button text, clears the note_type input and closes the dropdown' do
expect(find(dropdown_selector)).to have_content 'Comment'
expect(find("#{form_selector} #note_type", visible: false).value).to eq('')
expect(page).not_to have_selector menu_selector
end
if resource_name =~ /(issue|merge request)/
it 'updates the close button text' do
expect(find(close_selector)).to have_content "Comment & close #{resource_name}"
end
it 'typing does not change the close button text' do
find("#{form_selector} .note-textarea").send_keys('b')
expect(find(close_selector)).to have_content "Comment & close #{resource_name}"
end
end
it 'should have "Comment" selected when opening the menu' do
find(toggle_selector).click
find("#{menu_selector} li", match: :first)
items = all("#{menu_selector} li")
expect(items.first).to have_content 'Comment'
expect(items.first).to have_selector '.fa-check'
expect(items.first['class']).to match 'droplab-item-selected'
expect(items.last).to have_content 'Start discussion'
expect(items.last).not_to have_selector '.fa-check'
expect(items.last['class']).not_to match 'droplab-item-selected'
end
end
end
end
end
if resource_name =~ /(issue|merge request)/
describe "on a closed #{resource_name}" do
before do
find("#{form_selector} .js-note-target-close").click
find("#{form_selector} .note-textarea").send_keys('a')
end
it "should show a 'Comment & reopen #{resource_name}' button" do
expect(find("#{form_selector} .js-note-target-reopen")).to have_content "Comment & reopen #{resource_name}"
end
it "should show a 'Start discussion & reopen #{resource_name}' button when 'Start discussion' is selected" do
find(toggle_selector).click
find("#{menu_selector} li", match: :first)
all("#{menu_selector} li").last.click
expect(find("#{form_selector} .js-note-target-reopen")).to have_content "Start discussion & reopen #{resource_name}"
end
end
end
end
| 36.873832 | 152 | 0.654163 |
081571f8383c96545866093e1ffc7c00aab51ec6 | 4,585 | #
# Cookbook:: runit_test
# Minitest:: service
#
# Copyright 2012, Opscode, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require File.expand_path('../support/helpers', __FILE__)
describe "runit_test::service" do
include Helpers::RunitTest
it 'creates a service with the defaults' do
service('plain-defaults').must_be_running
file('/etc/service/plain-defaults/run').must_exist
file('/etc/service/plain-defaults/log/run').must_exist
file('/etc/init.d/plain-defaults').must_exist
unless node['platform'] == 'gentoo'
link('/etc/service/plain-defaults').must_exist.with(
:link_type, :symbolic).and(:to, '/etc/sv/plain-defaults')
end
end
it 'creates a service that doesnt use the svlog' do
service('no-svlog').must_be_running
directory('/etc/sv/no-svlog/log').wont_exist
end
it 'creates a service that uses the default svlog' do
regexp = %r{#!/bin/sh\nexec svlogd -tt /var/log/default-svlog}
service('default-svlog').must_be_running
file('/etc/service/default-svlog/log/run').must_match(regexp)
end
it 'creates a service that has a check script' do
service('checker').must_be_running
file('/etc/service/checker/check').must_exist
end
it 'creates a service that has a finish script' do
service('finisher').must_be_running
file('/etc/service/finisher/finish').must_exist
end
it 'creates a service using sv_timeout' do
service('timer').must_be_running
end
it 'creates a service using sv_verbose' do
service('chatterbox').must_be_running
end
it 'creates a service that uses env files' do
regexp = %r{\$PATH:/opt/chef/embedded/bin}
service('env-files').must_be_running
file('/etc/service/env-files/env/PATH').must_match(regexp)
end
it 'creates a service that sets options for the templates' do
service('template-options').must_be_running
file('/etc/service/template-options/run').must_match("# Options are delicious")
end
it 'creates a service that uses control signal files' do
service('control-signals').must_be_running
file('/etc/service/control-signals/control/u').must_match(/control signal up/)
end
it 'creates a runsvdir service for a normal user' do
regexp = %r{exec chpst -ufloyd runsvdir /home/floyd/service}
service('runsvdir-floyd').must_be_running
file('/etc/service/runsvdir-floyd/run').must_match(regexp)
end
it 'creates a service running by a normal user in its runsvdir' do
floyds_app = shell_out(
"#{node['runit']['sv_bin']} status /home/floyd/service/floyds-app",
:user => "floyd",
:cwd => "/home/floyd"
)
assert floyds_app.stdout.include?('run:')
file('/home/floyd/service/floyds-app/run').must_exist.with(:owner, 'floyd')
file('/home/floyd/service/floyds-app/log/run').must_exist.with(:owner, 'floyd')
file('/etc/init.d/floyds-app').must_exist
unless node['platform'] == 'gentoo'
link('/home/floyd/service/floyds-app').must_exist.with(
:link_type, :symbolic).and(:to, '/home/floyd/sv/floyds-app')
end
end
it 'creates a service with differently named template files' do
service('yerba').must_be_running
end
it 'creates a service with differently named run script template' do
service('yerba-alt').must_be_running
end
it 'creates a service that should exist but be disabled' do
file('/etc/sv/exist-disabled/run').must_exist
unless node['platform'] == 'gentoo'
link('/etc/service/exist-disabled').wont_exist
end
end
it 'can use templates from another cookbook' do
service('other-cookbook-templates').must_be_running
end
it 'creates a service that has its own run scripts' do
if node['platform_family'] == 'rhel'
skip "RHEL platforms don't have a generally available package w/ runit scripts"
end
git_daemon = shell_out("#{node['runit']['sv_bin']} status /etc/service/git-daemon")
assert git_daemon.stdout.include?('run:')
link('/etc/service/git-daemon').must_exist.with(
:link_type, :symbolic).and(:to, '/etc/sv/git-daemon')
end
end
| 34.734848 | 87 | 0.705998 |
791b8bd600cde5d98296740b17705aa20029530a | 2,426 | =begin
#Topological Inventory Ingress API
#Topological Inventory Ingress API
The version of the OpenAPI document: 0.0.2
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.2.0
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for TopologicalInventoryIngressApiClient::ContainerTemplate
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe 'ContainerTemplate' do
before do
# run before each test
@instance = TopologicalInventoryIngressApiClient::ContainerTemplate.new
end
after do
# run after each test
end
describe 'test an instance of ContainerTemplate' do
it 'should create an instance of ContainerTemplate' do
expect(@instance).to be_instance_of(TopologicalInventoryIngressApiClient::ContainerTemplate)
end
end
describe 'test attribute "archived_at"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "container_project"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "resource_timestamp"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "resource_version"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "source_created_at"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "source_deleted_at"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "source_ref"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 28.880952 | 102 | 0.734542 |
f83e845e36c9b359683411f67a0e50f743c820f3 | 1,512 | require "formula"
# NOTE: Configure will fail if using awk 20110810 from dupes.
# Upstream issue: https://savannah.gnu.org/bugs/index.php?37063
class Wget < Formula
homepage "https://www.gnu.org/software/wget/"
url "http://ftpmirror.gnu.org/wget/wget-1.16.tar.xz"
mirror "https://ftp.gnu.org/gnu/wget/wget-1.16.tar.xz"
sha1 "08d991acc80726abe57043a278f9da469c454503"
bottle do
sha1 "97196dab9c0eb7afc7060afec98fc8cda54459c2" => :yosemite
sha1 "98af6113f187abc5613b7aa2fbc24feeaa964e4f" => :mavericks
sha1 "d84826b6dca644b2ccf3b157fd8a092994de43e2" => :mountain_lion
end
head do
url "git://git.savannah.gnu.org/wget.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "xz" => :build
depends_on "gettext"
end
deprecated_option "enable-iri" => "with-iri"
deprecated_option "enable-debug" => "with-debug"
option "with-iri", "Enable iri support"
option "with-debug", "Build with debug support"
depends_on "openssl"
depends_on "libidn" if build.with? "iri"
def install
system "./bootstrap" if build.head?
args = %W[
--prefix=#{prefix}
--sysconfdir=#{etc}
--with-ssl=openssl
--with-libssl-prefix=#{Formula["openssl"].opt_prefix}
]
args << "--disable-debug" if build.without? "debug"
args << "--disable-iri" if build.without? "iri"
system "./configure", *args
system "make", "install"
end
test do
system "#{bin}/wget", "-O", "-", "www.google.com"
end
end
| 26.526316 | 69 | 0.673942 |
1c3662a907c9e6d73e90a27862f78d891d621edf | 2,351 | require 'rails_helper'
RSpec.describe Speaker, type: :model do
before do
create(:cndt2020)
end
describe 'with valid CSV' do
before do
file_path = File.join(Rails.root, 'spec/fixtures/speakers.csv')
@csv = ActionDispatch::Http::UploadedFile.new(
filename: File.basename(file_path),
type: 'image/jpeg',
tempfile: File.open(file_path)
)
@message = Speaker.import(@csv)
end
it "is imported 3 speakers" do
@speakers = Speaker.all
expect(@speakers.length).to eq 3
end
it "is Takaishi-sensei" do
@speaker = Speaker.find(1)
expect(@speaker.name).to eq "高石 諒"
end
it "is includes avatar_data in the exported data" do
all = Speaker.export
expect(all).to include "ultra-super-takaishi-sensei.png"
end
it "is no message returns" do
expect(@message.size).to eq 0
end
describe 'Update CSV' do
before do
file_path = File.join(Rails.root, 'spec/fixtures/modified_speakers.csv')
@csv = ActionDispatch::Http::UploadedFile.new(
filename: File.basename(file_path),
type: 'image/jpeg',
tempfile: File.open(file_path)
)
@message = Speaker.import(@csv)
end
it "is imported 4 speakers" do
@speakers = Speaker.all
expect(@speakers.length).to eq 4
end
it "is modified speaker" do
@speaker = Speaker.find(3)
expect(@speaker.name).to eq "変更され太郎"
end
it "is added speaker" do
@speaker = Speaker.find(4)
expect(@speaker.name).to eq "追加され太郎"
end
it "is speaker remain unchanged" do
@speaker = Speaker.find(2)
expect(@speaker.name).to eq "講演し太郎2"
end
end
end
describe 'with invalid CSV' do
before do
file_path = File.join(Rails.root, 'spec/fixtures/invalid-speakers.csv')
@csv = ActionDispatch::Http::UploadedFile.new(
filename: File.basename(file_path),
type: 'image/jpeg',
tempfile: File.open(file_path)
)
@message = Speaker.import(@csv)
end
it "is no speakers imported" do
@speakers = Speaker.all
expect(@speakers.length).to eq 0
end
it "is 1 message returns" do
expect(@message[0]).to include "id: 4"
end
end
end
| 23.989796 | 80 | 0.602722 |
288452b894811129e953f33fc4ba254f33f0d908 | 599 | # frozen_string_literal: true
require File.expand_path '../test_helper.rb', __dir__
# Unit Test suit for Outcome Model
class OutcomeTest < MiniTest::Unit::TestCase
MiniTest::Unit::TestCase
def test_outcome_must_has_career_and_choice
# Arrange
outcome1 = Outcome.new
outcome2 = Outcome.new
outcome3 = Outcome.new
# Act
outcome1.career_id = 1
outcome1.choice_id = 1
outcome2.career_id = 1
outcome3.choice_id = 1
# Assert
assert_equal(outcome1.valid?, true)
assert_equal(outcome2.valid?, false)
assert_equal(outcome3.valid?, false)
end
end
| 23.038462 | 53 | 0.716194 |
2184affc7ed332f775af28c8f592584f233b0151 | 1,217 | # frozen_string_literal: true
json.sections @sections do |section|
json.(section, :id, :title, :weight)
json.description format_html(section.description)
json.questions section.questions do |question|
json.(question, :id, :required, :question_type, :max_options, :min_options, :weight,
:grid_view)
json.description format_html(question.description)
json.options question.options, partial: 'course/survey/questions/option', as: :option
student_submitted_answers = question.answers.select do |answer|
answer.response.submitted? && answer.response.course_user.student?
end
json.answers student_submitted_answers do |answer|
json.(answer, :id)
unless @survey.anonymous?
json.response_path course_survey_response_path(current_course, @survey, answer.response)
json.course_user_name answer.response.course_user.name
json.course_user_id answer.response.course_user.id
end
json.phantom answer.response.course_user.phantom?
if question.text?
json.(answer, :text_response)
else
json.(answer, :question_option_ids)
end
end
end
end
json.survey do
json.partial! 'survey', survey: @survey
end
| 35.794118 | 96 | 0.722268 |
913a2f36afb35755d67b776473f2fa1028ef3615 | 15,198 |
describe RunLoop::DetectAUT::Detect do
let(:app) { RunLoop::App.new(Resources.shared.cal_app_bundle_path) }
let(:obj) { RunLoop::DetectAUT::Detect.new }
describe "#app_for_simulator" do
it "respects the APP variable" do
expect(RunLoop::Environment).to receive(:path_to_app_bundle).and_return(app.path)
actual = obj.app_for_simulator
expect(actual.path).to be == app.path
end
describe "standalone project" do
let(:local_dir) { File.expand_path("./") }
let(:search_dirs) { [local_dir] }
before do
allow(RunLoop::Environment).to receive(:path_to_app_bundle).and_return(nil)
allow(obj).to receive(:xcode_project?).and_return(false)
allow(obj).to receive(:xamarin_project?).and_return(false)
end
it "finds an app by recursively searching down from the local directory" do
apps = [app, app.dup, app.dup]
expect(obj).to receive(:candidate_apps).with(local_dir).and_return(apps)
expect(obj).to receive(:select_most_recent_app).with(apps).and_return(app)
expect(obj.app_for_simulator).to be == app
end
it "it does not find any apps" do
expect(obj).to receive(:candidate_apps).with(local_dir).and_return([])
expect do
obj.app_for_simulator
end.to raise_error RunLoop::NoSimulatorAppFoundError
end
end
describe "xamarin project" do
let(:search_dirs) { ["path/a"] }
before do
allow(RunLoop::Environment).to receive(:path_to_app_bundle).and_return(nil)
allow(obj).to receive(:xcode_project?).and_return(false)
allow(obj).to receive(:xamarin_project?).and_return(true)
end
it "found apps" do
apps = [app, app.dup, app.dup]
expect(obj).to receive(:solution_directory).and_return(search_dirs.first)
expect(obj).to receive(:candidate_apps).with(search_dirs.first).and_return(apps)
expect(obj).to receive(:select_most_recent_app).with(apps).and_return(app)
expect(obj.app_for_simulator).to be == app
end
it "found no apps" do
depth = RunLoop::DetectAUT::Detect::DEFAULTS[:search_depth]
expect(obj).to receive(:solution_directory).and_return(search_dirs.first)
expect(obj).to receive(:candidate_apps).with(search_dirs.first).and_return([])
expect(obj).to receive(:raise_no_simulator_app_found).with(search_dirs, depth).and_call_original
expect do
obj.app_for_simulator
end.to raise_error RunLoop::NoSimulatorAppFoundError
end
end
describe "xcode project" do
let(:search_dirs) { ["path/a", "path/b", "path/c"] }
before do
allow(RunLoop::Environment).to receive(:path_to_app_bundle).and_return(nil)
allow(obj).to receive(:xcode_project?).and_return(true)
allow(obj).to receive(:xamarin_project?).and_return(false)
end
it "found apps" do
apps = [app, app.dup, app.dup]
expect(obj).to receive(:detect_xcode_apps).and_return([apps, search_dirs])
expect(obj).to receive(:select_most_recent_app).with(apps).and_return(app)
expect(obj.app_for_simulator).to be == app
end
describe "found no apps" do
it "did not find any apps in DerivedData or by search recursively down from the directory" do
depth = RunLoop::DetectAUT::Detect::DEFAULTS[:search_depth]
expect(obj).to receive(:detect_xcode_apps).and_return([[], search_dirs])
expect(obj).to receive(:raise_no_simulator_app_found).with(search_dirs, depth).and_call_original
expect do
obj.app_for_simulator
end.to raise_error RunLoop::NoSimulatorAppFoundError
end
end
end
end
it "#select_most_recent_app" do
t0 = Time.now
t1 = t0 - 1
t2 = t0 - 2
allow(obj).to receive(:mtime).with("a").and_return(t0)
allow(obj).to receive(:mtime).with("b").and_return(t1)
allow(obj).to receive(:mtime).with("c").and_return(t2)
apps = ["a", "b", "c"].shuffle
expect(obj.select_most_recent_app(apps)).to be == "a"
end
describe "#app_or_nil" do
let(:path) { app.path }
before do
allow(obj).to receive(:app_with_bundle).and_return(app)
end
it "true" do
expect(obj.app_or_nil(path)).to be_truthy
end
describe "false" do
it "not a valid app bundle" do
expect(RunLoop::App).to receive(:valid?).with(path).and_return(false)
expect(obj.app_or_nil(path)).to be == nil
end
it "not a simulator app" do
expect(app).to receive(:simulator?).and_return(false)
expect(obj.app_or_nil(path)).to be == nil
end
it "not linked with Calabash" do
expect(app).to receive(:simulator?).and_return(true)
expect(app).to receive(:calabash_server_version).and_return(nil)
expect(obj.app_or_nil(path)).to be == nil
end
end
end
it "#mtime" do
expect(app).to receive(:path).and_return("path/to")
expect(app).to receive(:executable_name).and_return("binary")
path = "path/to/binary"
expect(File).to receive(:mtime).with(path)
obj.mtime(app)
end
describe "#globs_for_app_search" do
it "array of globs that based on default search depth" do
defaults = {:search_depth => 5}
stub_const("RunLoop::DetectAUT::Detect::DEFAULTS", defaults)
expected_count = RunLoop::DetectAUT::Detect::DEFAULTS[:search_depth]
expected = [
"./*.app",
"./*/*.app",
"./*/*/*.app",
"./*/*/*/*.app",
"./*/*/*/*/*.app"
]
expect(expected.count).to be == expected_count
actual = obj.send(:globs_for_app_search, "./")
expect(actual).to be == expected
end
it "respects changes to DEFAULTS[:search_depth]" do
stub_const("RunLoop::DetectAUT::Detect::DEFAULTS", {search_depth: 2})
expected_count = RunLoop::DetectAUT::Detect::DEFAULTS[:search_depth]
expected = [
"./*.app",
"./*/*.app",
]
expect(expected.count).to be == expected_count
actual = obj.send(:globs_for_app_search, "./")
expect(actual).to be == expected
end
end
describe "detecting the AUT" do
let(:app_path) { Resources.shared.app_bundle_path }
let(:app) { RunLoop::App.new(app_path) }
let(:app_bundle_id) { app.bundle_identifier }
let(:ipa_path) { Resources.shared.ipa_path }
let(:ipa) { RunLoop::Ipa.new(ipa_path) }
let(:ipa_bundle_id) { ipa.bundle_identifier }
let(:options) do
{
:app => app_path,
:bundle_id => app_bundle_id
}
end
describe ".app_from_options" do
it ":app" do
actual = RunLoop::DetectAUT.send(:app_from_options, options)
expect(actual).to be == options[:app]
end
it ":bundle_id" do
options[:app] = nil
actual = RunLoop::DetectAUT.send(:app_from_options, options)
expect(actual).to be == options[:bundle_id]
end
end
describe ".app_from_environment" do
describe "APP or APP_BUNDLE_PATH" do
it "is a path to a directory that exists" do
expect(RunLoop::Environment).to receive(:path_to_app_bundle).and_return(app_path)
actual = RunLoop::DetectAUT.send(:app_from_environment)
expect(actual).to be == app_path
end
it "is a bundle id" do
bundle_id = "com.example.MyApp"
expect(RunLoop::Environment).to receive(:path_to_app_bundle).and_return(bundle_id)
actual = RunLoop::DetectAUT.send(:app_from_environment)
expect(actual).to be == bundle_id
end
it "is a path to a bundle that does not exist" do
expect(RunLoop::Environment).to receive(:path_to_app_bundle).and_return(app_path)
expect(File).to receive(:exist?).with(app_path).and_return(false)
actual = RunLoop::DetectAUT.send(:app_from_environment)
expect(actual).to be == File.basename(app_path)
end
end
it "BUNDLE_ID" do
expect(RunLoop::Environment).to receive(:path_to_app_bundle).and_return(nil)
expect(RunLoop::Environment).to receive(:bundle_id).and_return(app_bundle_id)
actual = RunLoop::DetectAUT.send(:app_from_environment)
expect(actual).to be == app_bundle_id
end
end
# Untestable?
# describe ".app_from_constant" do
# let(:world_with_app) do
# Class.new do
# APP = Resources.shared.app_bundle_path
# def self.app_from_constant
# RunLoop::DetectAUT.send(:app_from_constant)
# end
# end
# end
#
# let(:world_with_app_bundle_path) do
# Class.new do
# APP_BUNDLE_PATH = Resources.shared.app_bundle_path
# def self.app_from_constant
# RunLoop::DetectAUT.send(:app_from_constant)
# end
# end
# end
#
# after do
# if Object.constants.include?(world_with_app)
# Object.send(:remove_const, world_with_app)
# end
#
# if Object.constants.include?(world_with_app_bundle_path)
# Object.send(:remove_const, world_with_app_bundle_path)
# end
# end
#
# it "APP and APP_BUNDLE_PATH not defined" do
# actual = RunLoop::DetectAUT.send(:app_from_constant)
# expect(actual).to be == nil
# end
#
# it "APP defined and non-nil" do
# actual = world_with_app.send(:app_from_constant)
# expect(actual).to be == app_path
# end
#
# it "APP_BUNDLE_PATH defined and non-nil" do
# actual = world_with_app_bundle_path.send(:app_from_constant)
# expect(actual).to be == app_path
# end
# end
describe ".app_from_opts_or_env_or_constant" do
it "app is defined in options" do
expect(RunLoop::DetectAUT).to receive(:app_from_options).and_return(app)
actual = RunLoop::DetectAUT.send(:app_from_opts_or_env_or_constant, options)
expect(actual).to be == app
end
it "app is defined in environment" do
expect(RunLoop::DetectAUT).to receive(:app_from_options).and_return(nil)
expect(RunLoop::DetectAUT).to receive(:app_from_environment).and_return(app)
actual = RunLoop::DetectAUT.send(:app_from_opts_or_env_or_constant, options)
expect(actual).to be == app
end
it "app is defined as constant" do
expect(RunLoop::DetectAUT).to receive(:app_from_options).and_return(nil)
expect(RunLoop::DetectAUT).to receive(:app_from_environment).and_return(nil)
expect(RunLoop::DetectAUT).to receive(:app_from_constant).and_return(app)
actual = RunLoop::DetectAUT.send(:app_from_opts_or_env_or_constant, options)
expect(actual).to be == app
end
it "app is not defined anywhere" do
expect(RunLoop::DetectAUT).to receive(:app_from_options).and_return(nil)
expect(RunLoop::DetectAUT).to receive(:app_from_environment).and_return(nil)
expect(RunLoop::DetectAUT).to receive(:app_from_constant).and_return(nil)
actual = RunLoop::DetectAUT.send(:app_from_opts_or_env_or_constant, options)
expect(actual).to be == nil
end
end
describe ".detect_app" do
describe "defined some where" do
it "is an App" do
expect(RunLoop::DetectAUT).to receive(:app_from_opts_or_env_or_constant).with(options).and_return(app)
actual = RunLoop::DetectAUT.send(:detect_app, options)
expect(actual).to be == app
end
it "is an Ipa" do
expect(RunLoop::DetectAUT).to receive(:app_from_opts_or_env_or_constant).with(options).and_return(ipa)
actual = RunLoop::DetectAUT.send(:detect_app, options)
expect(actual).to be == ipa
end
it "is an app path" do
expect(RunLoop::DetectAUT).to receive(:app_from_opts_or_env_or_constant).with(options).and_return(app_path)
actual = RunLoop::DetectAUT.send(:detect_app, options)
expect(actual).to be_a_kind_of(RunLoop::App)
expect(actual.bundle_identifier).to be == app.bundle_identifier
end
it "is an ipa path" do
expect(RunLoop::DetectAUT).to receive(:app_from_opts_or_env_or_constant).with(options).and_return(ipa_path)
actual = RunLoop::DetectAUT.send(:detect_app, options)
expect(actual).to be_a_kind_of(RunLoop::Ipa)
expect(actual.bundle_identifier).to be == ipa.bundle_identifier
end
it "is a bundle identifier" do
expect(RunLoop::DetectAUT).to receive(:app_from_opts_or_env_or_constant).with(options).and_return(app_bundle_id)
actual = RunLoop::DetectAUT.send(:detect_app, options)
expect(actual).to be == app_bundle_id
end
end
describe "it is not defined" do
let(:detector) { RunLoop::DetectAUT::Detect.new }
before do
allow(RunLoop::DetectAUT).to receive(:detector).and_return(detector)
end
it "is auto detected" do
expect(detector).to receive(:app_for_simulator).twice.and_return(app)
expect(RunLoop::DetectAUT).to receive(:app_from_opts_or_env_or_constant).with(options).and_return(nil)
actual = RunLoop::DetectAUT.send(:detect_app, options)
expect(actual).to be == app
expect(RunLoop::DetectAUT).to receive(:app_from_opts_or_env_or_constant).with(options).and_return("")
actual = RunLoop::DetectAUT.send(:detect_app, options)
expect(actual).to be == app
end
it "is not auto detected" do
expect(RunLoop::DetectAUT).to receive(:app_from_opts_or_env_or_constant).with(options).and_return("")
expect(detector).to receive(:app_for_simulator).and_raise(RuntimeError)
expect do
RunLoop::DetectAUT.send(:detect_app, options)
end.to raise_error RuntimeError
end
end
describe ".detect_app_under_test" do
describe "App or Ipa instance" do
it "App" do
expect(RunLoop::DetectAUT).to receive(:detect_app).with(options).and_return(app)
hash = RunLoop::DetectAUT.detect_app_under_test(options)
expect(hash[:app]).to be == app
expect(hash[:bundle_id]).to be == app_bundle_id
expect(hash[:is_ipa]).to be == false
end
it "Ipa" do
expect(RunLoop::DetectAUT).to receive(:detect_app).with(options).and_return(ipa)
hash = RunLoop::DetectAUT.detect_app_under_test(options)
expect(hash[:app]).to be == ipa
expect(hash[:bundle_id]).to be == ipa_bundle_id
expect(hash[:is_ipa]).to be == true
end
end
it "bundle identifier" do
expect(RunLoop::DetectAUT).to receive(:detect_app).with(options).and_return(app_bundle_id)
hash = RunLoop::DetectAUT.detect_app_under_test(options)
expect(hash[:app]).to be == nil
expect(hash[:bundle_id]).to be == app_bundle_id
expect(hash[:is_ipa]).to be == false
end
end
end
end
end
| 34.540909 | 122 | 0.642124 |
ff47f8999a8839c2f25941cc93cae0648a95aa6a | 193 | class Tag < ApplicationRecord
validates :name, presence: true
validates :name, uniqueness: true
has_many :enrollments, dependent: :destroy
has_many :clients, through: :enrollments
end
| 24.125 | 44 | 0.766839 |
1d6d911f049a4988c4c3c8f9503d39889c16b26e | 2,329 | class Consul < Formula
desc "Tool for service discovery, monitoring and configuration"
homepage "https://www.consul.io"
url "https://github.com/hashicorp/consul/archive/refs/tags/v1.10.3.tar.gz"
sha256 "2f5334ba13c324ce166e290904daa5207bd9dafb5eb4c8ebf496c5f9d90cfa9c"
license "MPL-2.0"
head "https://github.com/hashicorp/consul.git", branch: "main"
livecheck do
url :stable
regex(/^v?(\d+(?:\.\d+)+)$/i)
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "38c883579980eeaa29b7fbbf8c0c8ea024310fd38ad0fd4188a64dc552690ab6"
sha256 cellar: :any_skip_relocation, big_sur: "3270fd47e75ffef527dcb8360d6e73a0bb44a9dee2dc1aceda2cb0385886ce5b"
sha256 cellar: :any_skip_relocation, catalina: "c67e5fc2ad0d55fe9f55d1e8de64b2b355ce13b77f12a16775b81ada03d16737"
sha256 cellar: :any_skip_relocation, mojave: "b3d551d48fe949ee3af2addf98e96aced37722122798d42775d167873df48aba"
sha256 cellar: :any_skip_relocation, x86_64_linux: "2187746a484810e520d49f4e85dd7a4d84e45e88ced001f5be5eac5d641682ff"
end
depends_on "go" => :build
# Support go 1.17, remove after next release
patch do
url "https://github.com/hashicorp/consul/commit/e43cf462679b6fdd8b15ac7891747e970029ac4a.patch?full_index=1"
sha256 "4f0edde54f0caa4c7290b17f2888159a4e0b462b5c890e3068a41d4c3582ca2f"
end
def install
system "go", "build", *std_go_args(ldflags: "-s -w")
end
service do
run [opt_bin/"consul", "agent", "-dev", "-bind", "127.0.0.1"]
keep_alive true
error_log_path var/"log/consul.log"
log_path var/"log/consul.log"
working_dir var
end
test do
http_port = free_port
fork do
# most ports must be free, but are irrelevant to this test
system(
bin/"consul",
"agent",
"-dev",
"-bind", "127.0.0.1",
"-dns-port", "-1",
"-grpc-port", "-1",
"-http-port", http_port,
"-serf-lan-port", free_port,
"-serf-wan-port", free_port,
"-server-port", free_port
)
end
# wait for startup
sleep 3
k = "brew-formula-test"
v = "value"
system bin/"consul", "kv", "put", "-http-addr", "127.0.0.1:#{http_port}", k, v
assert_equal v, shell_output(bin/"consul kv get -http-addr 127.0.0.1:#{http_port} #{k}").chomp
end
end
| 33.753623 | 122 | 0.689566 |
1d595e6aeff9a17ba00fc32f5cba7fabe8d76750 | 499 | # frozen_string_literal: true
require 'spec_helper'
begin
gem 'activerecord'
require 'active_record'
rescue Gem::LoadError => e
# active_record is not loaded in this test run
warn "WARNING: Cannot load active_record - some tests will be skipped\n#{e}"
end
if defined?(ActiveJob)
ActiveJob::Base.queue_adapter = :test
else
RSpec.configure do |c|
# skip active record based specs
c.before(:each, active_record: true) do
skip 'activerecord is not loaded'
end
end
end
| 21.695652 | 78 | 0.723447 |
613efcbfe96740dad79017cb6ac59c861787c066 | 712 | module DeviseSecurity
module Generators
# Generator for Rails to create or append to a Devise initializer.
class InstallGenerator < Rails::Generators::Base
LOCALES = %w[ en de it ]
source_root File.expand_path('../../templates', __FILE__)
desc 'Install the devise security extension'
def copy_initializer
template('devise-security.rb',
'config/initializers/devise-security.rb',
)
end
def copy_locales
LOCALES.each do |locale|
copy_file(
"../../../config/locales/#{locale}.yml",
"config/locales/devise.security_extension.#{locale}.yml",
)
end
end
end
end
end
| 26.37037 | 70 | 0.602528 |
28b4c1435e747fd352b358c1c687715670b91b5c | 4,303 | require 'spec_helper'
feature 'Member managing jobs' do
let(:member) { Fabricate(:member) }
before do
login(member)
end
context 'viewing their jobs' do
scenario 'can view all jobs they posted' do
jobs = Fabricate.times(3, :published_job, created_by: member)
pending_jobs = Fabricate.times(2, :pending_job, created_by: member)
drafts = Fabricate.times(3, :job, created_by: member)
visit member_jobs_path
expect(page.all(:xpath, "//td/span[text()='Published']").count).to eq(3)
expect(page.all(:xpath, "//td/span[text()='Pending approval']").count).to eq(2)
expect(page.all(:xpath, "//td/span[text()='Draft']").count).to eq(3)
end
it 'an approved job renders the member job page' do
job = Fabricate(:job, approved: true, created_by: member)
visit member_jobs_path
click_on job.title
expect(page.current_path).to eq(member_job_path(job.id))
end
it 'drafts job post take a user to the member job page' do
job = Fabricate(:job, submitted: true, approved: false, created_by: member)
visit member_jobs_path
click_on job.title
expect(page.current_path).to eq(member_job_path(job.id))
end
it 'pending job post take a user to the member job post' do
job = Fabricate(:job, submitted: false, approved: false, created_by: member)
visit member_jobs_path
click_on job.title
expect(page.current_path).to eq(member_job_path(job.id))
end
end
context 'creating a new job' do
scenario 'is unsuccessful unless all mandatory fields are submitted' do
visit new_member_job_path
fill_in 'Name', with: 'codebar'
click_on 'Submit job'
expect(page).to have_content('Title can\'t be blank')
end
scenario 'is succesful when all madantory fields are submitted' do
visit new_member_job_path
fill_in 'Title', with: 'Internship'
fill_in 'Description', with: Faker::Lorem.paragraph
fill_in 'Name', with: 'codebar'
fill_in 'Website', with: 'https://codebar.io'
fill_in 'Location', with: 'London'
fill_in 'Link to job post', with: Faker::Internet.url
fill_in 'Application closing date', with: (Time.zone.now + 3.months).strftime('%d/%m/%y')
click_on 'Submit job'
expect(page).to have_content('This is a preview of your job.Edit to amend or Submit for approval')
end
end
context 'viewing a job' do
it 'renders a preview of the job' do
job = Fabricate(:job, submitted: false, approved: false, created_by: member)
visit member_job_path(job.id)
expect(page).to have_content('This is a preview of your job.Edit to amend or Submit for approval')
expect(page).to have_content(job.title)
end
it 'informs the user if a job has already been submitted' do
job = Fabricate(:pending_job, created_by: member)
visit member_job_path(job.id)
expect(page).to have_content("This job is pending approval. Edit to amend your post.")
end
it 'allows the user to submit draft jobs' do
job = Fabricate(:job, created_by: member)
visit member_job_path(job.id)
expect(page).to have_content('This is a preview of your job.Edit to amend or Submit for approval.')
click_on 'Submit'
expect(page).to have_content("Job submitted for approval. You will receive an email when it's been approved.")
end
end
context '#edit' do
scenario 'can edit their job' do
job = Fabricate(:job, approved: false, created_by: member)
visit edit_member_job_path(job.id)
fill_in 'Title', with: 'JavaScript Internship'
click_on 'Submit'
expect(page).to have_content('Your job has been updated')
end
scenario 'can not reset mandatory fields' do
job = Fabricate(:job, approved: false, created_by: member)
visit edit_member_job_path(job.id)
fill_in 'Title', with: ''
click_on 'Submit'
expect(page).to have_content('Title can\'t be blank')
end
scenario 'can not edit an approved job' do
approved_job = Fabricate(:published_job, created_by: member)
visit edit_member_job_path(approved_job.id)
expect(page).to have_content('You cannot edit a job that has already been approved.')
end
end
end
| 32.11194 | 116 | 0.676737 |
7a49ede0df13d7ce4c17a8abab7f3e6e6520e96f | 184 | require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../shared/to_i', __FILE__)
describe "Integer#ceil" do
it_behaves_like(:integer_to_i, :ceil)
end
| 26.285714 | 58 | 0.73913 |
5d37ea749fc191051b083e2bb407bb4a504e54db | 857 | RSpec.describe(Base, type: :rack_test) {
context(:production) {
before(:each) {
ENV['APP_ENV'] = 'production'
}
it('does not print raw stack traces in production for normal users') {
expect_slim(:error, stack_trace: nil)
get '/throw_error'
expect(last_response.status).to(be(500))
expect(last_response.body).to_not(include('Fuck you'))
}
it('does print raw stack traces in production for privileged users') {
set_cookie(:email, '[email protected]')
expect_slim(:error, stack_trace: an_instance_of(String))
get '/throw_error'
expect(last_response.status).to(be(500))
expect(last_response.body).to(include('Fuck you'))
}
}
it('renders not found to unknown urls') {
expect_slim(:not_found)
get '/not_a_url'
expect(last_response.status).to(be(404))
}
}
| 29.551724 | 74 | 0.655776 |
f7e12721fcc97b64d61f2129345663c90c9e6671 | 1,835 | require File.expand_path('../helper', __FILE__)
class TestRemoteSyslogSender < Test::Unit::TestCase
def setup
@server_port = rand(50000) + 1024
@socket = UDPSocket.new
@socket.bind('127.0.0.1', @server_port)
@tcp_server = TCPServer.open('127.0.0.1', 0)
@tcp_server_port = @tcp_server.addr[1]
@tcp_server_wait_thread = Thread.start do
@tcp_server.accept
end
end
def teardown
@socket.close
@tcp_server.close
end
def test_sender
@sender = RemoteSyslogSender.new('127.0.0.1', @server_port)
@sender.write "This is a test"
message, _ = *@socket.recvfrom(1024)
assert_match(/This is a test/, message)
end
def test_sender_long_payload
@sender = RemoteSyslogSender.new('127.0.0.1', @server_port, packet_size: 10240)
@sender.write "abcdefgh" * 1000
message, _ = *@socket.recvfrom(10240)
assert_match(/#{"abcdefgh" * 1000}/, message)
end
def test_sender_tcp
@sender = RemoteSyslogSender.new('127.0.0.1', @tcp_server_port, protocol: :tcp)
@sender.write "This is a test"
sock = @tcp_server_wait_thread.value
message, _ = *sock.recvfrom(1024)
assert_match(/This is a test/, message)
end
def test_sender_tcp_nonblock
@sender = RemoteSyslogSender.new('127.0.0.1', @tcp_server_port, protocol: :tcp, timeout: 20)
@sender.write "This is a test"
sock = @tcp_server_wait_thread.value
message, _ = *sock.recvfrom(1024)
assert_match(/This is a test/, message)
end
def test_sender_multiline
@sender = RemoteSyslogSender.new('127.0.0.1', @server_port)
@sender.write "This is a test\nThis is the second line"
message, _ = *@socket.recvfrom(1024)
assert_match(/This is a test/, message)
message, _ = *@socket.recvfrom(1024)
assert_match(/This is the second line/, message)
end
end
| 27.38806 | 96 | 0.681744 |
2867f178c24d65c05152ac19c086a660e6b69d42 | 2,383 | $:.push File.join(File.dirname(__FILE__), '..', 'lib')
require 'rubygems'
require 'activesupport'
require 'merb-core'
require 'dm-core'
require 'do_sqlite3'
require 'merb-auth-core'
require 'merb-auth-more'
require 'merb-auth-more/mixins/redirect_back'
require 'spec'
require 'merb-auth-remember-me'
Merb.start_environment(
:testing => true,
:adapter => 'runner',
:environment => ENV['MERB_ENV'] || 'test',
# :merb_root => Merb.root,
:session_store => :cookie,
:exception_details => true,
:session_secret_key => "d3a6d6f99a25004dd82b71af8bded0ab71d3ea21"
)
DataMapper.setup(:default, "sqlite3::memory:")
class User
include DataMapper::Resource
include Merb::Authentication::Mixins::AuthenticatedUser
property :id, Serial
property :email, String
property :login, String
end
Merb::Authentication.user_class = User
def user
Merb::Authentication.user_class
end
# for strategy
Merb::Config[:exception_details] = true
Merb::Router.reset!
Merb::Router.prepare do
match("/login", :method => :get).to(:controller => "exceptions", :action => "unauthenticated").name(:login)
match("/login", :method => :put).to(:controller => "sessions", :action => "update")
authenticate do
match("/").to(:controller => "my_controller")
end
match("/logout", :method => :delete).to(:controller => "sessions", :action => "destroy")
end
class Merb::Authentication
def store_user(user); user; end
def fetch_user(session_info); session_info; end
end
Merb::Authentication.activate!(:remember_me)
Merb::Authentication.activate!(:default_password_form)
class MockUserStrategy < Merb::Authentication::Strategy
def run!
params[:pass_auth] = if params[:pass_auth] == "false"
false
else
Merb::Authentication.user_class.first
end
params[:pass_auth]
end
end
class Application < Merb::Controller; end
class Sessions < Merb::Controller
before :ensure_authenticated
def update
redirect "/"
end
def destroy
cookies.delete :auth_token
session.abandon!
end
end
class MyController < Application
def index
"IN MY CONTROLLER"
end
end
Spec::Runner.configure do |config|
config.include(Merb::Test::ViewHelper)
config.include(Merb::Test::RouteHelper)
config.include(Merb::Test::ControllerHelper)
config.before(:all){ User.auto_migrate! }
config.after(:all){ User.all.destroy! }
end
| 23.362745 | 109 | 0.710869 |
e8a419a798be0971d555b76fd906acfc54ceefe2 | 1,699 | # frozen_string_literal: true
module LeetCode
# 621. Task Scheduler
module LC621
# Description:
# Given a char array representing tasks CPU need to do.
# It contains capital letters A to Z where different letters represent different tasks.
# Tasks could be done without original order.
# Each task could be done in one interval.
# For each interval, CPU could finish one task or just be idle.
#
# However, there is a non-negative cooling interval n that means between two same tasks,
# there must be at least n intervals that CPU are doing different tasks or just be idle.
#
# You need to return the least number of intervals the CPU will take to finish all the given tasks.
#
# Examples:
# Input: tasks = ["A", "A", "A", "B", "B", "B"], n = 2
# Output: 8
# Explanation: A->B->idle->A->B->idle->A->B.
#
# Notes:
# - The number of tasks is in the range [1, 10000].
# - The integer n is in the range [0, 100].
#
# @param tasks {Array<String>}
# @param n {Integer}
# @return {Integer}
def least_interval(tasks, n)
return tasks.length if n <= 0
intervals = 0
tasks = tasks.group_by(&:itself).transform_values(&:length).values.sort
while !tasks.empty? && tasks[tasks.length - 1].positive?
cooldown = 0
while cooldown <= n
break if tasks[tasks.length - 1].zero?
tasks[(tasks.length - 1) - cooldown] -= 1 if cooldown < tasks.length && tasks[(tasks.length - 1) - cooldown].positive?
intervals += 1
cooldown += 1
end
tasks = tasks.select(&:positive?).sort
end
intervals
end
end
end
| 30.890909 | 128 | 0.616833 |
08ca64a0f99fe5eac4cc0b5d98412828f722da4e | 477 | # frozen_string_literal: true
module Facts
module Rhel
module Os
module Distro
class Id
FACT_NAME = 'os.distro.id'
ALIASES = 'lsbdistid'
def call_the_resolver
fact_value = Facter::Resolvers::LsbRelease.resolve(:distributor_id)
[Facter::ResolvedFact.new(FACT_NAME, fact_value),
Facter::ResolvedFact.new(ALIASES, fact_value, :legacy)]
end
end
end
end
end
end
| 21.681818 | 79 | 0.599581 |
e8bcde43a0b2f8d2b6b2404674822ae467b4f2f3 | 1,726 | # encoding: utf-8
#
# = In-Reply-To Field
#
# The In-Reply-To field inherits from StructuredField and handles the
# In-Reply-To: header field in the email.
#
# Sending in_reply_to to a mail message will instantiate a Mail::Field object that
# has a InReplyToField as it's field type. This includes all Mail::CommonMessageId
# module instance metods.
#
# Note that, the #message_ids method will return an array of message IDs without the
# enclosing angle brackets which per RFC are not syntactically part of the message id.
#
# Only one InReplyTo field can appear in a header, though it can have multiple
# Message IDs.
#
# == Examples:
#
# mail = Mail.new
# mail.in_reply_to = '<[email protected]>'
# mail.in_reply_to #=> '<[email protected]>'
# mail[:in_reply_to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::InReplyToField:0x180e1c4
# mail['in_reply_to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::InReplyToField:0x180e1c4
# mail['In-Reply-To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::InReplyToField:0x180e1c4
#
# mail[:in_reply_to].message_ids #=> ['[email protected]']
#
require 'mail/fields/common/common_message_id'
module Mail
class InReplyToField < StructuredField
include Mail::CommonMessageId
FIELD_NAME = 'in-reply-to'
CAPITALIZED_FIELD = 'In-Reply-To'
def initialize(value = nil, charset = 'utf-8')
self.charset = charset
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
self.parse
self
end
def encoded
do_encode(CAPITALIZED_FIELD)
end
def decoded
do_decode
end
end
end
| 30.821429 | 91 | 0.700463 |
011a19470ee16345130affc687fc855fd3c377d3 | 1,500 | require 'spec_helper'
describe Mongo::Auth::CR do
let(:server) do
authorized_client.cluster.next_primary
end
let(:connection) do
Mongo::Server::Connection.new(server, SpecConfig.instance.test_options)
end
describe '#login' do
before do
connection.connect!
end
context 'when the user is not authorized' do
let(:user) do
Mongo::Auth::User.new(
database: 'driver',
user: 'notauser',
password: 'password'
)
end
let(:cr) do
described_class.new(user)
end
let(:login) do
cr.login(connection).documents[0]
end
it 'raises an exception' do
expect {
cr.login(connection)
}.to raise_error(Mongo::Auth::Unauthorized)
end
context 'when compression is used' do
require_compression
min_server_fcv '3.6'
it 'does not compress the message' do
expect(Mongo::Protocol::Compressed).not_to receive(:new)
expect {
cr.login(connection)
}.to raise_error(Mongo::Auth::Unauthorized)
end
end
end
end
context 'when the user is authorized for the database' do
max_server_fcv '2.6'
before do
connection.connect!
end
let(:cr) do
described_class.new(root_user)
end
let(:login) do
cr.login(connection)
end
it 'logs the user into the connection' do
expect(login['ok']).to eq(1)
end
end
end
| 19.480519 | 75 | 0.594667 |
ab6ec105185a2bc5081efebbc4460d8ee2901e71 | 255 | module Intrigue
module Entity
class File < Intrigue::Model::Entity
def self.metadata
{
:name => "File",
:description => "A File",
:user_creatable => false
}
end
def validate_entity
name =~ /^\w.*$/
end
end
end
end
| 12.75 | 36 | 0.588235 |
b90ef3160c17f41be6cfa659d7557e10eb287727 | 1,105 | module Ecm
module Core
module Backend
module Generators
class InstallGenerator < Rails::Generators::Base
desc 'Installs the initializer, routes and itsf_backend integration'
source_root File.expand_path('../templates', __FILE__)
def generate_controller
copy_file 'backend_controller.rb', 'app/controllers/backend_controller.rb'
end
def generate_initializer
copy_file 'initializer.rb', 'config/initializers/ecm_core_backend.rb'
end
def generate_routes
route File.read(File.join(File.expand_path('../templates', __FILE__), 'routes.source'))
end
def add_to_itsf_backend
insert_into_itsf_backend_config(Ecm::Core::Backend::Engine)
end
private
def insert_into_itsf_backend_config(engine_name)
inject_into_file 'config/initializers/001_itsf_backend.rb', after: "config.backend_engines = %w(\n" do
" #{engine_name}\n"
end
end
end
end
end
end
end
| 29.078947 | 114 | 0.624434 |
212597802e2a08d57ea1ce95176df63e3681c6af | 706 | # frozen_string_literal: true
module Neo4j::Driver::Internal
module RevocationStrategy
# Don't do any OCSP revocation checks, regardless whether there are stapled revocation statuses or not.
NO_CHECKS = :no_checks
# Verify OCSP revocation checks when the revocation status is stapled to the certificate, continue if not.
VERIFY_IF_PRESENT = :verify_if_present
# Require stapled revocation status and verify OCSP revocation checks,
# fail if no revocation status is stapled to the certificate.
STRICT = :strict
def self.requires_revocation_checking?(revocation_strategy)
revocation_strategy == STRICT || revocation_strategy == VERIFY_IF_PRESENT
end
end
end
| 35.3 | 110 | 0.766289 |
b913e9d45b0519b80d3667b4a46beed469abc5ef | 2,899 | Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
require 'sidekiq/web'
require 'sidekiq/cron/web'
unless Figaro.env.disable_uploads.to_b
mount DAV4Rack::Handler.new(
root: File.join(Rails.root, 'public', 'system'),
root_uri_path: '/magnet',
resource_class: UserFileResource
), at: '/magnet'
end
mount Bootsy::Engine => '/bootsy', as: 'bootsy'
concern :collectable do
resources :boards, only: [:index, :show] do
resources :cards, only: :index
end
end
namespace :api, path: '/', constraints: { subdomain: 'api' } do
resources :docs, only: [:index]
resources :categories, only: [:index, :show], concerns: :collectable do
get 'tree', on: :collection
end
concerns :collectable
end
resources :categories, except: :show
resources :boards do
post 'upload', on: :collection
post 'hashtag', on: :collection
member do
get 'poll'
get 'users'
get 'filters'
get 'options'
get 'analytics'
get 'charts'
get 'tag_cloud'
put 'wall'
end
resources :feeds do
get 'poll', on: :member
put 'toggle_streaming', on: :member
end
resources :cards, only: [:new, :create, :edit, :update, :show, :destroy] do
post 'trust', on: :member
post 'ban', on: :member
get 'cta', on: :member
post 'bulk_update', on: :collection
end
end
resources :campaigns, except: :show
devise_for :users, controllers: { registrations: 'users/registrations', omniauth_callbacks: 'users/omniauth_callbacks' }
devise_scope :user do
delete '/users/authentications/:id' => 'users/omniauth_callbacks#destroy', as: :user_authentication
end
authenticate :user, lambda { |u| u.admin? } do
mount Sidekiq::Web => '/sidekiq'
end
resources :users, except: :show, path: '/accounts'
resources :teams, except: :show
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
match 'go/:id', to: 'slideshows#deck', via: [:get, :post]
match 'go/:id/:action', controller: 'slideshows', as: 'slideshow', via: [:get, :post], constraints: { action: /(deck|timeline|wall)/ }
get 'embed/:id/:layout/sample', to: 'slideshows#sample', as: 'slideshow_sample', constraints: { layout: /(deck|timeline)/ }
match 'embed/:id/:action', controller: 'slideshows', as: 'slideshow_embed', via: [:get, :post], constraints: { action: /(deck|timeline|wall)/ }, embed: true
authenticated :user do
root :to => "pages#dashboard", :as => "dashboard"
end
# You can have the root of your site routed with "root"
root 'slideshows#show'
match '/:id' => "shortener/shortened_urls#show", via: [:get, :post], constraints: -> (req) { req.env['PATH_INFO'] != '/cable' }
end
| 32.211111 | 158 | 0.651259 |
280d8a45725c9ece2ce16d6ad8a8de6aae91b00a | 527 | require 'fog/ecloud/models/compute/login_banner'
module Fog
module Compute
class Ecloud
class LoginBanners < Fog::Ecloud::Collection
identity :href
model Fog::Compute::Ecloud::LoginBanner
def all
data = service.get_login_banners(href).body
load(data)
end
def get(uri)
if data = service.get_login_banner(uri)
new(data.body)
end
rescue Fog::Errors::NotFound
nil
end
end
end
end
end
| 18.821429 | 53 | 0.574953 |
1a9077a72d852726a5c0b79add7bdecf12f4bc7b | 690 | #
# Cookbook:: datadog
# Recipe:: system_core
#
# Copyright:: 2015, Datadog
#
# 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.
#
include_recipe 'datadog::dd-agent'
datadog_monitor 'system_core'
| 31.363636 | 74 | 0.756522 |
f7533f36343e6e354479172641b2af8cc408aedd | 186 | # frozen_string_literal: true
class API2
module Parsers
# Parse licenses for API.
class LicenseParser < ObjectBase
def model
License
end
end
end
end
| 14.307692 | 36 | 0.650538 |
1ccdc1bcba0a44ef3b1d17ae266c7fcffd6f7921 | 39,833 | require "cmd/missing"
require "formula"
require "keg"
require "language/python"
require "version"
class Volumes
def initialize
@volumes = get_mounts
end
def which path
vols = get_mounts path
# no volume found
if vols.empty?
return -1
end
vol_index = @volumes.index(vols[0])
# volume not found in volume list
if vol_index.nil?
return -1
end
return vol_index
end
def get_mounts path=nil
vols = []
# get the volume of path, if path is nil returns all volumes
args = %w[/bin/df -P]
args << path if path
Utils.popen_read(*args) do |io|
io.each_line do |line|
case line.chomp
# regex matches: /dev/disk0s2 489562928 440803616 48247312 91% /
when /^.+\s+[0-9]+\s+[0-9]+\s+[0-9]+\s+[0-9]{1,3}%\s+(.+)/
vols << $1
end
end
end
return vols
end
end
class Checks
############# HELPERS
# Finds files in HOMEBREW_PREFIX *and* /usr/local.
# Specify paths relative to a prefix eg. "include/foo.h".
# Sets @found for your convenience.
def find_relative_paths *relative_paths
@found = %W[#{HOMEBREW_PREFIX} /usr/local].uniq.inject([]) do |found, prefix|
found + relative_paths.map{|f| File.join(prefix, f) }.select{|f| File.exist? f }
end
end
def inject_file_list(list, str)
list.inject(str) { |s, f| s << " #{f}\n" }
end
# Git will always be on PATH because of the wrapper script in
# Library/ENV/scm, so we check if there is a *real*
# git here to avoid multiple warnings.
def git?
return @git if instance_variable_defined?(:@git)
@git = system "git --version >/dev/null 2>&1"
end
############# END HELPERS
# Sorry for the lack of an indent here, the diff would have been unreadable.
# See https://github.com/Homebrew/homebrew/pull/9986
def check_path_for_trailing_slashes
bad_paths = ENV['PATH'].split(File::PATH_SEPARATOR).select { |p| p[-1..-1] == '/' }
return if bad_paths.empty?
s = <<-EOS.undent
Some directories in your path end in a slash.
Directories in your path should not end in a slash. This can break other
doctor checks. The following directories should be edited:
EOS
bad_paths.each{|p| s << " #{p}"}
s
end
# Installing MacGPG2 interferes with Homebrew in a big way
# http://sourceforge.net/projects/macgpg2/files/
def check_for_macgpg2
return if File.exist? '/usr/local/MacGPG2/share/gnupg/VERSION'
suspects = %w{
/Applications/start-gpg-agent.app
/Library/Receipts/libiconv1.pkg
/usr/local/MacGPG2
}
if suspects.any? { |f| File.exist? f } then <<-EOS.undent
You may have installed MacGPG2 via the package installer.
Several other checks in this script will turn up problems, such as stray
dylibs in /usr/local and permissions issues with share and man in /usr/local/.
EOS
end
end
def __check_stray_files(dir, pattern, white_list, message)
return unless File.directory?(dir)
files = Dir.chdir(dir) {
Dir[pattern].select { |f| File.file?(f) && !File.symlink?(f) } - Dir.glob(white_list)
}.map { |file| File.join(dir, file) }
inject_file_list(files, message) unless files.empty?
end
def check_for_stray_dylibs
# Dylibs which are generally OK should be added to this list,
# with a short description of the software they come with.
white_list = [
"libfuse.2.dylib", # MacFuse
"libfuse_ino64.2.dylib", # MacFuse
"libmacfuse_i32.2.dylib", # OSXFuse MacFuse compatibility layer
"libmacfuse_i64.2.dylib", # OSXFuse MacFuse compatibility layer
"libosxfuse_i32.2.dylib", # OSXFuse
"libosxfuse_i64.2.dylib", # OSXFuse
"libTrAPI.dylib", # TrAPI / Endpoint Security VPN
]
__check_stray_files "/usr/local/lib", "*.dylib", white_list, <<-EOS.undent
Unbrewed dylibs were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected dylibs:
EOS
end
def check_for_stray_static_libs
# Static libs which are generally OK should be added to this list,
# with a short description of the software they come with.
white_list = [
"libsecurity_agent_client.a", # OS X 10.8.2 Supplemental Update
"libsecurity_agent_server.a", # OS X 10.8.2 Supplemental Update
]
__check_stray_files "/usr/local/lib", "*.a", white_list, <<-EOS.undent
Unbrewed static libraries were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected static libraries:
EOS
end
def check_for_stray_pcs
# Package-config files which are generally OK should be added to this list,
# with a short description of the software they come with.
white_list = [
"fuse.pc", # OSXFuse/MacFuse
"macfuse.pc", # OSXFuse MacFuse compatibility layer
"osxfuse.pc", # OSXFuse
]
__check_stray_files "/usr/local/lib/pkgconfig", "*.pc", white_list, <<-EOS.undent
Unbrewed .pc files were found in /usr/local/lib/pkgconfig.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected .pc files:
EOS
end
def check_for_stray_las
white_list = [
"libfuse.la", # MacFuse
"libfuse_ino64.la", # MacFuse
"libosxfuse_i32.la", # OSXFuse
"libosxfuse_i64.la", # OSXFuse
]
__check_stray_files "/usr/local/lib", "*.la", white_list, <<-EOS.undent
Unbrewed .la files were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected .la files:
EOS
end
def check_for_stray_headers
white_list = [
"fuse.h", # MacFuse
"fuse/**/*.h", # MacFuse
"macfuse/**/*.h", # OSXFuse MacFuse compatibility layer
"osxfuse/**/*.h", # OSXFuse
]
__check_stray_files "/usr/local/include", "**/*.h", white_list, <<-EOS.undent
Unbrewed header files were found in /usr/local/include.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected header files:
EOS
end
def check_for_other_package_managers
ponk = MacOS.macports_or_fink
unless ponk.empty?
<<-EOS.undent
You have MacPorts or Fink installed:
#{ponk.join(", ")}
This can cause trouble. You don't have to uninstall them, but you may want to
temporarily move them out of the way, e.g.
sudo mv /opt/local ~/macports
EOS
end
end
def check_for_broken_symlinks
broken_symlinks = []
Keg::PRUNEABLE_DIRECTORIES.select(&:directory?).each do |d|
d.find do |path|
if path.symlink? && !path.resolved_path_exists?
broken_symlinks << path
end
end
end
unless broken_symlinks.empty? then <<-EOS.undent
Broken symlinks were found. Remove them with `brew prune`:
#{broken_symlinks * "\n "}
EOS
end
end
if MacOS.version >= "10.9"
def check_for_installed_developer_tools
unless MacOS::Xcode.installed? || MacOS::CLT.installed? then <<-EOS.undent
No developer tools installed.
Install the Command Line Tools:
xcode-select --install
EOS
end
end
def check_xcode_up_to_date
if MacOS::Xcode.installed? && MacOS::Xcode.outdated?
<<-EOS.undent
Your Xcode (#{MacOS::Xcode.version}) is outdated
Please update to Xcode #{MacOS::Xcode.latest_version}.
Xcode can be updated from the App Store.
EOS
end
end
def check_clt_up_to_date
if MacOS::CLT.installed? && MacOS::CLT.outdated? then <<-EOS.undent
A newer Command Line Tools release is available.
Update them from Software Update in the App Store.
EOS
end
end
elsif MacOS.version == "10.8" || MacOS.version == "10.7"
def check_for_installed_developer_tools
unless MacOS::Xcode.installed? || MacOS::CLT.installed? then <<-EOS.undent
No developer tools installed.
You should install the Command Line Tools.
The standalone package can be obtained from
https://developer.apple.com/downloads
or it can be installed via Xcode's preferences.
EOS
end
end
def check_xcode_up_to_date
if MacOS::Xcode.installed? && MacOS::Xcode.outdated? then <<-EOS.undent
Your Xcode (#{MacOS::Xcode.version}) is outdated
Please update to Xcode #{MacOS::Xcode.latest_version}.
Xcode can be updated from
https://developer.apple.com/downloads
EOS
end
end
def check_clt_up_to_date
if MacOS::CLT.installed? && MacOS::CLT.outdated? then <<-EOS.undent
A newer Command Line Tools release is available.
The standalone package can be obtained from
https://developer.apple.com/downloads
or it can be installed via Xcode's preferences.
EOS
end
end
else
def check_for_installed_developer_tools
return unless OS.mac?
unless MacOS::Xcode.installed? then <<-EOS.undent
Xcode is not installed. Most formulae need Xcode to build.
It can be installed from
https://developer.apple.com/downloads
EOS
end
end
def check_xcode_up_to_date
if MacOS::Xcode.installed? && MacOS::Xcode.outdated? then <<-EOS.undent
Your Xcode (#{MacOS::Xcode.version}) is outdated
Please update to Xcode #{MacOS::Xcode.latest_version}.
Xcode can be updated from
https://developer.apple.com/downloads
EOS
end
end
end
def check_for_osx_gcc_installer
if (MacOS.version < "10.7" || MacOS::Xcode.version > "4.1") && \
MacOS.clang_version == "2.1"
message = <<-EOS.undent
You seem to have osx-gcc-installer installed.
Homebrew doesn't support osx-gcc-installer. It causes many builds to fail and
is an unlicensed distribution of really old Xcode files.
EOS
if MacOS.version >= :mavericks
message += <<-EOS.undent
Please run `xcode-select --install` to install the CLT.
EOS
elsif MacOS.version >= :lion
message += <<-EOS.undent
Please install the CLT or Xcode #{MacOS::Xcode.latest_version}.
EOS
else
message += <<-EOS.undent
Please install Xcode #{MacOS::Xcode.latest_version}.
EOS
end
end
end
def check_for_stray_developer_directory
# if the uninstaller script isn't there, it's a good guess neither are
# any troublesome leftover Xcode files
uninstaller = Pathname.new("/Developer/Library/uninstall-developer-folder")
if MacOS::Xcode.version >= "4.3" && uninstaller.exist? then <<-EOS.undent
You have leftover files from an older version of Xcode.
You should delete them using:
#{uninstaller}
EOS
end
end
def check_for_bad_install_name_tool
return if MacOS.version < "10.9"
libs = Pathname.new("/usr/bin/install_name_tool").dynamically_linked_libraries
# otool may not work, for example if the Xcode license hasn't been accepted yet
return if libs.empty?
unless libs.include? "/usr/lib/libxcselect.dylib" then <<-EOS.undent
You have an outdated version of /usr/bin/install_name_tool installed.
This will cause binary package installations to fail.
This can happen if you install osx-gcc-installer or RailsInstaller.
To restore it, you must reinstall OS X or restore the binary from
the OS packages.
EOS
end
end
def __check_subdir_access base
target = HOMEBREW_PREFIX+base
return unless target.exist?
cant_read = []
target.find do |d|
next unless d.directory?
cant_read << d unless d.writable_real?
end
cant_read.sort!
if cant_read.length > 0 then
s = <<-EOS.undent
Some directories in #{target} aren't writable.
This can happen if you "sudo make install" software that isn't managed
by Homebrew. If a brew tries to add locale information to one of these
directories, then the install will fail during the link step.
You should probably `chown` them:
EOS
cant_read.each{ |f| s << " #{f}\n" }
s
end
end
def check_access_share_locale
__check_subdir_access 'share/locale'
end
def check_access_share_man
__check_subdir_access 'share/man'
end
def check_access_usr_local
return unless HOMEBREW_PREFIX.to_s == '/usr/local'
unless File.writable_real?("/usr/local") then <<-EOS.undent
The /usr/local directory is not writable.
Even if this directory was writable when you installed Homebrew, other
software may change permissions on this directory. Some versions of the
"InstantOn" component of Airfoil are known to do this.
You should probably change the ownership and permissions of /usr/local
back to your user account.
EOS
end
end
%w{include etc lib lib/pkgconfig share}.each do |d|
define_method("check_access_#{d.sub("/", "_")}") do
dir = HOMEBREW_PREFIX.join(d)
if dir.exist? && !dir.writable_real? then <<-EOS.undent
#{dir} isn't writable.
This can happen if you "sudo make install" software that isn't managed by
by Homebrew. If a formula tries to write a file to this directory, the
install will fail during the link step.
You should probably `chown` #{dir}
EOS
end
end
end
def check_access_site_packages
if Language::Python.homebrew_site_packages.exist? && !Language::Python.homebrew_site_packages.writable_real?
<<-EOS.undent
#{Language::Python.homebrew_site_packages} isn't writable.
This can happen if you "sudo pip install" software that isn't managed
by Homebrew. If you install a formula with Python modules, the install
will fail during the link step.
You should probably `chown` #{Language::Python.homebrew_site_packages}
EOS
end
end
def check_access_logs
if HOMEBREW_LOGS.exist? and not HOMEBREW_LOGS.writable_real?
<<-EOS.undent
#{HOMEBREW_LOGS} isn't writable.
This can happen if you "sudo make install" software that isn't managed
by Homebrew.
Homebrew writes debugging logs to this location.
You should probably `chown` #{HOMEBREW_LOGS}
EOS
end
end
def check_ruby_version
return unless OS.mac?
ruby_version = MacOS.version >= "10.9" ? "2.0" : "1.8"
if RUBY_VERSION[/\d\.\d/] != ruby_version then <<-EOS.undent
Ruby version #{RUBY_VERSION} is unsupported on #{MacOS.version}. Homebrew
is developed and tested on Ruby #{ruby_version}, and may not work correctly
on other Rubies. Patches are accepted as long as they don't cause breakage
on supported Rubies.
EOS
end
end
def check_homebrew_prefix
return unless OS.mac?
unless HOMEBREW_PREFIX.to_s == '/usr/local'
<<-EOS.undent
Your Homebrew is not installed to /usr/local
You can install Homebrew anywhere you want, but some brews may only build
correctly if you install in /usr/local. Sorry!
EOS
end
end
def check_xcode_prefix
prefix = MacOS::Xcode.prefix
return if prefix.nil?
if prefix.to_s.match(' ')
<<-EOS.undent
Xcode is installed to a directory with a space in the name.
This will cause some formulae to fail to build.
EOS
end
end
def check_xcode_prefix_exists
prefix = MacOS::Xcode.prefix
return if prefix.nil?
unless prefix.exist?
<<-EOS.undent
The directory Xcode is reportedly installed to doesn't exist:
#{prefix}
You may need to `xcode-select` the proper path if you have moved Xcode.
EOS
end
end
def check_xcode_select_path
return unless OS.mac?
if not MacOS::CLT.installed? and not File.file? "#{MacOS.active_developer_dir}/usr/bin/xcodebuild"
path = MacOS::Xcode.bundle_path
path = '/Developer' if path.nil? or not path.directory?
<<-EOS.undent
Your Xcode is configured with an invalid path.
You should change it to the correct path:
sudo xcode-select -switch #{path}
EOS
end
end
def check_user_path_1
$seen_prefix_bin = false
$seen_prefix_sbin = false
out = nil
paths.each do |p|
case p
when '/usr/bin'
unless $seen_prefix_bin
# only show the doctor message if there are any conflicts
# rationale: a default install should not trigger any brew doctor messages
conflicts = Dir["#{HOMEBREW_PREFIX}/bin/*"].
map{ |fn| File.basename fn }.
select{ |bn| File.exist? "/usr/bin/#{bn}" }
if conflicts.size > 0
out = <<-EOS.undent
/usr/bin occurs before #{HOMEBREW_PREFIX}/bin
This means that system-provided programs will be used instead of those
provided by Homebrew. The following tools exist at both paths:
#{conflicts * "\n "}
Consider setting your PATH so that #{HOMEBREW_PREFIX}/bin
occurs before /usr/bin. Here is a one-liner:
echo export PATH='#{HOMEBREW_PREFIX}/bin:$PATH' >> ~/.bash_profile
EOS
end
end
when "#{HOMEBREW_PREFIX}/bin"
$seen_prefix_bin = true
when "#{HOMEBREW_PREFIX}/sbin"
$seen_prefix_sbin = true
end
end
out
end
def check_user_path_2
unless $seen_prefix_bin
<<-EOS.undent
Homebrew's bin was not found in your PATH.
Consider setting the PATH for example like so
echo export PATH='#{HOMEBREW_PREFIX}/bin:$PATH' >> ~/.bash_profile
EOS
end
end
def check_user_path_3
# Don't complain about sbin not being in the path if it doesn't exist
sbin = (HOMEBREW_PREFIX+'sbin')
if sbin.directory? and sbin.children.length > 0
unless $seen_prefix_sbin
<<-EOS.undent
Homebrew's sbin was not found in your PATH but you have installed
formulae that put executables in #{HOMEBREW_PREFIX}/sbin.
Consider setting the PATH for example like so
echo export PATH='#{HOMEBREW_PREFIX}/sbin:$PATH' >> ~/.bash_profile
EOS
end
end
end
def check_user_curlrc
if %w[CURL_HOME HOME].any?{|key| ENV[key] and File.exist? "#{ENV[key]}/.curlrc" } then <<-EOS.undent
You have a curlrc file
If you have trouble downloading packages with Homebrew, then maybe this
is the problem? If the following command doesn't work, then try removing
your curlrc:
curl http://github.com
EOS
end
end
def check_which_pkg_config
binary = which 'pkg-config'
return if binary.nil?
mono_config = Pathname.new("/usr/bin/pkg-config")
if mono_config.exist? && mono_config.realpath.to_s.include?("Mono.framework") then <<-EOS.undent
You have a non-Homebrew 'pkg-config' in your PATH:
/usr/bin/pkg-config => #{mono_config.realpath}
This was most likely created by the Mono installer. `./configure` may
have problems finding brew-installed packages using this other pkg-config.
Mono no longer installs this file as of 3.0.4. You should
`sudo rm /usr/bin/pkg-config` and upgrade to the latest version of Mono.
EOS
elsif binary.to_s != "#{HOMEBREW_PREFIX}/bin/pkg-config" then <<-EOS.undent
You have a non-Homebrew 'pkg-config' in your PATH:
#{binary}
`./configure` may have problems finding brew-installed packages using
this other pkg-config.
EOS
end
end
def check_for_gettext
return unless OS.mac?
find_relative_paths("lib/libgettextlib.dylib",
"lib/libintl.dylib",
"include/libintl.h")
return if @found.empty?
# Our gettext formula will be caught by check_linked_keg_only_brews
f = Formulary.factory("gettext") rescue nil
return if f and f.linked_keg.directory? and @found.all? do |path|
Pathname.new(path).realpath.to_s.start_with? "#{HOMEBREW_CELLAR}/gettext"
end
s = <<-EOS.undent_________________________________________________________72
gettext files detected at a system prefix
These files can cause compilation and link failures, especially if they
are compiled with improper architectures. Consider removing these files:
EOS
inject_file_list(@found, s)
end
def check_for_iconv
return unless OS.mac?
unless find_relative_paths("lib/libiconv.dylib", "include/iconv.h").empty?
if (f = Formulary.factory("libiconv") rescue nil) and f.linked_keg.directory?
if not f.keg_only? then <<-EOS.undent
A libiconv formula is installed and linked
This will break stuff. For serious. Unlink it.
EOS
else
# NOOP because: check_for_linked_keg_only_brews
end
else
s = <<-EOS.undent_________________________________________________________72
libiconv files detected at a system prefix other than /usr
Homebrew doesn't provide a libiconv formula, and expects to link against
the system version in /usr. libiconv in other prefixes can cause
compile or link failure, especially if compiled with improper
architectures. OS X itself never installs anything to /usr/local so
it was either installed by a user or some other third party software.
tl;dr: delete these files:
EOS
inject_file_list(@found, s)
end
end
end
def check_for_config_scripts
return unless HOMEBREW_CELLAR.exist?
real_cellar = HOMEBREW_CELLAR.realpath
scripts = []
whitelist = %W[
/usr/bin /usr/sbin
/usr/X11/bin /usr/X11R6/bin /opt/X11/bin
#{HOMEBREW_PREFIX}/bin #{HOMEBREW_PREFIX}/sbin
/Applications/Server.app/Contents/ServerRoot/usr/bin
/Applications/Server.app/Contents/ServerRoot/usr/sbin
].map(&:downcase)
paths.each do |p|
next if whitelist.include?(p.downcase) || !File.directory?(p)
realpath = Pathname.new(p).realpath.to_s
next if realpath.start_with?(real_cellar.to_s, HOMEBREW_CELLAR.to_s)
scripts += Dir.chdir(p) { Dir["*-config"] }.map { |c| File.join(p, c) }
end
unless scripts.empty?
s = <<-EOS.undent
"config" scripts exist outside your system or Homebrew directories.
`./configure` scripts often look for *-config scripts to determine if
software packages are installed, and what additional flags to use when
compiling and linking.
Having additional scripts in your path can confuse software installed via
Homebrew if the config script overrides a system or Homebrew provided
script of the same name. We found the following "config" scripts:
EOS
s << scripts.map { |f| " #{f}" }.join("\n")
end
end
def check_DYLD_vars
found = ENV.keys.grep(/^DYLD_/)
unless found.empty?
s = <<-EOS.undent
Setting DYLD_* vars can break dynamic linking.
Set variables:
EOS
s << found.map { |e| " #{e}: #{ENV.fetch(e)}\n" }.join
if found.include? 'DYLD_INSERT_LIBRARIES'
s += <<-EOS.undent
Setting DYLD_INSERT_LIBRARIES can cause Go builds to fail.
Having this set is common if you use this software:
http://asepsis.binaryage.com/
EOS
end
s
end
end
def check_for_symlinked_cellar
return unless HOMEBREW_CELLAR.exist?
if HOMEBREW_CELLAR.symlink?
<<-EOS.undent
Symlinked Cellars can cause problems.
Your Homebrew Cellar is a symlink: #{HOMEBREW_CELLAR}
which resolves to: #{HOMEBREW_CELLAR.realpath}
The recommended Homebrew installations are either:
(A) Have Cellar be a real directory inside of your HOMEBREW_PREFIX
(B) Symlink "bin/brew" into your prefix, but don't symlink "Cellar".
Older installations of Homebrew may have created a symlinked Cellar, but this can
cause problems when two formula install to locations that are mapped on top of each
other during the linking step.
EOS
end
end
def check_for_multiple_volumes
return unless OS.mac?
return unless HOMEBREW_CELLAR.exist?
volumes = Volumes.new
# Find the volumes for the TMP folder & HOMEBREW_CELLAR
real_cellar = HOMEBREW_CELLAR.realpath
tmp = Pathname.new with_system_path { `mktemp -d #{HOMEBREW_TEMP}/homebrew-brew-doctor-XXXXXX` }.strip
real_temp = tmp.realpath.parent
where_cellar = volumes.which real_cellar
where_temp = volumes.which real_temp
Dir.delete tmp
unless where_cellar == where_temp then <<-EOS.undent
Your Cellar and TEMP directories are on different volumes.
OS X won't move relative symlinks across volumes unless the target file already
exists. Brews known to be affected by this are Git and Narwhal.
You should set the "HOMEBREW_TEMP" environmental variable to a suitable
directory on the same volume as your Cellar.
EOS
end
end
def check_filesystem_case_sensitive
return unless OS.mac?
volumes = Volumes.new
case_sensitive_vols = [HOMEBREW_PREFIX, HOMEBREW_REPOSITORY, HOMEBREW_CELLAR, HOMEBREW_TEMP].select do |dir|
# We select the dir as being case-sensitive if either the UPCASED or the
# downcased variant is missing.
# Of course, on a case-insensitive fs, both exist because the os reports so.
# In the rare situation when the user has indeed a downcased and an upcased
# dir (e.g. /TMP and /tmp) this check falsely thinks it is case-insensitive
# but we don't care beacuse: 1. there is more than one dir checked, 2. the
# check is not vital and 3. we would have to touch files otherwise.
upcased = Pathname.new(dir.to_s.upcase)
downcased = Pathname.new(dir.to_s.downcase)
dir.exist? && !(upcased.exist? && downcased.exist?)
end.map { |case_sensitive_dir| volumes.get_mounts(case_sensitive_dir) }.uniq
return if case_sensitive_vols.empty?
<<-EOS.undent
The filesystem on #{case_sensitive_vols.join(",")} appears to be case-sensitive.
The default OS X filesystem is case-insensitive. Please report any apparent problems.
EOS
end
def __check_git_version
# https://help.github.com/articles/https-cloning-errors
`git --version`.chomp =~ /git version ((?:\d+\.?)+)/
if $1 and Version.new($1) < Version.new("1.7.10") then <<-EOS.undent
An outdated version of Git was detected in your PATH.
Git 1.7.10 or newer is required to perform checkouts over HTTPS from GitHub.
Please upgrade: brew upgrade git
EOS
end
end
def check_for_git
if git?
__check_git_version
else <<-EOS.undent
Git could not be found in your PATH.
Homebrew uses Git for several internal functions, and some formulae use Git
checkouts instead of stable tarballs. You may want to install Git:
brew install git
EOS
end
end
def check_git_newline_settings
return unless git?
autocrlf = `git config --get core.autocrlf`.chomp
if autocrlf == 'true' then <<-EOS.undent
Suspicious Git newline settings found.
The detected Git newline settings will cause checkout problems:
core.autocrlf = #{autocrlf}
If you are not routinely dealing with Windows-based projects,
consider removing these by running:
`git config --global core.autocrlf input`
EOS
end
end
def check_git_origin
return unless git? && (HOMEBREW_REPOSITORY/'.git').exist?
HOMEBREW_REPOSITORY.cd do
origin = `git config --get remote.origin.url`.strip
if origin.empty? then <<-EOS.undent
Missing git origin remote.
Without a correctly configured origin, Homebrew won't update
properly. You can solve this by adding the Homebrew remote:
cd #{HOMEBREW_REPOSITORY}
git remote add origin https://github.com/Homebrew/#{OS::GITHUB_REPOSITORY}.git
EOS
elsif origin !~ /(mxcl|Homebrew)\/#{OS::GITHUB_REPOSITORY}(\.git)?$/ then <<-EOS.undent
Suspicious git origin remote found.
With a non-standard origin, Homebrew won't pull updates from
the main repository. The current git origin is:
#{origin}
Unless you have compelling reasons, consider setting the
origin remote to point at the main repository, located at:
https://github.com/Homebrew/#{OS::GITHUB_REPOSITORY}.git
EOS
end
end
end
def check_for_autoconf
return unless MacOS::Xcode.provides_autotools?
autoconf = which('autoconf')
safe_autoconfs = %w[/usr/bin/autoconf /Developer/usr/bin/autoconf]
unless autoconf.nil? or safe_autoconfs.include? autoconf.to_s then <<-EOS.undent
An "autoconf" in your path blocks the Xcode-provided version at:
#{autoconf}
This custom autoconf may cause some Homebrew formulae to fail to compile.
EOS
end
end
def __check_linked_brew f
links_found = []
prefix = f.prefix
prefix.find do |src|
next if src == prefix
dst = HOMEBREW_PREFIX + src.relative_path_from(prefix)
next if !dst.symlink? || !dst.exist? || src != dst.resolved_path
if src.directory?
Find.prune
else
links_found << dst
end
end
return links_found
end
def check_for_linked_keg_only_brews
return unless HOMEBREW_CELLAR.exist?
warnings = Hash.new
Formula.each do |f|
next unless f.keg_only? and f.installed?
links = __check_linked_brew f
warnings[f.name] = links unless links.empty?
end
unless warnings.empty?
s = <<-EOS.undent
Some keg-only formula are linked into the Cellar.
Linking a keg-only formula, such as gettext, into the cellar with
`brew link <formula>` will cause other formulae to detect them during
the `./configure` step. This may cause problems when compiling those
other formulae.
Binaries provided by keg-only formulae may override system binaries
with other strange results.
You may wish to `brew unlink` these brews:
EOS
warnings.each_key { |f| s << " #{f}\n" }
s
end
end
def check_for_other_frameworks
# Other frameworks that are known to cause problems when present
%w{expat.framework libexpat.framework libcurl.framework}.
map{ |frmwrk| "/Library/Frameworks/#{frmwrk}" }.
select{ |frmwrk| File.exist? frmwrk }.
map do |frmwrk| <<-EOS.undent
#{frmwrk} detected
This can be picked up by CMake's build system and likely cause the build to
fail. You may need to move this file out of the way to compile CMake.
EOS
end.join
end
def check_tmpdir
tmpdir = ENV['TMPDIR']
"TMPDIR #{tmpdir.inspect} doesn't exist." unless tmpdir.nil? or File.directory? tmpdir
end
def check_homebrew_temp_executable
file = Pathname.new "#{HOMEBREW_TEMP}/check_homebrew_temp_executable"
FileUtils.rm_f file
file.write "#!/bin/sh\n", 0700
unless system(file) then <<-EOS.undent
The disk volume of #{HOMEBREW_TEMP} is not executable.
Set the HOMEBREW_TEMP environment varible to a directory that is mounted on
an executable volume.
For example:
export HOMEBREW_TEMP=/var/tmp
or
export HOMEBREW_TEMP=#{HOMEBREW_PREFIX}/tmp
EOS
end
ensure
FileUtils.rm_f file
end
def check_missing_deps
return unless HOMEBREW_CELLAR.exist?
missing = Set.new
Homebrew.missing_deps(Formula.installed).each_value do |deps|
missing.merge(deps)
end
if missing.any? then <<-EOS.undent
Some installed formula are missing dependencies.
You should `brew install` the missing dependencies:
brew install #{missing.sort_by(&:name) * " "}
Run `brew missing` for more details.
EOS
end
end
def check_git_status
return unless git?
HOMEBREW_REPOSITORY.cd do
unless `git status --untracked-files=all --porcelain -- Library/Homebrew/ 2>/dev/null`.chomp.empty?
<<-EOS.undent_________________________________________________________72
You have uncommitted modifications to Homebrew
If this a surprise to you, then you should stash these modifications.
Stashing returns Homebrew to a pristine state but can be undone
should you later need to do so for some reason.
cd #{HOMEBREW_LIBRARY} && git stash && git clean -d -f
EOS
end
end
end
def check_git_ssl_verify
return unless OS.mac?
if MacOS.version <= :leopard && !ENV['GIT_SSL_NO_VERIFY'] then <<-EOS.undent
The version of libcurl provided with Mac OS X #{MacOS.version} has outdated
SSL certificates.
This can cause problems when running Homebrew commands that use Git to
fetch over HTTPS, e.g. `brew update` or installing formulae that perform
Git checkouts.
You can force Git to ignore these errors:
export GIT_SSL_NO_VERIFY=1
or
git config --global http.sslVerify false
EOS
end
end
def check_for_enthought_python
if which "enpkg" then <<-EOS.undent
Enthought Python was found in your PATH.
This can cause build problems, as this software installs its own
copies of iconv and libxml2 into directories that are picked up by
other build systems.
EOS
end
end
def check_for_library_python
if File.exist?("/Library/Frameworks/Python.framework") then <<-EOS.undent
Python is installed at /Library/Frameworks/Python.framework
Homebrew only supports building against the System-provided Python or a
brewed Python. In particular, Pythons installed to /Library can interfere
with other software installs.
EOS
end
end
def check_for_old_homebrew_share_python_in_path
s = ''
['', '3'].map do |suffix|
if paths.include?((HOMEBREW_PREFIX/"share/python#{suffix}").to_s)
s += "#{HOMEBREW_PREFIX}/share/python#{suffix} is not needed in PATH.\n"
end
end
unless s.empty?
s += <<-EOS.undent
Formerly homebrew put Python scripts you installed via `pip` or `pip3`
(or `easy_install`) into that directory above but now it can be removed
from your PATH variable.
Python scripts will now install into #{HOMEBREW_PREFIX}/bin.
You can delete anything, except 'Extras', from the #{HOMEBREW_PREFIX}/share/python
(and #{HOMEBREW_PREFIX}/share/python3) dir and install affected Python packages
anew with `pip install --upgrade`.
EOS
end
end
def check_for_bad_python_symlink
return unless which "python"
`python -V 2>&1` =~ /Python (\d+)\./
# This won't be the right warning if we matched nothing at all
return if $1.nil?
unless $1 == "2" then <<-EOS.undent
python is symlinked to python#$1
This will confuse build scripts and in general lead to subtle breakage.
EOS
end
end
def check_for_non_prefixed_coreutils
gnubin = "#{Formulary.factory('coreutils').prefix}/libexec/gnubin"
if paths.include? gnubin then <<-EOS.undent
Putting non-prefixed coreutils in your path can cause gmp builds to fail.
EOS
end
end
def check_for_non_prefixed_findutils
return unless OS.mac?
default_names = Tab.for_name('findutils').with? "default-names"
if default_names then <<-EOS.undent
Putting non-prefixed findutils in your path can cause python builds to fail.
EOS
end
end
def check_for_pydistutils_cfg_in_home
if File.exist? "#{ENV['HOME']}/.pydistutils.cfg" then <<-EOS.undent
A .pydistutils.cfg file was found in $HOME, which may cause Python
builds to fail. See:
http://bugs.python.org/issue6138
http://bugs.python.org/issue4655
EOS
end
end
def check_for_outdated_homebrew
return unless git?
HOMEBREW_REPOSITORY.cd do
if File.directory? ".git"
local = `git rev-parse -q --verify refs/remotes/origin/master`.chomp
remote = /^([a-f0-9]{40})/.match(`git ls-remote origin refs/heads/master 2>/dev/null`)
if remote.nil? || local == remote[0]
return
end
end
timestamp = if File.directory? ".git"
`git log -1 --format="%ct" HEAD`.to_i
else
HOMEBREW_LIBRARY.mtime.to_i
end
if Time.now.to_i - timestamp > 60 * 60 * 24 then <<-EOS.undent
Your Homebrew is outdated.
You haven't updated for at least 24 hours. This is a long time in brewland!
To update Homebrew, run `brew update`.
EOS
end
end
end
def check_for_unlinked_but_not_keg_only
return unless HOMEBREW_CELLAR.exist?
unlinked = HOMEBREW_CELLAR.children.reject do |rack|
if not rack.directory?
true
elsif not (HOMEBREW_REPOSITORY/"Library/LinkedKegs"/rack.basename).directory?
begin
Formulary.factory(rack.basename.to_s).keg_only?
rescue FormulaUnavailableError
false
end
else
true
end
end.map{ |pn| pn.basename }
if not unlinked.empty? then <<-EOS.undent
You have unlinked kegs in your Cellar
Leaving kegs unlinked can lead to build-trouble and cause brews that depend on
those kegs to fail to run properly once built. Run `brew link` on these:
#{unlinked * "\n "}
EOS
end
end
def check_xcode_license_approved
# If the user installs Xcode-only, they have to approve the
# license or no "xc*" tool will work.
if `/usr/bin/xcrun clang 2>&1` =~ /license/ and not $?.success? then <<-EOS.undent
You have not agreed to the Xcode license.
Builds will fail! Agree to the license by opening Xcode.app or running:
xcodebuild -license
EOS
end
end
def check_for_latest_xquartz
return unless MacOS::XQuartz.version
return if MacOS::XQuartz.provided_by_apple?
installed_version = Version.new(MacOS::XQuartz.version)
latest_version = Version.new(MacOS::XQuartz.latest_version)
return if installed_version >= latest_version
<<-EOS.undent
Your XQuartz (#{installed_version}) is outdated
Please install XQuartz #{latest_version}:
https://xquartz.macosforge.org
EOS
end
def check_for_old_env_vars
if ENV["HOMEBREW_KEEP_INFO"]
<<-EOS.undent
`HOMEBREW_KEEP_INFO` is no longer used
info files are no longer deleted by default; you may
remove this environment variable.
EOS
end
end
def check_for_pth_support
homebrew_site_packages = Language::Python.homebrew_site_packages
return unless homebrew_site_packages.directory?
return if Language::Python.reads_brewed_pth_files?("python") != false
return unless Language::Python.in_sys_path?("python", homebrew_site_packages)
user_site_packages = Language::Python.user_site_packages "python"
<<-EOS.undent
Your default Python does not recognize the Homebrew site-packages
directory as a special site-packages directory, which means that .pth
files will not be followed. This means you will not be able to import
some modules after installing them with Homebrew, like wxpython. To fix
this for the current user, you can run:
mkdir -p #{user_site_packages}
echo 'import site; site.addsitedir("#{homebrew_site_packages}")' >> #{user_site_packages}/homebrew.pth
EOS
end
def all
methods.map(&:to_s).grep(/^check_/)
end
end # end class Checks
module Homebrew
def doctor
checks = Checks.new
if ARGV.include? '--list-checks'
puts checks.all.sort
exit
end
inject_dump_stats(checks) if ARGV.switch? 'D'
if ARGV.named.empty?
methods = checks.all.sort
methods << "check_for_linked_keg_only_brews" << "check_for_outdated_homebrew"
methods = methods.reverse.uniq.reverse
else
methods = ARGV.named
end
first_warning = true
methods.each do |method|
out = checks.send(method)
unless out.nil? or out.empty?
if first_warning
puts <<-EOS.undent
#{Tty.white}Please note that these warnings are just used to help the Homebrew maintainers
with debugging if you file an issue. If everything you use Homebrew for is
working fine: please don't worry and just ignore them. Thanks!#{Tty.reset}
EOS
end
puts
opoo out
Homebrew.failed = true
first_warning = false
end
end
puts "Your system is ready to brew." unless Homebrew.failed?
end
def inject_dump_stats checks
checks.extend Module.new {
def send(method, *)
time = Time.now
super
ensure
$times[method] = Time.now - time
end
}
$times = {}
at_exit {
puts $times.sort_by{|k, v| v }.map{|k, v| "#{k}: #{v}"}
}
end
end
| 31.290652 | 110 | 0.692089 |
286e15f4d31ca51e25b64b4a1ee8498e85ecc520 | 366 | module Popularity
class Github < Crawler
stats :stars
def stars
response_json.size
end
def valid?
host == 'github.com'
end
protected
def request_url
parts = @url.split("/").last(2)
repo = parts.last
owner = parts.first
"https://api.github.com/repos/#{owner}/#{repo}/stargazers"
end
end
end
| 15.913043 | 64 | 0.587432 |
f75f716c6d722f799e13338e07e9e90beb452841 | 1,352 | require 'spec_helper'
require 'airenv/sdk'
describe Airenv::Sdk do
subject { Airenv::Sdk.new }
let(:description) { Airenv::SdkDescription.new("AIR 4.5.6", "4.5.6", 5678) }
describe '#package_uri' do
before do
subject.description = description
end
its(:package_uri) { should == "http://airdownload.adobe.com/air/mac/download/4.5/AIRSDK_Compiler.tbz2" }
end
describe '#simple_version' do
before do
subject.description = description
end
its(:simple_version) { should == "4.5" }
end
describe '#parse_version_id' do
context 'given build number' do
before do
subject.description = description
subject.parse_version_id("4.5-b1234")
end
its(:simple_version) { should == "4.5" }
its("description.build") { should == 1234 }
end
context 'not given build number' do
before do
subject.parse_version_id("4.6")
end
its(:simple_version) { should == "4.6" }
its("description.build") { should be_nil }
end
end
describe '#package_name' do
before do
subject.description = description
end
its(:package_name) { should == "AIRSDK_4.5.6-b5678" }
end
describe '#simple_name' do
before do
subject.description = description
end
its(:simple_name) { should == "AIRSDK_4.5" }
end
end
| 22.163934 | 108 | 0.633876 |
38659ec07dc61c562f3255f8b3303ad9c4808cbe | 2,613 | describe "miq_ae_class/_ns_list.html.haml" do
include Spec::Support::AutomationHelper
context 'render' do
def setup_namespace_form(dom)
assign(:in_a_form, true)
assign(:ae_ns, dom)
assign(:edit, :new => {:ns_name => dom.name, :ns_description => "test"})
end
describe "Git domain" do
before do
dom = FactoryBot.create(:miq_ae_git_domain)
setup_namespace_form(dom)
end
it "with name_readonly and description_readonly set to true", :js => true do
render
expect(response).to have_css("namespace-form[name_readonly='true']")
expect(response).to have_css("namespace-form[description_readonly='true']")
end
it "with ae_ns_domain set to true", :js => true do
render
expect(response).to have_css("namespace-form[ae_ns_domain='true']")
end
it "with empty namespace_path", :js => true do
render
expect(response).to have_css("namespace-form[namespace_path='']")
end
end
describe "User domain" do
before do
dom = FactoryBot.create(:miq_ae_domain)
setup_namespace_form(dom)
end
it "with name_readonly and description_readonly set to false", :js => true do
render
expect(response).to have_css("namespace-form[name_readonly='false']")
expect(response).to have_css("namespace-form[description_readonly='false']")
end
it "with ae_ns_domain set to true", :js => true do
render
expect(response).to have_css("namespace-form[ae_ns_domain='true']")
end
it "with empty namespace_path", :js => true do
render
expect(response).to have_css("namespace-form[namespace_path='']")
end
end
describe "Namespace" do
before do
dom = FactoryBot.create(:miq_ae_namespace, :parent => FactoryBot.create(:miq_ae_domain))
assign(:sb, :namespace_path => 'namespace/path')
setup_namespace_form(dom)
end
it "with name_readonly and description_readonly set to false", :js => true do
render
expect(response).to have_css("namespace-form[name_readonly='false']")
expect(response).to have_css("namespace-form[description_readonly='false']")
end
it "with ae_ns_domain set to true", :js => true do
render
expect(response).to have_css("namespace-form[ae_ns_domain='false']")
end
it "Check Git enabled domain", :js => true do
render
expect(response).to have_css("namespace-form[namespace_path='namespace/path']")
end
end
end
end
| 31.865854 | 96 | 0.642556 |
875ba5357a30189b93d538baaf9a251eb8f7b808 | 2,219 | require 'spec_helper'
require 'sisimai'
require 'sisimai/mail/maildir'
require 'sisimai/message'
require 'json'
cannotparse = './set-of-emails/to-be-debugged-because/sisimai-cannot-parse-yet'
if File.exist?(cannotparse)
describe Sisimai do
it 'returns nil' do
expect(Sisimai.make(cannotparse)).to be nil
end
end
describe Sisimai::Mail::Maildir do
maildir = Sisimai::Mail::Maildir.new(cannotparse)
describe 'Sisimai::Mail::Maildir' do
it 'is Sisimai::Mail::Maildir' do
expect(maildir).to be_a Sisimai::Mail::Maildir
end
describe 'each method' do
example '#dir returns directory name' do
expect(maildir.dir).to be == cannotparse
end
example '#file retuns nil' do
expect(maildir.file).to be nil
end
example '#inodes is Hash' do
expect(maildir.inodes).to be_a Hash
end
example '#handle is Dir' do
expect(maildir.handle).to be_a Dir
end
describe '#read' do
mailobj = Sisimai::Mail::Maildir.new(cannotparse)
mailtxt = mailobj.data.read
it 'returns message string' do
expect(mailtxt).to be_a String
expect(mailtxt.size).to be > 0
end
end
end
end
end
describe Sisimai::Message do
seekhandle = Dir.open(cannotparse)
mailastext = ''
while r = seekhandle.read do
next if r == '.' || r == '..'
emailindir = sprintf('%s/%s', cannotparse, r)
emailindir = emailindir.squeeze('/')
next unless File.ftype(emailindir) == 'file'
next unless File.size(emailindir) > 0
next unless File.readable?(emailindir)
filehandle = File.open(emailindir,'r')
mailastext = filehandle.read
filehandle.close
it 'returns String' do
expect(mailastext).to be_a String
expect(mailastext.size).to be > 0
end
p = Sisimai::Message.new(data: mailastext)
it 'returns Sisimai::Message' do
expect(p).to be_a Sisimai::Message
expect(p.ds).to be nil
expect(p.from).to be nil
expect(p.rfc822).to be nil
expect(p.header).to be nil
end
end
end
end
| 26.416667 | 79 | 0.612438 |
edff3eab49f28f9476ee09f6d34aec003cfdc627 | 4,705 | module Fog
module Compute
class AWS
class Real
require 'fog/aws/parsers/compute/basic'
# Creates a route in a route table within a VPC.
#
# ==== Parameters
# * RouteTableId<~String> - The ID of the route table for the route.
# * DestinationCidrBlock<~String> - The CIDR address block used for the destination match. Routing decisions are based on the most specific match.
# * GatewayId<~String> - The ID of an Internet gateway attached to your VPC.
# * InstanceId<~String> - The ID of a NAT instance in your VPC. The operation fails if you specify an instance ID unless exactly one network interface is attached.
# * NetworkInterfaceId<~String> - The ID of a network interface.
#
# === Returns
# * response<~Excon::Response>:
# * body<~Hash>:
# * 'requestId'<~String> - Id of the request
# * 'return'<~Boolean> - Returns true if the request succeeds. Otherwise, returns an error.
#
# {Amazon API Reference}[http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateRoute.html]
def create_route(route_table_id, destination_cidr_block, internet_gateway_id=nil, instance_id=nil, network_interface_id=nil)
request_vars = {
'Action' => 'CreateRoute',
'RouteTableId' => route_table_id,
'DestinationCidrBlock' => destination_cidr_block,
:parser => Fog::Parsers::Compute::AWS::Basic.new
}
if internet_gateway_id
request_vars['GatewayId'] = internet_gateway_id
elsif instance_id
request_vars['InstanceId'] = instance_id
elsif network_interface_id
request_vars['NetworkInterfaceId'] = network_interface_id
end
request(request_vars)
end
end
class Mock
def create_route(route_table_id, destination_cidr_block, internet_gateway_id=nil, instance_id=nil, network_interface_id=nil)
instance_owner_id = nil
route_table = self.data[:route_tables].find { |routetable| routetable["routeTableId"].eql? route_table_id }
if !route_table.nil? && destination_cidr_block
if !internet_gateway_id.nil? || !instance_id.nil? || !network_interface_id.nil?
if !internet_gateway_id.nil? && self.internet_gateways.all('internet-gateway-id'=>internet_gateway_id).first.nil?
raise Fog::Compute::AWS::NotFound.new("The gateway ID '#{internet_gateway_id}' does not exist")
elsif !instance_id.nil? && self.servers.all('instance-id'=>instance_id).first.nil?
raise Fog::Compute::AWS::NotFound.new("The instance ID '#{instance_id}' does not exist")
elsif !network_interface_id.nil? && self.network_interfaces.all('networkInterfaceId'=>network_interface_id).first.nil?
raise Fog::Compute::AWS::NotFound.new("The networkInterface ID '#{network_interface_id}' does not exist")
elsif !route_table['routeSet'].find { |route| route['destinationCidrBlock'].eql? destination_cidr_block }.nil?
raise Fog::Compute::AWS::Error, "RouteAlreadyExists => The route identified by #{destination_cidr_block} already exists."
else
response = Excon::Response.new
route_table['routeSet'].push({
"destinationCidrBlock" => destination_cidr_block,
"gatewayId" => internet_gateway_id,
"instanceId"=>instance_id,
"instanceOwnerId"=>instance_owner_id,
"networkInterfaceId"=>network_interface_id,
"state" => "pending",
"origin" => "CreateRoute"
})
response.status = 200
response.body = {
'requestId'=> Fog::AWS::Mock.request_id,
'return' => true
}
response
end
else
message = 'MissingParameter => '
message << 'The request must contain either a gateway id, a network interface id, or an instance id'
raise Fog::Compute::AWS::Error.new(message)
end
elsif route_table.nil?
raise Fog::Compute::AWS::NotFound.new("The routeTable ID '#{route_table_id}' does not exist")
elsif destination_cidr_block.empty?
raise Fog::Compute::AWS::InvalidParameterValue.new("Value () for parameter destinationCidrBlock is invalid. This is not a valid CIDR block.")
end
end
end
end
end
end
| 52.277778 | 171 | 0.612327 |
010c960ec51500c2eac89e6fc3eca6091ce5a7b4 | 809 | #
# tkextlib/bwidget/scrollableframe.rb
# by Hidetoshi NAGAI ([email protected])
#
require 'tk'
require 'tk/frame'
require 'tkextlib/bwidget.rb'
module Tk
module BWidget
class ScrollableFrame < TkWindow
end
end
end
class Tk::BWidget::ScrollableFrame
include Scrollable
TkCommandNames = ['ScrollableFrame'.freeze].freeze
WidgetClassName = 'ScrollableFrame'.freeze
WidgetClassNames[WidgetClassName] = self
def get_frame(&b)
win = window(tk_send_without_enc('getframe'))
if b
if TkCore::WITH_RUBY_VM ### Ruby 1.9 !!!!
win.instance_exec(self, &b)
else
win.instance_eval(&b)
end
end
win
end
def see(win, vert=None, horiz=None)
tk_send_without_enc('see', win, vert, horiz)
self
end
end
| 19.731707 | 75 | 0.656366 |
1cee61f86e008056ef958600bbb339e4cd230f03 | 502 | module Gitlab
module Git
class BlobSnippet
attr_accessor :ref
attr_accessor :lines
attr_accessor :filename
attr_accessor :startline
def initialize(ref, lines, startline, filename)
@ref, @lines, @startline, @filename = ref, lines, startline, filename
end
def data
lines.join("\n")
end
def name
filename
end
def size
data.length
end
def mode
nil
end
end
end
end
| 15.6875 | 77 | 0.567729 |
ab072438692ed8fdc2d7544f51f9471eaa3bae6e | 733 | module JupiterCore
extend ActiveSupport::Autoload
class ObjectNotFound < StandardError; end
class PropertyInvalidError < StandardError; end
class MultipleIdViolationError < StandardError; end
class AlreadyDefinedError < StandardError; end
class LockedInstanceError < StandardError; end
class SolrNameManglingError < StandardError; end
class VocabularyMissingError < StandardError; end
VISIBILITY_PUBLIC = CONTROLLED_VOCABULARIES[:visibility].public.freeze
VISIBILITY_PRIVATE = CONTROLLED_VOCABULARIES[:visibility].private.freeze
VISIBILITY_AUTHENTICATED = CONTROLLED_VOCABULARIES[:visibility].authenticated.freeze
VISIBILITIES = [VISIBILITY_PUBLIC, VISIBILITY_PRIVATE, VISIBILITY_AUTHENTICATED].freeze
end
| 40.722222 | 89 | 0.834925 |
03ce600cc44055d99fc5e40153907785c93e1ac5 | 12,222 | # frozen_string_literal: true
require 'rubygems/installer_test_case'
require 'rubygems/commands/uninstall_command'
class TestGemCommandsUninstallCommand < Gem::InstallerTestCase
def setup
super
@cmd = Gem::Commands::UninstallCommand.new
@executable = File.join(@gemhome, 'bin', 'executable')
end
def test_execute_all_named
initial_install
util_make_gems
default = new_default_spec 'default', '1'
install_default_gems default
gemhome2 = "#{@gemhome}2"
a_4, = util_gem 'a', 4
install_gem a_4, :install_dir => gemhome2
Gem::Specification.dirs = [@gemhome, gemhome2]
assert_includes Gem::Specification.all_names, 'a-1'
assert_includes Gem::Specification.all_names, 'a-4'
assert_includes Gem::Specification.all_names, 'b-2'
assert_includes Gem::Specification.all_names, 'default-1'
@cmd.options[:all] = true
@cmd.options[:args] = %w[a]
use_ui @ui do
@cmd.execute
end
assert_equal %w[a_evil-9 b-2 c-1.2 default-1 dep_x-1 pl-1-x86-linux x-1],
Gem::Specification.all_names.sort
end
def test_execute_all_named_default_single
z_1 = new_default_spec 'z', '1'
install_default_gems z_1
assert_includes Gem::Specification.all_names, 'z-1'
@cmd.options[:all] = true
@cmd.options[:args] = %w[z]
use_ui @ui do
@cmd.execute
end
assert_equal %w[z-1], Gem::Specification.all_names.sort
output = @ui.output.split "\n"
assert_equal 'Gem z-1 cannot be uninstalled because it is a default gem', output.shift
end
def test_execute_all_named_default_multiple
z_1 = new_default_spec 'z', '1'
install_default_gems z_1
z_2, = util_gem 'z', 2
install_gem z_2
assert_includes Gem::Specification.all_names, 'z-1'
assert_includes Gem::Specification.all_names, 'z-2'
@cmd.options[:all] = true
@cmd.options[:args] = %w[z]
use_ui @ui do
@cmd.execute
end
assert_equal %w[z-1], Gem::Specification.all_names.sort
output = @ui.output.split "\n"
assert_equal 'Gem z-1 cannot be uninstalled because it is a default gem', output.shift
assert_equal 'Successfully uninstalled z-2', output.shift
end
def test_execute_dependency_order
initial_install
c = quick_gem 'c' do |spec|
spec.add_dependency 'a'
end
util_build_gem c
installer = util_installer c, @gemhome
use_ui @ui do
installer.install
end
ui = Gem::MockGemUi.new
@cmd.options[:args] = %w[a c]
@cmd.options[:executables] = true
use_ui ui do
@cmd.execute
end
output = ui.output.split "\n"
assert_equal 'Successfully uninstalled c-2', output.shift
assert_equal "Removing executable", output.shift
assert_equal 'Successfully uninstalled a-2', output.shift
end
def test_execute_removes_executable
initial_install
if win_platform?
assert File.exist?(@executable)
else
assert File.symlink?(@executable)
end
# Evil hack to prevent false removal success
FileUtils.rm_f @executable
File.open @executable, "wb+" do |f|
f.puts "binary"
end
@cmd.options[:executables] = true
@cmd.options[:args] = [@spec.name]
use_ui @ui do
@cmd.execute
end
output = @ui.output.split "\n"
assert_match(/Removing executable/, output.shift)
assert_match(/Successfully uninstalled/, output.shift)
assert_equal false, File.exist?(@executable)
assert_nil output.shift, "UI output should have contained only two lines"
end
def test_execute_removes_formatted_executable
installer = setup_base_installer
FileUtils.rm_f @executable # Wish this didn't happen in #setup
Gem::Installer.exec_format = 'foo-%s-bar'
installer.format_executable = true
installer.install
formatted_executable = File.join @gemhome, 'bin', 'foo-executable-bar'
assert_equal true, File.exist?(formatted_executable)
@cmd.options[:executables] = true
@cmd.options[:format_executable] = true
@cmd.execute
assert_equal false, File.exist?(formatted_executable)
rescue
Gem::Installer.exec_format = nil
end
def test_execute_prerelease
@spec = util_spec "pre", "2.b"
@gem = File.join @tempdir, @spec.file_name
FileUtils.touch @gem
installer = util_setup_gem
build_rake_in do
use_ui @ui do
installer.install
end
end
@cmd.options[:executables] = true
@cmd.options[:args] = ["pre"]
use_ui @ui do
@cmd.execute
end
output = @ui.output
assert_match(/Successfully uninstalled/, output)
end
def test_execute_with_version_leaves_non_matching_versions
initial_install
ui = Gem::MockGemUi.new
util_make_gems
assert_equal 3, Gem::Specification.find_all_by_name('a').length
@cmd.options[:version] = '1'
@cmd.options[:force] = true
@cmd.options[:args] = ['a']
use_ui ui do
@cmd.execute
end
assert_equal 2, Gem::Specification.find_all_by_name('a').length
assert File.exist? File.join(@gemhome, 'bin', 'executable')
end
def test_execute_with_version_specified_as_colon
initial_install
ui = Gem::MockGemUi.new "y\n"
util_make_gems
assert_equal 3, Gem::Specification.find_all_by_name('a').length
@cmd.options[:force] = true
@cmd.options[:args] = ['a:1']
use_ui ui do
@cmd.execute
end
assert_equal 2, Gem::Specification.find_all_by_name('a').length
assert File.exist? File.join(@gemhome, 'bin', 'executable')
end
def test_uninstall_selection
ui = Gem::MockGemUi.new "1\n"
util_make_gems
list = Gem::Specification.find_all_by_name 'a'
@cmd.options[:args] = ['a']
use_ui ui do
@cmd.execute
end
updated_list = Gem::Specification.find_all_by_name('a')
assert_equal list.length - 1, updated_list.length
assert_match ' 1. a-1', ui.output
assert_match ' 2. a-2', ui.output
assert_match ' 3. a-3.a', ui.output
assert_match ' 4. All versions', ui.output
assert_match 'uninstalled a-1', ui.output
end
def test_uninstall_selection_multiple_gems
ui = Gem::MockGemUi.new "1\n"
util_make_gems
a_list = Gem::Specification.find_all_by_name('a')
b_list = Gem::Specification.find_all_by_name('b')
list = a_list + b_list
@cmd.options[:args] = ['a', 'b']
use_ui ui do
@cmd.execute
end
updated_a_list = Gem::Specification.find_all_by_name('a')
updated_b_list = Gem::Specification.find_all_by_name('b')
updated_list = updated_a_list + updated_b_list
assert_equal list.length - 2, updated_list.length
out = ui.output.split("\n")
assert_match 'uninstalled b-2', out.shift
assert_match '', out.shift
assert_match 'Select gem to uninstall:', out.shift
assert_match ' 1. a-1', out.shift
assert_match ' 2. a-2', out.shift
assert_match ' 3. a-3.a', out.shift
assert_match ' 4. All versions', out.shift
assert_match 'uninstalled a-1', out.shift
assert_empty out
end
def test_execute_with_force_and_without_version_uninstalls_everything
initial_install
ui = Gem::MockGemUi.new "y\n"
a_1, = util_gem 'a', 1
install_gem a_1
a_3a, = util_gem 'a', '3.a'
install_gem a_3a
assert_equal 3, Gem::Specification.find_all_by_name('a').length
@cmd.options[:force] = true
@cmd.options[:args] = ['a']
use_ui ui do
@cmd.execute
end
assert_empty Gem::Specification.find_all_by_name('a')
assert_match "Removing executable", ui.output
refute File.exist? @executable
end
def test_execute_with_force_ignores_dependencies
initial_install
ui = Gem::MockGemUi.new
util_make_gems
assert Gem::Specification.find_all_by_name('dep_x').length > 0
assert Gem::Specification.find_all_by_name('x').length > 0
@cmd.options[:force] = true
@cmd.options[:args] = ['x']
use_ui ui do
@cmd.execute
end
assert Gem::Specification.find_all_by_name('dep_x').length > 0
assert Gem::Specification.find_all_by_name('x').length.zero?
end
def test_execute_all
util_make_gems
default = new_default_spec 'default', '1'
install_default_gems default
gemhome2 = "#{@gemhome}2"
a_4, = util_gem 'a', 4
install_gem a_4
Gem::Specification.dirs = [@gemhome, gemhome2]
assert_includes Gem::Specification.all_names, 'a-1'
assert_includes Gem::Specification.all_names, 'a-4'
assert_includes Gem::Specification.all_names, 'default-1'
@cmd.options[:all] = true
@cmd.options[:args] = []
use_ui @ui do
@cmd.execute
end
assert_equal %w[default-1], Gem::Specification.all_names.sort
assert_equal "INFO: Uninstalled all gems in #{@gemhome}", @ui.output.split("\n").last
end
def test_execute_outside_gem_home
ui = Gem::MockGemUi.new "y\n"
gemhome2 = "#{@gemhome}2"
a_4, = util_gem 'a', 4
install_gem a_4 , :install_dir => gemhome2
Gem::Specification.dirs = [@gemhome, gemhome2]
assert_includes Gem::Specification.all_names, 'a-4'
@cmd.options[:args] = ['a:4']
e = assert_raises Gem::InstallError do
use_ui ui do
@cmd.execute
end
end
assert_includes e.message, "a is not installed in GEM_HOME"
end
def test_handle_options
@cmd.handle_options %w[]
assert_equal false, @cmd.options[:check_dev]
assert_nil @cmd.options[:install_dir]
assert_equal true, @cmd.options[:user_install]
assert_equal Gem::Requirement.default, @cmd.options[:version]
assert_equal false, @cmd.options[:vendor]
end
def test_handle_options_vendor
vendordir(File.join(@tempdir, 'vendor')) do
use_ui @ui do
@cmd.handle_options %w[--vendor]
end
assert @cmd.options[:vendor]
assert_equal Gem.vendor_dir, @cmd.options[:install_dir]
assert_empty @ui.output
expected = <<-EXPECTED
WARNING: Use your OS package manager to uninstall vendor gems
EXPECTED
assert_match expected, @ui.error
end
end
def test_execute_two_version
@cmd.options[:args] = %w[a b]
@cmd.options[:version] = Gem::Requirement.new("> 1")
use_ui @ui do
e = assert_raises Gem::MockGemUi::TermError do
@cmd.execute
end
assert_equal 1, e.exit_code
end
msg = "ERROR: Can't use --version with multiple gems. You can specify multiple gems with" \
" version requirements using `gem uninstall 'my_gem:1.0.0' 'my_other_gem:~>2.0.0'`"
assert_empty @ui.output
assert_equal msg, @ui.error.lines.last.chomp
end
def test_handle_options_vendor_missing
vendordir(nil) do
e = assert_raises OptionParser::InvalidOption do
@cmd.handle_options %w[--vendor]
end
assert_equal 'invalid option: --vendor your platform is not supported',
e.message
refute @cmd.options[:vendor]
refute @cmd.options[:install_dir]
end
end
def test_execute_with_gem_not_installed
@cmd.options[:args] = ['d']
use_ui ui do
@cmd.execute
end
output = ui.output.split "\n"
assert_equal output.first, "Gem 'd' is not installed"
end
def test_execute_with_gem_uninstall_error
initial_install
util_make_gems
@cmd.options[:args] = %w[a]
uninstall_exception = lambda do |_a|
ex = Gem::UninstallError.new
ex.spec = @spec
raise ex
end
e = nil
@cmd.stub :uninstall, uninstall_exception do
use_ui @ui do
e = assert_raises Gem::MockGemUi::TermError do
@cmd.execute
end
end
assert_equal 1, e.exit_code
end
assert_empty @ui.output
assert_match %r{Error: unable to successfully uninstall '#{@spec.name}'}, @ui.error
end
private
def initial_install
installer = setup_base_installer
common_installer_setup
build_rake_in do
use_ui @ui do
installer.install
end
end
end
end
| 24.20198 | 96 | 0.658321 |
f71395b7fd9590c1b0b21be293c1996ec2d9100e | 5,336 | module Freelancer
module API
module Common
module InstanceMethods
# Get a list of projects that are pending feedback
#
# Valid parameters are:
# - type: the type of projects to list ("P" or "B" (default))
def pending_feedback(*args)
params = extract_params(args)
# Execute the service call
result = api_get("/Common/getPendingFeedback.json", build_api_params({
:type => params[:type]
}))
# Parse and return the response
::Freelancer::Models::Project.parse_collection(result, :shift => [ :"json-result", :items ])
end
# Get the configuration version of a specific service function
#
# Valid parameters are:
# - function: the function to look up config version for
def config_version(*args)
params = extract_params(args)
# Execute the service call
result = api_get("/Common/getConfigVersion.json", build_api_params({
:function => params[:function]
}))
# Parse and return the response
::Freelancer::Models::ConfigVersion.parse(result, :shift => :"json-result")
end
# Returns the current Terms and Conditions from the site
def terms
result = api_get("/Common/getTerms.json")
json = JSONMapper::Parser.parse(result)
if !json.nil? && json.key?(:"json-result")
return json[:"json-result"][:terms]
end
return nil
end
# Request to cancel an awarded project
#
# Valid parameters are:
# - project_id: the id of the project to cancel
# - selected_winner: the id of the selected winner of the project
# - comment: the comment for the cancellation request
# - reason: the reason for cancelling the project
# - followed_guidelines: if the guidelines for cancelling the project has been followed
def request_cancel_project(*args)
params = extract_params(args)
# Execute the service call
result = api_get("/Common/requestCancelProject.json", build_api_params({
:projectid => params[:project_id],
:selectedwinner => params[:selected_winner],
:commenttext => params[:comment],
:reasoncancellation => params[:reason],
:followedguidelinesstatus => params[:followed_guidelines]
}))
# Parse and return the response
::Freelancer::Models::StatusConfirmation.parse(result, :shift => :"json-result")
end
# Post feedback for a user
#
# Valid parameters are:
# - project_id: the project id related to the feedback
# - user_id: the id of the user to rate
# - username: the username of the user to rate
# - comment: the feedback comment
# - rating: the feedback rating
def post_feedback(*args)
params = extract_params(args)
# Execute the service call
result = api_get("/Common/postFeedback.json", build_api_params({
:projectid => params[:project_id],
:userid => params[:user_id],
:username => params[:username],
:feedbacktext => params[:comment],
:rating => params[:rating]
}))
# Parse and return the response
::Freelancer::Models::StatusConfirmation.parse(result, :shift => :"json-result")
end
# Post reply to a feedback given to you
#
# Valid parameters are:
# - project_id: the id of the project related to the feedback
# - user_id: the id of the user to reply to
# - username: the username of the user to reply to
# - comment: the feedback comment
def post_feedback_reply(*args)
params = extract_params(args)
# Execute the service call
result = api_get("/Common/postReplyForFeedback.json", build_api_params({
:projectid => params[:project_id],
:userid => params[:user_id],
:username => params[:username],
:feedbacktext => params[:comment]
}))
# Parse and return the response
::Freelancer::Models::StatusConfirmation.parse(result, :shift => :"json-result")
end
# Request that posted feedback is withdrawn
#
# Valid parameters are:
# - project_id: the id of the project related to feedback
# - user_id: the user id the feedback is posted to
# - username: the username the feedback is posted to
def request_withdraw_feedback(*args)
params = extract_params(args)
# Execute the service call
result = api_get("/Common/requestWithdrawFeedback.json", build_api_params({
:projectid => params[:project_id],
:userid => params[:user_id],
:username => params[:username]
}))
# Parse and return the response
::Freelancer::Models::StatusConfirmation.parse(result, :shift => :"json-result")
end
end
module ClassMethods
end
end
end
end
| 33.559748 | 102 | 0.576649 |
38ac73d09610a535eac09e1f813718eee5d48433 | 122 | module CartHelper
def get_product(orderAuction)
product = Product.find(orderAuction.product_id)
end
end
| 10.166667 | 51 | 0.721311 |
d53ce1dbfb7cdc5520318dc5bc251c7f92dc37f1 | 862 | # frozen_string_literal: true
# dependencies class
class Object
def self.const_missing(const)
@calling_const_missing ||= {}
return nil if @calling_const_missing
@calling_const_missing[const] = true
require RulersJmvbxx.to_underscore(const.to_s)
klass = Object.const_get(const)
@calling_const_missing[const] = false
klass
end
# Comment on Chapter 3, Exercise 1
# My first reaction was to test the existence of the constant by using `Object.const_defined?("CONSTANT")`.
# The reasoning behind this was the comment in the book about Rails checking whether or not the constant exists
# before loading the file.
#
# Aside from that I struggled with this question and was forced to copy the provided answer. Admittedly, I am not
# familiar with mutexes in Ruby and I will need to investigate this topic in detail.
end
| 34.48 | 115 | 0.74942 |
e8fc69c72534870e18c44496973ab3eee326716c | 231 | class CreatePosts < ActiveRecord::Migration[6.0]
def change
create_table :posts do |t|
t.string :title
t.text :body
t.references :author, null: false, foreign_key: true
t.timestamps
end
end
end
| 19.25 | 58 | 0.649351 |
1cdbe385f6398551c41203bdcc215736278869fe | 663 | # frozen_string_literal: true
class FlyingSphinx::Commands::IndexSQL < FlyingSphinx::Commands::Base
def call
if async?
send_action 'index', indexing_options.merge(:unique => 'true')
else
clear_jobs
run_action 'index', index_timeout, indexing_options
end
end
private
def async?
indices.any? && !options[:verbose]
end
def clear_jobs
::Delayed::Job.
where("handler LIKE '--- !ruby/object:FlyingSphinx::%'").
delete_all if defined?(::Delayed) && ::Delayed::Job.table_exists?
end
def indexing_options
{:indices => indices.join(",")}
end
def indices
options[:indices] || []
end
end
| 19.5 | 71 | 0.650075 |
1c406f039453e992764ede96875919810d8adccf | 6,511 | require File.expand_path('../spec_helper', __FILE__)
load_extension("hash")
describe "C-API Hash function" do
before :each do
@s = CApiHashSpecs.new
end
describe "rb_hash" do
it "calls #hash on the object" do
obj = mock("rb_hash")
obj.should_receive(:hash).and_return(5)
@s.rb_hash(obj).should == 5
end
it "converts a Bignum returned by #hash to a Fixnum" do
obj = mock("rb_hash bignum")
obj.should_receive(:hash).and_return(bignum_value)
# The actual conversion is an implementation detail.
# We only care that ultimately we get a Fixnum instance.
@s.rb_hash(obj).should be_an_instance_of(Fixnum)
end
it "calls #to_int to converts a value returned by #hash to a Fixnum" do
obj = mock("rb_hash to_int")
obj.should_receive(:hash).and_return(obj)
obj.should_receive(:to_int).and_return(12)
@s.rb_hash(obj).should == 12
end
it "raises a TypeError if the object does not implement #to_int" do
obj = mock("rb_hash no to_int")
obj.should_receive(:hash).and_return(nil)
lambda { @s.rb_hash(obj) }.should raise_error(TypeError)
end
end
describe "rb_hash_new" do
it "returns a new hash" do
@s.rb_hash_new.should == {}
end
it "creates a hash with no default proc" do
@s.rb_hash_new {}.default_proc.should be_nil
end
end
describe "rb_hash_dup" do
it "returns a copy of the hash" do
hsh = {}
dup = @s.rb_hash_dup(hsh)
dup.should == hsh
dup.should_not equal(hsh)
end
end
describe "rb_hash_freeze" do
it "freezes the hash" do
@s.rb_hash_freeze({}).frozen?.should be_true
end
end
describe "rb_hash_aref" do
it "returns the value associated with the key" do
hsh = {chunky: 'bacon'}
@s.rb_hash_aref(hsh, :chunky).should == 'bacon'
end
it "returns the default value if it exists" do
hsh = Hash.new(0)
@s.rb_hash_aref(hsh, :chunky).should == 0
@s.rb_hash_aref_nil(hsh, :chunky).should be_false
end
it "returns nil if the key does not exist" do
hsh = { }
@s.rb_hash_aref(hsh, :chunky).should be_nil
@s.rb_hash_aref_nil(hsh, :chunky).should be_true
end
end
describe "rb_hash_aset" do
it "adds the key/value pair and returns the value" do
hsh = {}
@s.rb_hash_aset(hsh, :chunky, 'bacon').should == 'bacon'
hsh.should == {chunky: 'bacon'}
end
end
describe "rb_hash_clear" do
it "returns self that cleared keys and values" do
hsh = { :key => 'value' }
@s.rb_hash_clear(hsh).should equal(hsh)
hsh.should == {}
end
end
describe "rb_hash_delete" do
it "removes the key and returns the value" do
hsh = {chunky: 'bacon'}
@s.rb_hash_delete(hsh, :chunky).should == 'bacon'
hsh.should == {}
end
end
describe "rb_hash_delete_if" do
it "removes an entry if the block returns true" do
h = { a: 1, b: 2, c: 3 }
@s.rb_hash_delete_if(h) { |k, v| v == 2 }
h.should == { a: 1, c: 3 }
end
it "returns an Enumerator when no block is passed" do
@s.rb_hash_delete_if({a: 1}).should be_an_instance_of(Enumerator)
end
end
describe "rb_hash_fetch" do
before :each do
@hsh = {:a => 1, :b => 2}
end
it "returns the value associated with the key" do
@s.rb_hash_fetch(@hsh, :b).should == 2
end
it "raises a KeyError if the key is not found and default is set" do
@hsh.default = :d
lambda { @s.rb_hash_fetch(@hsh, :c) }.should raise_error(KeyError)
end
it "raises a KeyError if the key is not found and no default is set" do
lambda { @s.rb_hash_fetch(@hsh, :c) }.should raise_error(KeyError)
end
end
describe "rb_hash_foreach" do
it "iterates over the hash" do
hsh = {name: "Evan", sign: :libra}
out = @s.rb_hash_foreach(hsh)
out.equal?(hsh).should == false
out.should == hsh
end
it "stops via the callback" do
hsh = {name: "Evan", sign: :libra}
out = @s.rb_hash_foreach_stop(hsh)
out.size.should == 1
end
it "deletes via the callback" do
hsh = {name: "Evan", sign: :libra}
out = @s.rb_hash_foreach_delete(hsh)
out.should == {name: "Evan", sign: :libra}
hsh.should == {}
end
end
describe "rb_hash_size" do
it "returns the size of the hash" do
hsh = {fast: 'car', good: 'music'}
@s.rb_hash_size(hsh).should == 2
end
it "returns zero for an empty hash" do
@s.rb_hash_size({}).should == 0
end
end
describe "rb_hash_lookup" do
it "returns the value associated with the key" do
hsh = {chunky: 'bacon'}
@s.rb_hash_lookup(hsh, :chunky).should == 'bacon'
end
it "does not return the default value if it exists" do
hsh = Hash.new(0)
@s.rb_hash_lookup(hsh, :chunky).should be_nil
@s.rb_hash_lookup_nil(hsh, :chunky).should be_true
end
it "returns nil if the key does not exist" do
hsh = { }
@s.rb_hash_lookup(hsh, :chunky).should be_nil
@s.rb_hash_lookup_nil(hsh, :chunky).should be_true
end
describe "rb_hash_lookup2" do
it "returns the value associated with the key" do
hash = {chunky: 'bacon'}
@s.rb_hash_lookup2(hash, :chunky, nil).should == 'bacon'
end
it "returns the default value if the key does not exist" do
hash = {}
@s.rb_hash_lookup2(hash, :chunky, 10).should == 10
end
end
end
describe "rb_hash_set_ifnone" do
it "sets the default value of non existing keys" do
hash = {}
@s.rb_hash_set_ifnone(hash, 10)
hash[:chunky].should == 10
end
end
describe "rb_Hash" do
it "returns an empty hash when the argument is nil" do
@s.rb_Hash(nil).should == {}
end
it "returns an empty hash when the argument is []" do
@s.rb_Hash([]).should == {}
end
it "tries to convert the passed argument to a hash by calling #to_hash" do
h = BasicObject.new
def h.to_hash; {"bar" => "foo"}; end
@s.rb_Hash(h).should == {"bar" => "foo"}
end
it "raises a TypeError if the argument does not respond to #to_hash" do
lambda { @s.rb_Hash(42) }.should raise_error(TypeError)
end
it "raises a TypeError if #to_hash does not return a hash" do
h = BasicObject.new
def h.to_hash; 42; end
lambda { @s.rb_Hash(h) }.should raise_error(TypeError)
end
end
end
| 26.46748 | 78 | 0.619567 |
4a5e1937006051e081188f42fa5c2a0f8318ac31 | 1,454 | cask 'slack' do
version '2.9.0'
sha256 '043b1a795a5f6465b97b3fdc69d6e77dd78f6c5c80cbec5423c75e868537dd6b'
# downloads.slack-edge.com was verified as official when first introduced to the cask
url "https://downloads.slack-edge.com/mac_releases/Slack-#{version}-macOS.zip"
name 'Slack'
homepage 'https://slack.com/'
auto_updates true
app 'Slack.app'
uninstall quit: 'com.tinyspeck.slackmacgap'
zap trash: [
'~/Library/Application Scripts/com.tinyspeck.slackmacgap',
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.tinyspeck.slackmacgap.sfl*',
'~/Library/Application Support/Slack',
'~/Library/Caches/com.tinyspeck.slackmacgap',
'~/Library/Caches/com.tinyspeck.slackmacgap.ShipIt',
'~/Library/Containers/com.tinyspeck.slackmacgap',
'~/Library/Containers/com.tinyspeck.slackmacgap.SlackCallsService',
'~/Library/Cookies/com.tinyspeck.slackmacgap.binarycookies',
'~/Library/Group Containers/*.com.tinyspeck.slackmacgap',
'~/Library/Group Containers/*.slack',
'~/Library/Preferences/com.tinyspeck.slackmacgap.helper.plist',
'~/Library/Preferences/com.tinyspeck.slackmacgap.plist',
'~/Library/Saved Application State/com.tinyspeck.slackmacgap.savedState',
]
end
| 45.4375 | 157 | 0.676066 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.