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
|
---|---|---|---|---|---|
e91f97cb998a336d23825ed5de7377d047523f48
| 977 |
require 'rubygems'
begin
gem 'uispecrunner'
require 'uispecrunner'
require 'uispecrunner/options'
rescue LoadError => error
puts "Unable to load UISpecRunner: #{error}"
end
namespace :uispec do
desc "Run all specs"
task :all do
options = UISpecRunner::Options.from_file('uispec.opts') rescue {}
uispec_runner = UISpecRunner.new(options)
uispec_runner.run_all!
end
desc "Run all unit specs (those that implement UISpecUnit)"
task :units do
options = UISpecRunner::Options.from_file('uispec.opts') rescue {}
uispec_runner = UISpecRunner.new(options)
uispec_runner.run_protocol!('UISpecUnit')
end
desc "Run all integration specs (those that implement UISpecIntegration)"
task :integration do
options = UISpecRunner::Options.from_file('uispec.opts') rescue {}
uispec_runner = UISpecRunner.new(options)
uispec_runner.run_protocol!('UISpecIntegration')
end
end
desc "Run all specs"
task :default => 'uispec:all'
| 27.138889 | 75 | 0.731832 |
f8fc1b6c0b2047b55b5b77a88017c93ff96f377b
| 961 |
# frozen_string_literal: true
module Orbacle
module AstUtils
def self.const_to_string(const_ast)
get_nesting(const_ast).flatten.join("::")
end
def self.const_prename_and_name_to_string(prename_ast, name_ast)
(prename(prename_ast) + [name_ast.to_s]).compact.join("::")
end
def self.get_nesting(ast_const)
[prename(ast_const.children[0]), ast_const.children[1].to_s]
end
def self.prename(ast_const)
if ast_const.nil?
[]
else
prename(ast_const.children[0]) + [ast_const.children[1].to_s]
end
end
def build_position_range_from_ast(ast)
build_position_range_from_parser_range(ast.loc.expression)
end
def build_position_range_from_parser_range(parser_range)
PositionRange.new(
Position.new(parser_range.begin.line - 1, parser_range.begin.column),
Position.new(parser_range.end.line - 1, parser_range.end.column - 1))
end
end
end
| 26.694444 | 77 | 0.69615 |
b931b20c007e8b27188ef3e0e68e5bfa90ccbcf7
| 5,010 |
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for parentheses around the arguments in method
# definitions. Both instance and class/singleton methods are checked.
#
# @example EnforcedStyle: require_parentheses (default)
# # The `require_parentheses` style requires method definitions
# # to always use parentheses
#
# # bad
# def bar num1, num2
# num1 + num2
# end
#
# def foo descriptive_var_name,
# another_descriptive_var_name,
# last_descriptive_var_name
# do_something
# end
#
# # good
# def bar(num1, num2)
# num1 + num2
# end
#
# def foo(descriptive_var_name,
# another_descriptive_var_name,
# last_descriptive_var_name)
# do_something
# end
#
# @example EnforcedStyle: require_no_parentheses
# # The `require_no_parentheses` style requires method definitions
# # to never use parentheses
#
# # bad
# def bar(num1, num2)
# num1 + num2
# end
#
# def foo(descriptive_var_name,
# another_descriptive_var_name,
# last_descriptive_var_name)
# do_something
# end
#
# # good
# def bar num1, num2
# num1 + num2
# end
#
# def foo descriptive_var_name,
# another_descriptive_var_name,
# last_descriptive_var_name
# do_something
# end
#
# @example EnforcedStyle: require_no_parentheses_except_multiline
# # The `require_no_parentheses_except_multiline` style prefers no
# # parentheses when method definition arguments fit on single line,
# # but prefers parentheses when arguments span multiple lines.
#
# # bad
# def bar(num1, num2)
# num1 + num2
# end
#
# def foo descriptive_var_name,
# another_descriptive_var_name,
# last_descriptive_var_name
# do_something
# end
#
# # good
# def bar num1, num2
# num1 + num2
# end
#
# def foo(descriptive_var_name,
# another_descriptive_var_name,
# last_descriptive_var_name)
# do_something
# end
class MethodDefParentheses < Cop
include ConfigurableEnforcedStyle
include RangeHelp
MSG_PRESENT = 'Use def without parentheses.'
MSG_MISSING = 'Use def with parentheses when there are ' \
'parameters.'
def on_def(node)
args = node.arguments
if require_parentheses?(args)
if arguments_without_parentheses?(node)
missing_parentheses(node)
else
correct_style_detected
end
elsif parentheses?(args)
unwanted_parentheses(args)
else
correct_style_detected
end
end
alias on_defs on_def
def autocorrect(node)
lambda do |corrector|
if node.args_type?
# offense is registered on args node when parentheses are unwanted
correct_arguments(node, corrector)
else
correct_definition(node, corrector)
end
end
end
private
def correct_arguments(arg_node, corrector)
corrector.replace(arg_node.loc.begin, ' ')
corrector.remove(arg_node.loc.end)
end
def correct_definition(def_node, corrector)
arguments_range = def_node.arguments.source_range
args_with_space = range_with_surrounding_space(range: arguments_range,
side: :left)
leading_space = range_between(args_with_space.begin_pos,
arguments_range.begin_pos)
corrector.replace(leading_space, '(')
corrector.insert_after(arguments_range, ')')
end
def require_parentheses?(args)
style == :require_parentheses ||
(style == :require_no_parentheses_except_multiline &&
args.multiline?)
end
def arguments_without_parentheses?(node)
node.arguments? && !parentheses?(node.arguments)
end
def missing_parentheses(node)
location = node.arguments.source_range
add_offense(node, location: location, message: MSG_MISSING) do
unexpected_style_detected(:require_no_parentheses)
end
end
def unwanted_parentheses(args)
add_offense(args, message: MSG_PRESENT) do
unexpected_style_detected(:require_parentheses)
end
end
end
end
end
end
| 30 | 80 | 0.562475 |
f783071897d7c31ea420ca097ddca192c42f2627
| 1,283 |
module Pod
class ConfigureIOS
attr_reader :configurator
def self.perform(options)
new(options).perform
end
def initialize(options)
@configurator = options.fetch(:configurator)
end
def perform
keep_demo = :yes
configurator.set_test_framework("xctest", "m", "ios")
puts "--- 首页:HP,事儿:RM,家:MF,发现:FN,我的:AM,非业务组件:ZJ ---".green
prefix = nil
loop do
prefix = configurator.ask("What is your class prefix")
if prefix.include?(' ')
puts 'Your class prefix cannot contain spaces.'.red
else
break
end
end
Pod::ProjectManipulator.new({
:configurator => @configurator,
:xcodeproj_path => "templates/ios/Example/PROJECT.xcodeproj",
:platform => :ios,
:remove_demo_project => (keep_demo == :no),
:prefix => prefix
}).run
# There has to be a single file in the Classes dir
# or a framework won't be created, which is now default
`touch Pod/Classes/ReplaceMe.m`
`touch Pod/Assets/NAME.xcassets/ReplaceMe.imageset`
`mv ./templates/ios/* ./`
# remove podspec for osx
`rm ./NAME-osx.podspec`
end
end
end
| 23.759259 | 69 | 0.571317 |
873806600032cc4b69a0358d91168a227b850242
| 3,483 |
#!/usr/bin/env ruby
require 'aws-sdk'
region = ARGV[0]
instance_id = ARGV[1]
tag_name = ARGV[2]
tag_val = ARGV[3]
device = ARGV[4]
Aws.config.update({
region: region,
credentials: Aws::InstanceProfileCredentials.new,
})
client = Aws::EC2::Client.new
resp = client.describe_instance_status({
instance_ids: [instance_id],
})
az_id = resp.instance_statuses[0].availability_zone
def create_volume(az_id, volume_id, snap_id, tag_name)
if volume_id then
vol = Aws::EC2::Volume.new(volume_id)
if vol.availability_zone == az_id then
return vol.id
else
snapshot = vol.create_snapshot({
description: "ephemeral-snapshot",
})
snapshot.wait_until_completed
client = Aws::EC2::Client.new
resp = client.create_volume({
availability_zone: az_id,
snapshot_id: snapshot.id,
volume_type: 'gp2',
})
new_vol = Aws::EC2::Volume.new(resp.volume_id)
new_vol.create_tags({
tags: vol.tags,
})
new_vol.wait_until(max_attempts:10, delay:5) {|nvol| nvol.state == 'available' }
idx = 0
vol.tags.each_with_index do |tval, tidx|
if tval['key'] == tag_name then
idx = tidx
break
end
end
vol.create_tags({
tags: [
{
key: vol.tags[idx]["key"],
value: vol.tags[idx]["value"]+"-archived",
},
],
})
snapshot.delete
return new_vol.id
end
else
snap = Aws::EC2::Snapshot.new(snap_id)
client = Aws::EC2::Client.new
resp = client.create_volume({
availability_zone: az_id,
snapshot_id: snap.id,
volume_type: 'gp2',
})
new_vol = Aws::EC2::Volume.new(resp.volume_id)
new_vol.create_tags({
tags: snap.tags,
})
new_vol.wait_until(max_attempts:10, delay:5) {|nvol| nvol.state == 'available' }
return new_vol.id
end
end
def get_vol_for_az(az_id, tag_name, tag_val)
ec2 = Aws::EC2::Resource.new
volumes = ec2.volumes({
filters: [
{
name: 'status',
values: ['available'],
}
],
})
vol_id = nil
snap_id = nil
if volumes.count > 0 then
volumes.each do |vol|
vol.tags.each do |tags|
if ( tags['key'] == tag_name ) && ( tags['value'] == tag_val )
vol_id = vol.id
break
end
end
break if vol_id != nil
end
return create_volume(az_id, vol_id, false, tag_name)
else
snapshots = ec2.snapshots({
filters: [
name: 'tag-key',
values: tag_name,
name: 'tag-value',
values: [tag_val],
],
})
if snapshots.count > 0 then
snapshots.each do |snap|
snap.tags.each do |tags|
if ( tags['key'] == tag_name ) && ( tags['value'] == tag_val )
snap_id = snap.id
break
end
end
break if snap_id != nil
end
end
return create_volume(az_id, false, snap_id, tag_name)
end
end
def attach_volume(inst_id, vol_id, dev='/dev/xvdh')
vol = Aws::EC2::Volume.new(vol_id)
vol.attach_to_instance({
instance_id: inst_id,
device: dev,
})
vol.wait_until(max_attempts:20, delay:5) {|nvol| nvol.state == 'in-use' }
while !system("file -s #{dev} | grep data > /dev/null")
sleep 2
end
end
volume_id = get_vol_for_az(az_id, tag_name, tag_val)
attach_volume(instance_id, volume_id, device)
| 18.625668 | 86 | 0.578811 |
38b6d099f9939be399532a06be26b731d07ad914
| 21,787 |
# frozen_string_literal: true
# rubocop:disable Metrics/BlockLength
WasteCarriersEngine::Engine.routes.draw do
resources :start_forms,
only: %i[new create],
path: "start",
path_names: { new: "" },
constraints: ->(_request) { WasteCarriersEngine::FeatureToggle.active?(:new_registration) }
get "transient-registration/:token/destroy",
to: "transient_registrations#destroy",
as: "delete_transient_registration"
scope "/:token" do
# New registration flow
resources :renew_registration_forms,
only: %i[new create],
path: "renew-registration",
path_names: { new: "" } do
get "back",
to: "renew_registration_forms#go_back",
as: "back",
on: :collection
end
resources :your_tier_forms,
only: %i[new create],
path: "your-tier",
path_names: { new: "" } do
get "back",
to: "your_tier_forms#go_back",
as: "back",
on: :collection
end
resources :check_your_tier_forms,
only: %i[new create],
path: "check-your-tier",
path_names: { new: "" } do
get "back",
to: "check_your_tier_forms#go_back",
as: "back",
on: :collection
end
resources :registration_received_pending_payment_forms,
only: :new,
path: "registration-received-pending-payment",
path_names: { new: "" }
resources :registration_received_pending_worldpay_payment_forms,
only: :new,
path: "registration-received-pending-worldpay-payment",
path_names: { new: "" }
resources :registration_completed_forms,
only: :new,
path: "registration-completed",
path_names: { new: "" }
resources :registration_received_pending_conviction_forms,
only: :new,
path: "registration-received",
path_names: { new: "" }
# End of new registration flow
# Order copy cards flow
resources :copy_cards_forms,
only: %i[new create],
path: "order-copy-cards",
path_names: { new: "" }
resources :copy_cards_payment_forms,
only: %i[new create],
path: "order-copy-cards-payment",
path_names: { new: "" } do
get "back",
to: "copy_cards_payment_forms#go_back",
as: "back",
on: :collection
end
resources :copy_cards_bank_transfer_forms,
only: %i[new create],
path: "order-copy-cards-bank-transfer",
path_names: { new: "" } do
get "back",
to: "copy_cards_bank_transfer_forms#go_back",
as: "back",
on: :collection
end
resources :copy_cards_order_completed_forms,
only: %i[new create],
path: "order-copy-cards-complete",
path_names: { new: "" }
# End of order copy cards flow
# Ceased or revoked flow
resources :cease_or_revoke_forms,
only: %i[new create],
path: "cease-or-revoke",
path_names: { new: "" }
resources :ceased_or_revoked_confirm_forms,
only: %i[new create],
path: "ceased-or-revoked-confirm",
path_names: { new: "" } do
get "back",
to: "ceased_or_revoked_confirm_forms#go_back",
as: "back",
on: :collection
end
# End of ceased or revoked flow
# Edit flow
resources :edit_forms,
only: %i[new create],
path: "edit",
path_names: { new: "" } do
get "cbd-type",
to: "edit_forms#edit_cbd_type",
as: "cbd_type",
on: :collection
get "company-name",
to: "edit_forms#edit_company_name",
as: "company_name",
on: :collection
get "main-people",
to: "edit_forms#edit_main_people",
as: "main_people",
on: :collection
get "company-address",
to: "edit_forms#edit_company_address",
as: "company_address",
on: :collection
get "contact-name",
to: "edit_forms#edit_contact_name",
as: "contact_name",
on: :collection
get "contact-phone",
to: "edit_forms#edit_contact_phone",
as: "contact_phone",
on: :collection
get "contact-email",
to: "edit_forms#edit_contact_email",
as: "contact_email",
on: :collection
get "contact-address",
to: "edit_forms#edit_contact_address",
as: "contact_address",
on: :collection
get "contact-address-reuse",
to: "edit_forms#edit_contact_address_reuse",
as: "contact_address_reuse",
on: :collection
get "cancel",
to: "edit_forms#cancel",
as: "cancel",
on: :collection
end
resources :edit_payment_summary_forms,
only: %i[new create],
path: "edit-payment",
path_names: { new: "" } do
get "back",
to: "edit_payment_summary_forms#go_back",
as: "back",
on: :collection
end
resources :edit_bank_transfer_forms,
only: %i[new create],
path: "edit-bank-transfer",
path_names: { new: "" } do
get "back",
to: "edit_bank_transfer_forms#go_back",
as: "back",
on: :collection
end
resources :edit_complete_forms,
only: %i[new create],
path: "edit-complete",
path_names: { new: "" }
resources :confirm_edit_cancelled_forms,
only: %i[new create],
path: "confirm-edit-cancelled",
path_names: { new: "" } do
get "back",
to: "confirm_edit_cancelled_forms#go_back",
as: "back",
on: :collection
end
resources :edit_cancelled_forms,
only: %i[new create],
path: "edit-cancelled",
path_names: { new: "" }
# End of edit flow
resources :renewal_start_forms,
only: %i[new create],
path: "renew",
path_names: { new: "" }
resources :location_forms,
only: %i[new create],
path: "location",
path_names: { new: "" } do
get "back",
to: "location_forms#go_back",
as: "back",
on: :collection
end
resources :register_in_northern_ireland_forms,
only: %i[new create],
path: "register-in-northern-ireland",
path_names: { new: "" } do
get "back",
to: "register_in_northern_ireland_forms#go_back",
as: "back",
on: :collection
end
resources :register_in_scotland_forms,
only: %i[new create],
path: "register-in-scotland",
path_names: { new: "" } do
get "back",
to: "register_in_scotland_forms#go_back",
as: "back",
on: :collection
end
resources :register_in_wales_forms,
only: %i[new create],
path: "register-in-wales",
path_names: { new: "" } do
get "back",
to: "register_in_wales_forms#go_back",
as: "back",
on: :collection
end
resources :business_type_forms,
only: %i[new create],
path: "business-type",
path_names: { new: "" } do
get "back",
to: "business_type_forms#go_back",
as: "back",
on: :collection
end
resources :other_businesses_forms,
only: %i[new create],
path: "other-businesses",
path_names: { new: "" } do
get "back",
to: "other_businesses_forms#go_back",
as: "back",
on: :collection
end
resources :service_provided_forms,
only: %i[new create],
path: "service-provided",
path_names: { new: "" } do
get "back",
to: "service_provided_forms#go_back",
as: "back",
on: :collection
end
resources :construction_demolition_forms,
only: %i[new create],
path: "construction-demolition",
path_names: { new: "" } do
get "back",
to: "construction_demolition_forms#go_back",
as: "back",
on: :collection
end
resources :waste_types_forms,
only: %i[new create],
path: "waste-types",
path_names: { new: "" } do
get "back",
to: "waste_types_forms#go_back",
as: "back",
on: :collection
end
resources :cbd_type_forms,
only: %i[new create],
path: "cbd-type",
path_names: { new: "" } do
get "back",
to: "cbd_type_forms#go_back",
as: "back",
on: :collection
end
resources :renewal_information_forms,
only: %i[new create],
path: "renewal-information",
path_names: { new: "" } do
get "back",
to: "renewal_information_forms#go_back",
as: "back",
on: :collection
end
resources :registration_number_forms,
only: %i[new create],
path: "registration-number",
path_names: { new: "" } do
get "back",
to: "registration_number_forms#go_back",
as: "back",
on: :collection
end
resources :check_registered_company_name_forms,
only: %i[new create],
path: "check-registered-company-name",
path_names: { new: "" } do
get "back",
to: "check_registered_company_name_forms#go_back",
as: "back",
on: :collection
end
resources :incorrect_company_forms,
only: %i[new create],
path: "incorrect-company",
path_names: { new: "" } do
get "back",
to: "incorrect_company_forms#go_back",
as: "back",
on: :collection
end
resources :company_name_forms,
only: %i[new create],
path: "company-name",
path_names: { new: "" } do
get "back",
to: "company_name_forms#go_back",
as: "back",
on: :collection
end
resources :company_postcode_forms,
only: %i[new create],
path: "company-postcode",
path_names: { new: "" } do
get "back",
to: "company_postcode_forms#go_back",
as: "back",
on: :collection
get "skip_to_manual_address",
to: "company_postcode_forms#skip_to_manual_address",
as: "skip_to_manual_address",
on: :collection
end
resources :company_address_forms,
only: %i[new create],
path: "company-address",
path_names: { new: "" } do
get "back",
to: "company_address_forms#go_back",
as: "back",
on: :collection
get "skip_to_manual_address",
to: "company_address_forms#skip_to_manual_address",
as: "skip_to_manual_address",
on: :collection
end
resources :company_address_manual_forms,
only: %i[new create],
path: "company-address-manual",
path_names: { new: "" } do
get "back",
to: "company_address_manual_forms#go_back",
as: "back",
on: :collection
end
resources :main_people_forms,
only: %i[new create],
path: "main-people",
path_names: { new: "" } do
get "back",
to: "main_people_forms#go_back",
as: "back",
on: :collection
delete "delete_person/:id",
to: "main_people_forms#delete_person",
as: "delete_person",
on: :collection
end
resources :declare_convictions_forms,
only: %i[new create],
path: "declare-convictions",
path_names: { new: "" } do
get "back",
to: "declare_convictions_forms#go_back",
as: "back",
on: :collection
end
resources :conviction_details_forms,
only: %i[new create],
path: "conviction-details",
path_names: { new: "" } do
get "back",
to: "conviction_details_forms#go_back",
as: "back",
on: :collection
delete "delete_person/:id",
to: "conviction_details_forms#delete_person",
as: "delete_person",
on: :collection
end
resources :contact_name_forms,
only: %i[new create],
path: "contact-name",
path_names: { new: "" } do
get "back",
to: "contact_name_forms#go_back",
as: "back",
on: :collection
end
resources :contact_phone_forms,
only: %i[new create],
path: "contact-phone",
path_names: { new: "" } do
get "back",
to: "contact_phone_forms#go_back",
as: "back",
on: :collection
end
resources :contact_email_forms,
only: %i[new create],
path: "contact-email",
path_names: { new: "" } do
get "back",
to: "contact_email_forms#go_back",
as: "back",
on: :collection
end
resources :contact_postcode_forms,
only: %i[new create],
path: "contact-postcode",
path_names: { new: "" } do
get "back",
to: "contact_postcode_forms#go_back",
as: "back",
on: :collection
get "skip_to_manual_address",
to: "contact_postcode_forms#skip_to_manual_address",
as: "skip_to_manual_address",
on: :collection
end
resources :contact_address_forms,
only: %i[new create],
path: "contact-address",
path_names: { new: "" } do
get "back",
to: "contact_address_forms#go_back",
as: "back",
on: :collection
get "skip_to_manual_address",
to: "contact_address_forms#skip_to_manual_address",
as: "skip_to_manual_address",
on: :collection
end
resources :contact_address_manual_forms,
only: %i[new create],
path: "contact-address-manual",
path_names: { new: "" } do
get "back",
to: "contact_address_manual_forms#go_back",
as: "back",
on: :collection
end
resources :contact_address_reuse_forms,
only: %i[new create],
path: "contact-address-reuse",
path_names: { new: "" } do
get "back",
to: "contact_address_reuse_forms#go_back",
as: "back",
on: :collection
end
resources :check_your_answers_forms,
only: %i[new create],
path: "check-your-answers",
path_names: { new: "" } do
get "back",
to: "check_your_answers_forms#go_back",
as: "back",
on: :collection
end
resources :declaration_forms,
only: %i[new create],
path: "declaration",
path_names: { new: "" } do
get "back",
to: "declaration_forms#go_back",
as: "back",
on: :collection
end
resources :cards_forms,
only: %i[new create],
path: "cards",
path_names: { new: "" } do
get "back",
to: "cards_forms#go_back",
as: "back",
on: :collection
end
resources :payment_summary_forms,
only: %i[new create],
path: "payment-summary",
path_names: { new: "" } do
get "back",
to: "payment_summary_forms#go_back",
as: "back",
on: :collection
end
resources :worldpay_forms,
only: %i[new create],
path: "worldpay",
path_names: { new: "" } do
get "success",
to: "worldpay_forms#success",
as: "success",
on: :collection
get "failure",
to: "worldpay_forms#failure",
as: "failure",
on: :collection
get "cancel",
to: "worldpay_forms#cancel",
as: "cancel",
on: :collection
get "error",
to: "worldpay_forms#error",
as: "error",
on: :collection
get "pending",
to: "worldpay_forms#pending",
as: "pending",
on: :collection
end
resources :confirm_bank_transfer_forms,
only: %i[new create],
path: "confirm-bank-transfer",
path_names: { new: "" } do
get "back",
to: "confirm_bank_transfer_forms#go_back",
as: "back",
on: :collection
end
resources :renewal_complete_forms,
only: %i[new create],
path: "renewal-complete",
path_names: { new: "" }
resources :renewal_received_pending_conviction_forms,
only: %i[new create],
path: "renewal-received",
path_names: { new: "" }
resources :renewal_received_pending_payment_forms,
only: %i[new create],
path: "renewal-received-pending-payment",
path_names: { new: "" }
resources :renewal_received_pending_worldpay_payment_forms,
only: %i[new create],
path: "renewal-received-pending-worldpay-payment",
path_names: { new: "" }
resources :cannot_renew_type_change_forms,
only: %i[new create],
path: "cannot-renew-type-change",
path_names: { new: "" } do
get "back",
to: "cannot_renew_type_change_forms#go_back",
as: "back",
on: :collection
end
end
mount DefraRubyEmail::Engine => "/email"
# See http://patrickperey.com/railscast-053-handling-exceptions/
get "(errors)/:status",
to: "errors#show",
constraints: { status: /\d{3}/ },
as: "error"
# Renew via magic link token
get "/renew/:token",
to: "renews#new",
as: "renew"
# Static pages with HighVoltage
resources :pages, only: [:show], controller: "pages"
end
# rubocop:enable Metrics/BlockLength
| 33.161339 | 103 | 0.448478 |
26125b25b0e5dba750ee32a6307dc3133dd3fd7f
| 2,822 |
Pod::Spec.new do |s|
s.name = "Nimble"
s.version = "8.0.5"
s.summary = "A Matcher Framework for Swift and Objective-C"
s.description = <<-DESC
Use Nimble to express the expected outcomes of Swift or Objective-C expressions. Inspired by Cedar.
DESC
s.homepage = "https://github.com/Quick/Nimble"
s.license = { :type => "Apache 2.0", :file => "LICENSE" }
s.author = "Quick Contributors"
s.ios.deployment_target = "8.0"
s.osx.deployment_target = "10.10"
s.tvos.deployment_target = "9.0"
s.source = { :git => "https://github.com/Quick/Nimble.git",
:tag => "v#{s.version}" }
s.source_files = [
"Sources/**/*.{swift,h,m,c}",
"Carthage/Checkouts/CwlPreconditionTesting/Dependencies/CwlCatchException/Sources/**/*.{swift,h,m,c}",
"Carthage/Checkouts/CwlPreconditionTesting/Sources/**/*.{swift,h,m,c}",
]
s.osx.exclude_files = [
"Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/CwlCatchBadInstructionPosix.swift",
]
s.ios.exclude_files = [
"Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/CwlCatchBadInstructionPosix.swift",
]
s.tvos.exclude_files = [
"Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/Mach/CwlPreconditionTesting.h",
"Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/CwlCatchBadInstruction.swift",
"Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/CwlBadInstructionException.swift",
"Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/CwlDarwinDefinitions.swift",
"Carthage/Checkouts/CwlPreconditionTesting/Dependencies/CwlCatchException/Sources/CwlCatchException/CwlCatchException.swift",
"Carthage/Checkouts/CwlPreconditionTesting/Dependencies/CwlCatchException/Sources/CwlCatchExceptionSupport/CwlCatchException.m",
"Carthage/Checkouts/CwlPreconditionTesting/Dependencies/CwlCatchException/Sources/CwlCatchExceptionSupport/include/CwlCatchException.h",
]
s.exclude_files = "Sources/Nimble/Adapters/NonObjectiveC/*.swift"
s.weak_framework = "XCTest"
s.requires_arc = true
s.compiler_flags = '-DPRODUCT_NAME=Nimble/Nimble'
s.pod_target_xcconfig = {
'APPLICATION_EXTENSION_API_ONLY' => 'YES',
'DEFINES_MODULE' => 'YES',
'ENABLE_BITCODE' => 'NO',
'OTHER_LDFLAGS' => '$(inherited) -weak-lswiftXCTest -Xlinker -no_application_extension',
'OTHER_SWIFT_FLAGS' => '$(inherited) -suppress-warnings',
'FRAMEWORK_SEARCH_PATHS' => '$(inherited) "$(PLATFORM_DIR)/Developer/Library/Frameworks"',
}
s.cocoapods_version = '>= 1.4.0'
if s.respond_to?(:swift_versions) then
s.swift_versions = ['4.2', '5.0']
else
s.swift_version = '4.2'
end
end
| 47.830508 | 140 | 0.7236 |
7a09a8395f501d23eb946cb09210624c6b956063
| 227 |
module Procodile
def self.root
File.expand_path('../../', __FILE__)
end
def self.bin_path
File.join(root, 'bin', 'procodile')
end
end
class String
def color(color)
"\e[#{color}m#{self}\e[0m"
end
end
| 12.611111 | 40 | 0.621145 |
11194e2025aa85bd0f33663810145b7542ecdd3b
| 182 |
# encoding: UTF-8
module GoodData
module Mixin
module RootKeySetter
def root_key(a_key)
define_method :root_key, proc { a_key.to_s }
end
end
end
end
| 15.166667 | 52 | 0.648352 |
018d7cb23c6f7de05e9cccedac2331616397bb1a
| 608 |
class SessionsController < ApplicationController
def index
if uid = session[:user_id]
render json: UserSerializer(User.find(uid)).to_serialized_json
else
render json: {errors: ["Session not found! Please login again."]}, status: 403
end
end
def create
user = User.find_by(email: params[:user][:email])
if user.authenticate(params[:user][:password])
session[:user_id] = user.id
render json: UserSerializer.new(user).to_serialized_json
else
render json: {errors: ["Could not find account with that email/password!"]}, status: 403
end
end
end
| 28.952381 | 94 | 0.685855 |
18a1845cd53427f6233eea0c306682abb9184aa1
| 1,077 |
#Our CLI Controller
require_relative 'weather.rb'
class MyWeather::CLI
def call
welcome
menu
end
def welcome
puts "*******Welcome to my Weather CLI app where you can get current weather conditions*******"
end
def menu
input = ""
while input != "exit"
puts "What is your 'zip code'? Enter a 5-digit 'zip code' or type 'exit' to leave the program."
input = gets.strip.downcase #inputs string to lower case
if input.to_i > 0 && input.length == 5 #input must be integer and length of 5. This prevents "00000" from working.
MyWeather::Weather
puts "The current weather condition for your location (at zip code: #{input}) is: (sunny). The current temperature is: (70) degrees F."
elsif input =="exit" #skips error message to quit program
ending
else
puts "Please enter five numbers for 'zip code' or type ‘exit’ to quit." #error message
end
end
end
def ending
puts "Thank you for using my CLI weather app! Have a nice day!"
end
end
| 30.771429 | 145 | 0.63324 |
b94e0d0529b7d3ca7071450209b94dfd0dba8354
| 1,079 |
# Changes the kind field on a policy to "coverall"
require File.join(Rails.root, "lib/mongoid_migration_task")
class UpdateTotalResponsibleAmount < MongoidMigrationTask
def migrate
policy = Policy.where(eg_id: ENV['eg_id']).first
if policy.present? && policy.aptc_credits.empty?
total_responsible_amount= ENV['total_responsible_amount']
premium_amount_total = ENV['premium_amount_total']
applied_aptc = ENV['applied_aptc']
policy.update_attributes(tot_res_amt: total_responsible_amount) if is_number?(total_responsible_amount)
policy.update_attributes(pre_amt_tot: premium_amount_total) if is_number?(premium_amount_total)
policy.update_attributes(applied_aptc: applied_aptc) if is_number?(applied_aptc)
policy.save!
elsif policy.blank?
puts "Policy not found for eg_id #{ENV['eg_id']}"
elsif policy.aptc_credits.size > 0
puts "This policy has aptc credit documents. Please inspect and modify those instead."
end
end
def is_number?(string)
true if Float(string) rescue false
end
end
| 37.206897 | 109 | 0.748842 |
bf0df471e6b9e91e9343851caef00b7cc9809c76
| 8,901 |
require 'active_record'
require_relative '../../helpers/data_services_metrics_helper'
require_dependency 'carto/helpers/auth_token_generator'
require_dependency 'carto/carto_json_serializer'
require_dependency 'carto/helpers/organization_commons'
module Carto
class Organization < ActiveRecord::Base
include CartodbCentralSynchronizable
include DataServicesMetricsHelper
include Carto::OrganizationQuotas
include AuthTokenGenerator
include OrganizationSoftLimits
include Carto::OrganizationCommons
belongs_to :owner, class_name: 'Carto::User', inverse_of: :owned_organization
has_many :users, -> { order(:username) }, inverse_of: :organization
has_many :groups, -> { order(:display_name) }, inverse_of: :organization
has_many :assets, class_name: 'Carto::Asset', dependent: :destroy, inverse_of: :organization
has_many :notifications, -> { order('created_at DESC') }, dependent: :destroy
has_many :connector_configurations, inverse_of: :organization, dependent: :destroy
has_many :oauth_app_organizations, inverse_of: :oauth_app, dependent: :destroy
validates :quota_in_bytes, :seats, presence: true
validates(
:name,
presence: true,
uniqueness: true,
format: { with: /\A[a-z0-9\-]+\z/, message: 'must only contain lowercase letters, numbers & hyphens' }
)
validates(
:geocoding_quota,
:here_isolines_quota,
:obs_snapshot_quota,
:obs_general_quota,
numericality: { only_integer: true }
)
validates :default_quota_in_bytes, numericality: { only_integer: true, allow_nil: true, greater_than: 0 }
validates :auth_saml_configuration, carto_json_symbolizer: true
validate :validate_password_expiration_in_d
validate :organization_name_collision
validate :validate_seats
validate :authentication_methods_available
before_validation :ensure_auth_saml_configuration
before_validation :set_default_quotas
before_save :register_modified_quotas
after_save :save_metadata
before_destroy :destroy_related_resources
after_destroy :destroy_metadata
serialize :auth_saml_configuration, CartoJsonSymbolizerSerializer
## AR compatibility
alias values attributes
## ./ AR compatibility
def self.find_by_database_name(database_name)
Carto::Organization
.joins('INNER JOIN users ON organizations.owner_id = users.id')
.where('users.database_name = ?', database_name).first
end
def default_password_expiration_in_d
Cartodb.get_config(:passwords, 'expiration_in_d')
end
def valid_builder_seats?(users = [])
remaining_seats(excluded_users: users).positive?
end
def remaining_seats(excluded_users: [])
seats - assigned_seats(excluded_users: excluded_users)
end
def assigned_seats(excluded_users: [])
builder_users.count { |u| !excluded_users.map(&:id).include?(u.id) }
end
# Make code more uniform with user.database_schema
def database_schema
name
end
def last_billing_cycle
owner ? owner.last_billing_cycle : Date.today
end
def twitter_imports_count(options = {})
require_organization_owner_presence!
date_to = (options[:to] ? options[:to].to_date : Date.today)
date_from = (options[:from] ? options[:from].to_date : owner.last_billing_cycle)
Carto::SearchTweet.twitter_imports_count(users.joins(:search_tweets), date_from, date_to)
end
alias get_twitter_imports_count twitter_imports_count
def owner?(user)
owner_id == user.id
end
def tags(type, exclude_shared = true)
users.map { |u| u.tags(exclude_shared, type) }.flatten
end
def public_vis_by_type(type, page_num, items_per_page, tags, order = 'updated_at', version = nil)
CartoDB::Visualization::Collection.new.fetch(
user_id: users.pluck(:id),
type: type,
privacy: CartoDB::Visualization::Member::PRIVACY_PUBLIC,
page: page_num,
per_page: items_per_page,
tags: tags,
order: order,
o: { updated_at: :desc },
version: version
)
end
def signup_page_enabled
whitelisted_email_domains.present? && auth_enabled?
end
def auth_enabled?
auth_username_password_enabled || auth_google_enabled || auth_github_enabled || auth_saml_enabled?
end
def total_seats
seats + viewer_seats
end
def remaining_viewer_seats(excluded_users: [])
viewer_seats - assigned_viewer_seats(excluded_users: excluded_users)
end
def assigned_viewer_seats(excluded_users: [])
viewer_users.count { |u| !excluded_users.map(&:id).include?(u.id) }
end
def notify_if_disk_quota_limit_reached
::Resque.enqueue(::Resque::OrganizationJobs::Mail::DiskQuotaLimitReached, id) if disk_quota_limit_reached?
end
def notify_if_seat_limit_reached
::Resque.enqueue(::Resque::OrganizationJobs::Mail::SeatLimitReached, id) if will_reach_seat_limit?
end
def database_name
owner&.database_name
end
def revoke_cdb_conf_access
users.map { |user| user.db_service.revoke_cdb_conf_access }
end
def create_group(display_name)
Carto::Group.create_group_with_extension(self, display_name)
end
def name_to_display
display_name || name
end
def max_import_file_size
owner ? owner.max_import_file_size : ::User::DEFAULT_MAX_IMPORT_FILE_SIZE
end
def max_import_table_row_count
owner ? owner.max_import_table_row_count : ::User::DEFAULT_MAX_IMPORT_TABLE_ROW_COUNT
end
def max_concurrent_import_count
owner ? owner.max_concurrent_import_count : ::User::DEFAULT_MAX_CONCURRENT_IMPORT_COUNT
end
def max_layers
owner ? owner.max_layers : ::User::DEFAULT_MAX_LAYERS
end
def auth_saml_enabled?
auth_saml_configuration.present?
end
def builder_users
users.reject(&:viewer)
end
def viewer_users
users.select(&:viewer)
end
def admin?(user)
user.belongs_to_organization?(self) && user.organization_admin?
end
def non_owner_users
owner ? users.where.not(id: owner.id) : users
end
def inheritable_feature_flags
inherit_owner_ffs ? owner.self_feature_flags : Carto::FeatureFlag.none
end
delegate :dbdirect_effective_ips, to: :owner
delegate :dbdirect_effective_ips=, to: :owner
def map_views_count
users.map(&:map_views_count).sum
end
def require_organization_owner_presence!
raise Carto::Organization::OrganizationWithoutOwner, self unless owner
end
# INFO: replacement for destroy because destroying owner triggers
# organization destroy
def destroy_cascade(delete_in_central: false)
groups.each(&:destroy_group_with_extension)
destroy_non_owner_users
owner ? owner.sequel_user.destroy_cascade : destroy
end
def validate_seats_for_signup(user, errors)
errors.add(:organization, 'not enough seats') if user.builder? && !valid_builder_seats?([user])
return unless user.viewer? && remaining_viewer_seats(excluded_users: [user]) <= 0
errors.add(:organization, 'not enough viewer seats')
end
def validate_for_signup(errors, user)
validate_seats_for_signup(user, errors)
return if valid_disk_quota?(user.quota_in_bytes.to_i)
errors.add(:quota_in_bytes, 'not enough disk quota')
end
private
def destroy_non_owner_users
non_owner_users.each do |user|
user.ensure_nonviewer
user.shared_entities.map(&:entity).uniq.each(&:delete)
user.sequel_user.destroy_cascade
end
end
def destroy_assets
assets.map { |asset| Carto::Asset.find(asset.id) }.map(&:destroy).all?
end
def will_reach_seat_limit?
remaining_seats <= 1
end
def authentication_methods_available
if whitelisted_email_domains.present? && !auth_enabled?
errors.add(:whitelisted_email_domains, 'enable at least one auth. system or clear whitelisted email domains')
end
end
def organization_name_collision
errors.add(:name, 'cannot exist as user') if Carto::User.exists?(username: name)
end
def validate_seats
errors.add(:seats, 'cannot be less than the number of builders') if seats && remaining_seats.negative?
return unless viewer_seats && remaining_viewer_seats.negative?
errors.add(:viewer_seats, 'cannot be less than the number of viewers')
end
def validate_password_expiration_in_d
valid = password_expiration_in_d.blank? || password_expiration_in_d.positive? && password_expiration_in_d < 366
errors.add(:password_expiration_in_d, 'must be greater than 0 and lower than 366') unless valid
end
def ensure_auth_saml_configuration
self.auth_saml_configuration ||= {}
end
end
end
| 31.013937 | 117 | 0.718234 |
e9309e43347589204ef117a23017d811f0d70a50
| 2,181 |
module OidGenerator
extend ActiveSupport::Concern
if Settings.oid_prefix.blank? ||
Settings.oid_prefix['Section'].blank? ||
Settings.oid_prefix['Question'].blank? ||
Settings.oid_prefix['ResponseSet'].blank?
raise 'OID prefixes misconfigured, cannot continue. Configure these prefixes in config/settings.yml'
end
included do
end
# Callback that assigns the oid. This should never be called directly.
def assign_oid
if version > 1
# If not first version, set the oid to whatever the parent's oid was
parent_oid = self.class.where(version_independent_id: version_independent_id, version: 1)
.limit(1)
.pluck(:oid)
.first
# If parent oid is blank, we get an infinite loop
if parent_oid != oid && !parent_oid.blank?
update_attribute(:oid, parent_oid)
end
else
new_oid = "#{self.class.oid_prefix}.#{id}"
if self.class.where(oid: new_oid).count > 0
new_oid = self.class.next_avail_oid(id)
end
update_attribute(:oid, new_oid)
end
end
# If oid exists, check if oid is unique for all records that are NOT a different version of the same record
def validate_oid
return if oid.blank?
conflicts = if version == 1
self.class.where.not(id: id).where(oid: oid).count
else
self.class.where.not(version_independent_id: version_independent_id).where(oid: oid).count
end
if conflicts > 0
errors.add(:oid, "Cannot save #{self.class.name} record, OID already in use")
end
end
module ClassMethods
def oid_prefix
Settings.oid_prefix[name]
end
def next_avail_oid(start_oid = 1)
oid_list = where("oid LIKE ? AND split_part(oid, '.', 9)::int > ?", "%#{oid_prefix}%", start_oid)
.order("split_part(oid, '.', 9)::int ASC")
.pluck(:oid)
next_oid = start_oid + 1
oid_list.each do |oid|
current = oid.split('.').last.to_i
break if next_oid != current
next_oid += 1
end
"#{oid_prefix}.#{next_oid}"
end
end
end
| 32.552239 | 109 | 0.615773 |
f832fff120c2cccc28a24e899b286157e6a1940b
| 69 |
require "cama_stripe_donation/engine"
module CamaStripeDonation
end
| 13.8 | 37 | 0.869565 |
ac93929ec1fa721c99f7407294bbf1059c2726d5
| 1,150 |
ENV["RAILS_ENV"] = "test"
$:.unshift(File.dirname(__FILE__) + '/../lib')
require 'rubygems'
require 'active_record'
require 'active_record/version'
require 'active_record/fixtures'
require 'action_controller'
require 'action_controller/test_process'
require 'action_controller/test_case'
require 'action_view'
require 'action_view/test_case'
require 'test/unit'
require 'shoulda'
#require 'active_support/core_ext/module'
require File.dirname(__FILE__) + '/../init.rb'
config = YAML::load(IO.read(File.dirname(__FILE__) + '/db/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
ActiveRecord::Base.establish_connection(config[ENV['DB'] || 'sqlite3mem'])
ActiveRecord::Migration.verbose = false
load(File.dirname(__FILE__) + "/db/schema.rb")
Fixtures.create_fixtures(File.dirname(__FILE__) + '/fixtures', ActiveRecord::Base.connection.tables)
ActionController::Routing::Routes.reload rescue nil
class Time
@@new_now = Time.now
def self.now_with_stub
@@new_now || Time.now_without_stub
end
class << self
alias_method :now_without_stub, :now
alias_method :now, :now_with_stub
end
end
| 30.263158 | 100 | 0.76087 |
38d97113537e2834061ab0335d283b68cb8ad621
| 405 |
require 'sinatra/base'
class Helpers
def self.valid_email?(email)
email =~ /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
end
def self.valid_username?(username)
username =~ /\A[a-z0-9_]{4,16}\z/
end
def self.current_user(session)
User.find_by(id: session[:user_id])
end
def self.is_logged_in?(session)
!!session[:user_id]
end
end
| 21.315789 | 63 | 0.553086 |
289c40249a82731e7d1b57b01d923122fe2b237a
| 61 |
# frozen_string_literal: true
require_relative 'system_info'
| 20.333333 | 30 | 0.852459 |
1cba639e8df34834f12315fc5a54038b82962814
| 1,472 |
require 'open3'
describe 'Integration' do
apps = {
golang: 'go run golang/echo.go',
ruby: 'ruby ruby/echo.rb'
}
combinations = <<~TEXT
golang
golang golang
golang golang golang
ruby
ruby ruby
ruby ruby ruby
golang ruby
ruby golang
ruby golang ruby
golang ruby golang
golang ruby golang ruby golang
TEXT
describe 'the echo app chain with' do
combinations.lines.each do |line|
example line.gsub(' ', '/') do
calls = line.scan(/\w+/).map.with_index { |name, i| ["#{i + 1}.#{name}", apps[name.to_sym]] }.to_h
errs_top = []
errs_bottom = []
calls.keys.each.with_index do |name, index|
errs_top << "#{name} init"
errs_top << "#{name} dig" unless index.zero?
errs_top << "#{name} calling"
unless index.zero?
errs_bottom << "#{name} done"
errs_bottom << "#{name} trigger"
end
errs_bottom << "#{name} handle #{calls.to_a[index + 1].first}" unless index == calls.length - 1
end
errs = (errs_top + errs_bottom.reverse).join("\n") << "\n"
cmd = calls.each_with_object [] do |(name, exe), c|
c << exe
c << '--main' if c.one?
c << name
end.join(' ')
# TODO: assert JSON output on STDOUT
_o, e, s = Open3.capture3(cmd)
expect(e).to eq errs
expect(s).to be_success
end
end
end
end
| 25.37931 | 106 | 0.54212 |
3901518615a93f85ec92af5af4d0e63315bbfe3c
| 751 |
# frozen_string_literal: true
class BankAccount < ApplicationRecord
belongs_to :user
has_many :transactions
monetize :balance, as: :balance_cents
enum status: %i[inactive active].freeze
validates :account_number, presence: true, uniqueness: true
validates :balance, presence: true
validates :user_id, presence: true
validates :status, presence: true
before_validation :load_defaults
def load_defaults
if new_record?
self.account_number = '%05d' % rand(5**10)
self.status = 'active'
end
end
def change_status
if active? && balance.zero?
update_attribute :status, 'inactive'
elsif inactive? && balance >= 0
update_attribute :status, 'active'
else
false
end
end
end
| 20.861111 | 61 | 0.699068 |
e83716ea5e840be5e84c82cd17c393e35a20d323
| 6,849 |
#
# irb/extend-command.rb - irb extend command
# $Release Version: 0.9.5$
# $Revision: 11708 $
# $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $
# by Keiju ISHITSUKA([email protected])
#
# --
#
#
#
module IRB
#
# IRB extended command
#
module ExtendCommandBundle
EXCB = ExtendCommandBundle
NO_OVERRIDE = 0
OVERRIDE_PRIVATE_ONLY = 0x01
OVERRIDE_ALL = 0x02
def irb_exit(ret = 0)
irb_context.exit(ret)
end
def irb_context
IRB.CurrentContext
end
@ALIASES = [
[:context, :irb_context, NO_OVERRIDE],
[:conf, :irb_context, NO_OVERRIDE],
[:irb_quit, :irb_exit, OVERRIDE_PRIVATE_ONLY],
[:exit, :irb_exit, OVERRIDE_PRIVATE_ONLY],
[:quit, :irb_exit, OVERRIDE_PRIVATE_ONLY],
]
@EXTEND_COMMANDS = [
[:irb_current_working_workspace, :CurrentWorkingWorkspace, "irb/cmd/chws",
[:irb_print_working_workspace, OVERRIDE_ALL],
[:irb_cwws, OVERRIDE_ALL],
[:irb_pwws, OVERRIDE_ALL],
# [:irb_cww, OVERRIDE_ALL],
# [:irb_pww, OVERRIDE_ALL],
[:cwws, NO_OVERRIDE],
[:pwws, NO_OVERRIDE],
# [:cww, NO_OVERRIDE],
# [:pww, NO_OVERRIDE],
[:irb_current_working_binding, OVERRIDE_ALL],
[:irb_print_working_binding, OVERRIDE_ALL],
[:irb_cwb, OVERRIDE_ALL],
[:irb_pwb, OVERRIDE_ALL],
# [:cwb, NO_OVERRIDE],
# [:pwb, NO_OVERRIDE]
],
[:irb_change_workspace, :ChangeWorkspace, "irb/cmd/chws",
[:irb_chws, OVERRIDE_ALL],
# [:irb_chw, OVERRIDE_ALL],
[:irb_cws, OVERRIDE_ALL],
# [:irb_cw, OVERRIDE_ALL],
[:chws, NO_OVERRIDE],
# [:chw, NO_OVERRIDE],
[:cws, NO_OVERRIDE],
# [:cw, NO_OVERRIDE],
[:irb_change_binding, OVERRIDE_ALL],
[:irb_cb, OVERRIDE_ALL],
[:cb, NO_OVERRIDE]],
[:irb_workspaces, :Workspaces, "irb/cmd/pushws",
[:workspaces, NO_OVERRIDE],
[:irb_bindings, OVERRIDE_ALL],
[:bindings, NO_OVERRIDE]],
[:irb_push_workspace, :PushWorkspace, "irb/cmd/pushws",
[:irb_pushws, OVERRIDE_ALL],
# [:irb_pushw, OVERRIDE_ALL],
[:pushws, NO_OVERRIDE],
# [:pushw, NO_OVERRIDE],
[:irb_push_binding, OVERRIDE_ALL],
[:irb_pushb, OVERRIDE_ALL],
[:pushb, NO_OVERRIDE]],
[:irb_pop_workspace, :PopWorkspace, "irb/cmd/pushws",
[:irb_popws, OVERRIDE_ALL],
# [:irb_popw, OVERRIDE_ALL],
[:popws, NO_OVERRIDE],
# [:popw, NO_OVERRIDE],
[:irb_pop_binding, OVERRIDE_ALL],
[:irb_popb, OVERRIDE_ALL],
[:popb, NO_OVERRIDE]],
[:irb_load, :Load, "irb/cmd/load"],
[:irb_require, :Require, "irb/cmd/load"],
[:irb_source, :Source, "irb/cmd/load",
[:source, NO_OVERRIDE]],
[:irb, :IrbCommand, "irb/cmd/subirb"],
[:irb_jobs, :Jobs, "irb/cmd/subirb",
[:jobs, NO_OVERRIDE]],
[:irb_fg, :Foreground, "irb/cmd/subirb",
[:fg, NO_OVERRIDE]],
[:irb_kill, :Kill, "irb/cmd/subirb",
[:kill, OVERRIDE_PRIVATE_ONLY]],
[:irb_help, :Help, "irb/cmd/help",
[:help, NO_OVERRIDE]],
]
def self.install_extend_commands
for args in @EXTEND_COMMANDS
def_extend_command(*args)
end
end
# aliases = [commans_alias, flag], ...
def self.def_extend_command(cmd_name, cmd_class, load_file = nil, *aliases)
case cmd_class
when Symbol
cmd_class = cmd_class.id2name
when String
when Class
cmd_class = cmd_class.name
end
if load_file
eval %[
def #{cmd_name}(*opts, &b)
require "#{load_file}"
eval %[
def #{cmd_name}(*opts, &b)
ExtendCommand::#{cmd_class}.execute(irb_context, *opts, &b)
end
]
send :#{cmd_name}, *opts, &b
end
]
else
eval %[
def #{cmd_name}(*opts, &b)
ExtendCommand::#{cmd_class}.execute(irb_context, *opts, &b)
end
]
end
for ali, flag in aliases
@ALIASES.push [ali, cmd_name, flag]
end
end
# override = {NO_OVERRIDE, OVERRIDE_PRIVATE_ONLY, OVERRIDE_ALL}
def install_alias_method(to, from, override = NO_OVERRIDE)
to = to.id2name unless to.kind_of?(String)
from = from.id2name unless from.kind_of?(String)
if override == OVERRIDE_ALL or
(override == OVERRIDE_PRIVATE_ONLY) && !respond_to?(to) or
(override == NO_OVERRIDE) && !respond_to?(to, true)
target = self
(class<<self;self;end).instance_eval{
if target.respond_to?(to, true) &&
!target.respond_to?(EXCB.irb_original_method_name(to), true)
alias_method(EXCB.irb_original_method_name(to), to)
end
alias_method to, from
}
else
print "irb: warn: can't alias #{to} from #{from}.\n"
end
end
def self.irb_original_method_name(method_name)
"irb_" + method_name + "_org"
end
def self.extend_object(obj)
unless (class<<obj;ancestors;end).include?(EXCB)
super
for ali, com, flg in @ALIASES
obj.install_alias_method(ali, com, flg)
end
end
end
install_extend_commands
end
# extension support for Context
module ContextExtender
CE = ContextExtender
@EXTEND_COMMANDS = [
[:eval_history=, "irb/ext/history.rb"],
[:use_tracer=, "irb/ext/tracer.rb"],
[:math_mode=, "irb/ext/math-mode.rb"],
[:use_loader=, "irb/ext/use-loader.rb"],
[:save_history=, "irb/ext/save-history.rb"],
]
def self.install_extend_commands
for args in @EXTEND_COMMANDS
def_extend_command(*args)
end
end
def self.def_extend_command(cmd_name, load_file, *aliases)
Context.module_eval %[
def #{cmd_name}(*opts, &b)
Context.module_eval {remove_method(:#{cmd_name})}
require "#{load_file}"
send :#{cmd_name}, *opts, &b
end
for ali in aliases
alias_method ali, cmd_name
end
]
end
CE.install_extend_commands
end
module MethodExtender
def def_pre_proc(base_method, extend_method)
base_method = base_method.to_s
extend_method = extend_method.to_s
alias_name = new_alias_name(base_method)
module_eval %[
alias_method alias_name, base_method
def #{base_method}(*opts)
send :#{extend_method}, *opts
send :#{alias_name}, *opts
end
]
end
def def_post_proc(base_method, extend_method)
base_method = base_method.to_s
extend_method = extend_method.to_s
alias_name = new_alias_name(base_method)
module_eval %[
alias_method alias_name, base_method
def #{base_method}(*opts)
send :#{alias_name}, *opts
send :#{extend_method}, *opts
end
]
end
# return #{prefix}#{name}#{postfix}<num>
def new_alias_name(name, prefix = "__alias_of__", postfix = "__")
base_name = "#{prefix}#{name}#{postfix}"
all_methods = instance_methods(true) + private_instance_methods(true)
same_methods = all_methods.grep(/^#{Regexp.quote(base_name)}[0-9]*$/)
return base_name if same_methods.empty?
no = same_methods.size
while !same_methods.include?(alias_name = base_name + no)
no += 1
end
alias_name
end
end
end
| 25.845283 | 80 | 0.649292 |
1d72958d07d78680f3273a5ad6f41f077b8c8784
| 925 |
require 'rdf'
require 'ebnf'
module RDF
##
# **`RDF::Turtle`** is an Turtle extension for RDF.rb.
#
# @example Requiring the `RDF::Turtle` module
# require 'rdf/turtle'
#
# @example Parsing RDF statements from an Turtle file
# RDF::Turtle::Reader.open("etc/foaf.ttl") do |reader|
# reader.each_statement do |statement|
# puts statement.inspect
# end
# end
#
# @see https://rubydoc.info/github/ruby-rdf/rdf/master/frames
# @see https://dvcs.w3.org/hg/rdf/raw-file/default/rdf-turtle/index.html
#
# @author [Gregg Kellogg](https://greggkellogg.net/)
module Turtle
require 'rdf/turtle/format'
autoload :Reader, 'rdf/turtle/reader'
autoload :FreebaseReader, 'rdf/turtle/freebase_reader'
autoload :Terminals, 'rdf/turtle/terminals'
autoload :VERSION, 'rdf/turtle/version'
autoload :Writer, 'rdf/turtle/writer'
end
end
| 29.83871 | 74 | 0.650811 |
e2d4575ce9c5614b8baffb5362d4a305d01258f4
| 6,928 |
require "#{Rails.root}/lib/import_helpers.rb"
require "#{Rails.root}/lib/spreadsheet_helpers.rb"
require "#{Rails.root}/lib/address_helpers.rb"
require "#{Rails.root}/lib/abatement_helpers.rb"
require 'rubyXL'
include ImportHelpers
include SpreadsheetHelpers
include AddressHelpers
include AbatementHelpers
namespace :foreclosures do
desc "Downloading CDC case numbers from s3.amazon.com"
task :load_writfile, [:file_name, :bucket_name] => :environment do |t, args|
args.with_defaults(:bucket_name => "neworleansdata", :file_name => "WRITS - WORKING COPY - Oct.3.2012.xlsx")#"Writs Filed - Code Enforcement.xlsx")
p args
#connect to amazon
ImportHelpers.connect_to_aws
s3obj = AWS::S3::S3Object.find args.file_name, args.bucket_name
downloaded_file_path = ImportHelpers.download_from_aws(s3obj)
workbook = RubyXL::Parser.parse(downloaded_file_path)
sheet = workbook.worksheets[1].extract_data
cdc_col = 4
addr_col = 2
client = Savon.client ENV['SHERIFF_WSDL']
sheet.each do |row|
if row[cdc_col]
cdc_number = row[cdc_col]
address_long = row[addr_col]
puts "writs file row => " << row.to_s
begin
if cdc_number && cdc_number != "CDC ID"# && cdc_number != "NO CASE #"
response = client.request 'm:GetForeclosure' do
http.headers['SOAPAction'] = ENV['SHERIFF_ACTION']
soap.namespaces['xmlns:m'] = ENV['SHERIFF_NS']
soap.body = {'m:cdcCaseNumber' => cdc_number, 'm:key' => ENV['SHERIFF_PASSWORD'] }
end
puts "Requesting cdcCaseNumber => #{cdc_number}"
foreclosure = response.hash[:envelope][:body][:get_foreclosure_response][:get_foreclosure_result][:foreclosure]
if foreclosure
sale_dt = nil
unless foreclosure[:sale_date] == "Null"
sale_dt = DateTime.strptime(foreclosure[:sale_date], '%m/%d/%Y %H:%M:%S %p')
end
addr = {address_long: nil, house_num: nil, street_type: nil, street_name: nil}
if foreclosure[:property_address]
addr[:address_long] = foreclosure[:property_address]
if addr[:address_long].end_with?(".")
addr[:address_long] = addr[:address_long].chop
end
addr[:house_num] = addr[:address_long].split(' ')[0]
addr[:street_type] = AddressHelpers.get_street_type addr[:address_long]
addr[:street_name] = AddressHelpers.get_street_name addr[:address_long]
end
Foreclosure.create(status: foreclosure[:sale_status], notes: nil, sale_date: sale_dt, title: foreclosure[:case_title][0..254], cdc_case_number: foreclosure[:cdc_case_number], defendant: foreclosure[:defendant][0..254], plaintiff: foreclosure[:plaintiff][0..254], address_long: foreclosure[:property_address], street_name: addr[:street_name], street_type: addr[:street_type], house_num: addr[:house_num])
end
end
rescue Exception=>e
puts e.inspect
Foreclosure.create(cdc_case_number: cdc_number, address_long: address_long)
end
end
end
puts "foreclosures:load_sheriff"
end
desc "Downloading CDC case numbers from s3.amazon.com"
task :load_cdcNumbers, [:cdc_numbers] => :environment do |t, args|
p args
client = Savon.client ENV['SHERIFF_WSDL']
args[:cdc_numbers].split('|').each do |cdc_number|# sheet.each do |row|
response = client.request 'm:GetForeclosure' do
http.headers['SOAPAction'] = ENV['SHERIFF_ACTION']
soap.namespaces['xmlns:m'] = ENV['SHERIFF_NS']
soap.body = {'m:cdcCaseNumber' => cdc_number, 'm:key' => ENV['SHERIFF_PASSWORD'] }
end
puts "Requesting cdcCaseNumber => #{cdc_number}"
foreclosure = response.hash[:envelope][:body][:get_foreclosure_response][:get_foreclosure_result][:foreclosure]
if foreclosure
puts foreclosure
sale_dt = nil
unless foreclosure[:sale_date] == "Null"
sale_dt = DateTime.strptime(foreclosure[:sale_date], '%m/%d/%Y %H:%M:%S %p')
end
addr = {address_long: nil, house_num: nil, street_type: nil, street_name: nil}
if foreclosure[:property_address]
addr[:address_long] = foreclosure[:property_address]
if addr[:address_long].end_with?(".")
addr[:address_long] = addr[:address_long].chop
end
addr[:house_num] = addr[:address_long].split(' ')[0]
addr[:street_type] = AddressHelpers.get_street_type addr[:address_long]
addr[:street_name] = AddressHelpers.get_street_name addr[:address_long]
end
Foreclosure.create(status: foreclosure[:sale_status], notes: nil, sale_date: sale_dt, title: foreclosure[:case_title][0..254], cdc_case_number: foreclosure[:cdc_case_number], defendant: foreclosure[:defendant][0..254], plaintiff: foreclosure[:plaintiff][0..254], address_long: foreclosure[:property_address], street_name: addr[:street_name], street_type: addr[:street_type], house_num: addr[:house_num])
end
end
puts "foreclosures:load_cdcNumbers"
end
desc "Correlate foreclosure data with addresses"
task :match => :environment do |t, args|
# go through each foreclosure
success = 0
failure = 0
case_matches = 0
Foreclosure.where('address_id is null').each do |row|
# compare each address in demo list to our address table
#address = Address.where("address_long LIKE ?", "%#{row.address_long}%")
address = AddressHelpers.find_address(row.address_long)
unless (address.empty?)
fore = Foreclosure.find(row.id)
fore.update_attributes(:address_id => address.first.id)
success += 1
fore.address.cases.each do |c|
unless Foreclosure.where("case_number = :case_number", {:case_number => c.case_number}).nil?
fore.update_attributes(:case_number => c.case_number)
case_matches += 1;
end
end
else
puts "#{row.address_long} address not found in address table"
failure += 1
end
end
puts "There were #{success} successful address matches and #{failure} failed address matches and #{case_matches} cases matched"
end
desc "Correlate foreclosure data with cases"
task :match_case => :environment do |t, args|
# go through each demolition
foreclosures = Foreclosure.where("address_id is not null and case_number is null")
AbatementHelpers.match_case(foreclosures)
end
desc "Delete all foreclosures from database"
task :drop => :environment do |t, args|
Foreclosure.destroy_all
end
end
| 42.243902 | 417 | 0.641455 |
ab1ef6bce1a499d8ea0ed08258a73994b110a969
| 825 |
require 'test_helper'
class MicropostsControllerTest < ActionDispatch::IntegrationTest
def setup
@micropost = microposts(:orange)
end
test "should redirect create when not logged in" do
assert_no_difference 'Micropost.count' do
post microposts_path, params: { micropost: { content: "Lorem ipsum" } }
end
assert_redirected_to login_url
end
test "should redirect destroy when not logged in" do
assert_no_difference 'Micropost.count' do
delete micropost_path(@micropost)
end
assert_redirected_to login_url
end
test "should redirect destroy for wrong micropost" do
log_in_as(users(:test_user))
micropost = microposts(:ants)
assert_no_difference 'Micropost.count' do
delete micropost_path(micropost)
end
assert_redirected_to root_url
end
end
| 26.612903 | 77 | 0.738182 |
e2c5adb87990ee2721dea8bb4276f1627825aa98
| 1,004 |
#
# Copyright:: Copyright (c) 2018 Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
class Telemetry
class Session
# The telemetry session data is normally kept in .chef, which we don't have.
def session_file
ChefApply::Config.telemetry_session_file.freeze
end
end
def deliver(data = {})
if ChefApply::Telemeter.instance.enabled?
payload = event.prepare(data)
client.await.fire(payload)
end
end
end
| 30.424242 | 80 | 0.731076 |
5df3c144e5ed919af609bc237089253c4b48bdd5
| 838 |
module WillPaginate
module ViewHelpers
# This class does the heavy lifting of actually building the pagination
# links. It is used by +will_paginate+ helper internally.
class PageNumberRendererBase
# * +collection+ is a WillPaginate::Collection instance or any other object
# that conforms to that API
# * +options+ are forwarded from +will_paginate+ view helper
def prepare(options, current_page, total_pages)
@current_page = current_page
@total_pages = total_pages
@options = options
end
def numbers
[]
end
private
def current_page
@collection.current_page
end
def total_pages
@total_pages ||= @collection.total_pages
end
end
end
end
| 25.393939 | 83 | 0.610979 |
ff199a3bf959e5d99e8ae60884c873a3814e53ea
| 542 |
class LastfmFplib < Formula
homepage "http://blog.last.fm/2007/08/29/audio-fingerprinting-for-clean-metadata"
head "svn://svn.audioscrobbler.net/recommendation/MusicID/lastfm_fplib"
depends_on "cmake" => :build
depends_on "taglib"
depends_on "mad"
depends_on "libsamplerate"
depends_on "fftw"
def install
inreplace "fplib/src/FloatingAverage.h",
"for ( int i = 0; i < size; ++i )",
"for ( int i = 0; i < m_values.size(); ++i )"
system "cmake", ".", *std_cmake_args
system "make", "install"
end
end
| 28.526316 | 83 | 0.666052 |
6159de23dffda84e9a8a7cbf39549e6f42e9bc8b
| 9,064 |
class ActionDispatch::Routing::Mapper
def draw(routes_name)
path = File.expand_path("routes/#{routes_name}.rb", File.dirname(__FILE__))
instance_eval(File.read(path))
end
end
Rails.application.routes.draw do
get '/products/music-metadata-enrichment', to: redirect('/music'), as: 'music_metadata_enrichment_product'
#get '/music_metadata_enrichment' => 'product/music_metadata_enrichment#index'
get '/music' => 'product/music_metadata_enrichment#index'
get '/music_metadata_enrichment', to: redirect('/music')
get '/music-metadata-enrichment', to: redirect('/music')
namespace :music, module: 'music_metadata_enrichment' do
resources :groups, only: [:index, :new, :create, :show] do
resources :memberships, only: [:create], controller: 'group_memberships'
resources :artists, only: [:new], controller: 'group_artist_connections' do
collection do
get :import
post :import, as: :post_import
get :name_confirmation
get :select_artist
get :creation
end
end
member do
get 'artists' => 'artists#index'
get 'releases' => 'releases#index'
get 'releases/export' => 'releases#export'
end
resources :releases, only: [:new]
resources :videos, only: [:index, :new]
end
resources :group_memberships, only: [:destroy]
resources :artists, only: [:index, :new, :create, :show] do
collection do
get :name_confirmation
get 'by_name/:name', to: 'artists#by_name'
get :by_name, as: :by_name
get :autocomplete
end
resources :releases, only: [:new] do
collection do
get :autocomplete
end
end
resources :tracks, only: [] do
collection do
get :autocomplete
end
end
resources :videos, only: [:index, :new]
end
resources :releases, only: [:index, :new, :create, :show] do
collection do
get :artist_confirmation
get :select_artist
get :name
get :name_confirmation
get :announce
post :create_announcement
get 'by_name/:artist_name/:name', to: 'releases#by_name'
get :by_name, as: :by_name
end
end
resources :tracks, only: [:index, :new, :create, :show] do
collection do
get :artist_confirmation
get :select_artist
get :name
get :name_confirmation
get 'by_name/:artist_name/:name', to: 'tracks#by_name'
get :by_name, as: :by_name
end
resources :videos, only: [:new]
end
resources :videos, only: [:index, :new, :create, :show] do
collection do
get :artist_confirmation
get :select_artist
get :track_name
get :track_confirmation
get :create_track
get :metadata
get 'by_name/:artist_name/:name', to: 'videos#by_name'
get :by_name, as: :by_name
end
end
end
get 'music/groups/:group_id/years_in_review' => 'music_metadata_enrichment/group_year_in_reviews#index', as: :group_music_years_in_review
get 'music/groups/:group_id/years_in_review/:year' => 'music_metadata_enrichment/group_year_in_reviews#show', as: :group_music_year_in_review
get 'music/groups/:group_id/years_in_review/:year/top_releases' => 'music_metadata_enrichment/group_year_in_review_releases#index', as: :group_music_year_in_review_top_releases
get 'music/groups/:group_id/years_in_review/:year/top_releases/export' => 'music_metadata_enrichment/group_year_in_review_releases#export', as: :group_export_music_year_in_review_top_releases
get 'music/groups/:group_id/years_in_review/:year/top_tracks' => 'music_metadata_enrichment/group_year_in_review_tracks#index', as: :group_music_year_in_review_top_tracks
get 'music/groups/:group_id/years_in_review/:year/top_tracks/export' => 'music_metadata_enrichment/group_year_in_review_tracks#export', as: :group_export_music_year_in_review_top_tracks
get 'users/:user_id/library/music' => 'library/music#index', as: :user_music_library
get 'users/:user_id/library/music/years_in_review' => 'library/music/years_in_review#index', as: :user_music_years_in_review
post 'users/:user_id/library/music/years_in_review' => 'library/music/years_in_review#create', as: :create_user_music_year_in_review
get 'users/:user_id/library/music/years_in_review/:year' => 'library/music/years_in_review#show', as: :user_music_year_in_review
put 'users/current/library/music/years_in_review/:id' => 'library/music/years_in_review#publish', as: :publish_music_year_in_review
delete 'users/current/library/music/years_in_review/:id' => 'library/music/years_in_review#destroy', as: :destroy_music_year_in_review
get 'users/:user_id/library/music/years_in_review/:year/top_releases' => 'library/music/year_in_review_releases#index', as: :user_music_year_in_review_top_releases
get 'users/:user_id/library/music/years_in_review/:year/top_releases/new' => 'library/music/year_in_review_releases#new', as: :new_user_music_year_in_review_top_release
post 'users/:user_id/library/music/years_in_review/:year/top_releases' => 'library/music/year_in_review_releases#create', as: :create_user_music_year_in_review_top_release
post 'users/:user_id/library/music/years_in_review/:year/flop_releases' => 'library/music/year_in_review_release_flops#create', as: :create_user_music_year_in_review_flop_release
get 'users/current/library/music/years_in_review/:year/top_releases/multiple_new' => 'library/music/year_in_review_releases#multiple_new', as: :multiple_new_user_music_year_in_review_top_releases
post 'users/:user_id/library/music/years_in_review/:year/top_releases/create_multiple' => 'library/music/year_in_review_releases#create_multiple', as: :create_multiple_user_music_year_in_review_top_releases
delete 'users/current/library/music/year_in_review_music_releases/:id' => 'library/music/year_in_review_releases#destroy', as: :destroy_music_year_in_review_top_release
put 'users/current/library/music/year_in_review_music_releases/move' => 'library/music/year_in_review_releases#move', as: :move_music_year_in_review_top_release
put 'users/current/library/music/years_in_review/:year/top_releases/update_all_positions' => 'library/music/year_in_review_releases#update_all_positions', as: :update_all_positions_music_year_in_review_top_release
get 'users/current/library/music/years_in_review/:year/top_releases/export' => 'library/music/year_in_review_releases#export', as: :export_music_year_in_review_top_releases
get 'users/:user_id/library/music/years_in_review/:year/top_tracks' => 'library/music/year_in_review_tracks#index', as: :user_music_year_in_review_top_tracks
get 'users/:user_id/library/music/years_in_review/:year/top_tracks/new' => 'library/music/year_in_review_tracks#new', as: :new_user_music_year_in_review_top_track
post 'users/:user_id/library/music/years_in_review/:year/top_tracks' => 'library/music/year_in_review_tracks#create', as: :create_user_music_year_in_review_top_track
post 'users/:user_id/library/music/years_in_review/:year/flop_tracks' => 'library/music/year_in_review_track_flops#create', as: :create_user_music_year_in_review_flop_track
get 'users/current/library/music/years_in_review/:year/top_tracks/multiple_new' => 'library/music/year_in_review_tracks#multiple_new', as: :multiple_new_user_music_year_in_review_top_tracks
post 'users/:user_id/library/music/years_in_review/:year/top_tracks/create_multiple' => 'library/music/year_in_review_tracks#create_multiple', as: :create_multiple_user_music_year_in_review_top_tracks
delete 'users/current/library/music/year_in_review_music_tracks/:id' => 'library/music/year_in_review_tracks#destroy', as: :destroy_music_year_in_review_top_track
put 'users/current/library/music/year_in_review_music_tracks/move' => 'library/music/year_in_review_tracks#move', as: :move_music_year_in_review_top_track
put 'users/current/library/music/years_in_review/:year/top_tracks/update_all_positions' => 'library/music/year_in_review_tracks#update_all_positions', as: :update_all_positions_music_year_in_review_top_track
get 'users/current/library/music/years_in_review/:year/top_tracks/export' => 'library/music/year_in_review_tracks#export', as: :export_music_year_in_review_top_tracks
get 'users/:user_id/library/music/releases' => 'music_metadata_enrichment/releases#index', as: :user_music_library_releases
get 'users/:user_id/library/music/videos' => 'music_metadata_enrichment/videos#index', as: :user_music_library_videos
get 'users/:user_id/library/music/artists' => 'music_metadata_enrichment/artists#index', as: :user_music_library_artists
get 'users/:user_id/library/music/artists/new' => 'music_metadata_enrichment/artists#new', as: :new_user_music_library_artist
delete 'users/current/library/music/artists/:id' => 'library/music/artists#destroy', as: :destroy_music_library_artist
draw :api
end
| 60.832215 | 215 | 0.755185 |
91c055db0c8d25ad9169954d6d52c2ae9632e473
| 330 |
class RegistrationsController < Devise::RegistrationsController
private
def sign_up_params
params.require(:teacher).permit(:name, :email, :password, :password_confirmation)
end
def account_update_params
params.require(:teacher).permit(:name, :email, :password, :password_confirmation, :current_password)
end
end
| 33 | 104 | 0.781818 |
33babaf6d6716bcd512be43898c1da7dd769588d
| 157 |
class DropVotesTable < ActiveRecord::Migration[6.0]
def up
drop_table :votes
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
| 15.7 | 51 | 0.738854 |
d5cd31196d5a3ac5e59489fb485311af02d6fecc
| 818 |
require 'cocoapods'
require 'cocoapods-core'
require 'cocoapods-prefer/command'
require 'cocoapods-prefer/config'
require 'cocoapods-prefer/hook'
module CocoapodsPrefer
Pod::HooksManager.register('cocoapods-prefer', :source_provider) do |context, user_options|
Pod::PreferConfig.instance.prefer_sources().each { |e, source|
context.add_source(source)
}
end
Pod::HooksManager.register('cocoapods-prefer', :pre_install) do |context, user_options|
Pod::PreferConfig.instance.prefer_source_options(user_options)
# targets = context.podfile.target_definition_list.reject { |e| e.name.include?("Pods") }
# targets.each{ |e| puts e.name }
end
Pod::HooksManager.register('cocoapods-prefer', :post_install) do |context, user_options|
Pod::PreferConfig.instance.report()
end
end
| 31.461538 | 94 | 0.745721 |
ed5f2cf2fd5e94bd423eed1966ea4ea73efbb178
| 36 |
module Bruv
VERSION = "0.2.2"
end
| 9 | 19 | 0.638889 |
e9e65f66ead87182bc47b075555c4c059ba43cfd
| 1,680 |
module Factories
def self.product(sku = 'ROR-TS')
{
"id"=> 12345,
"name"=> "Ruby on Rails T-Shirt",
"description"=> "Some description text for the product.",
"sku"=> sku,
"price"=> 31,
"created_at" => "2014-02-03T19:00:54.386Z",
"updated_at" => "2014-02-03T19:22:54.386Z",
"properties"=> {
"fabric"=> "cotton",
},
"options"=> [ "color", "size" ],
"taxons"=> [
['Categories', 'Clothes', 'T-Shirts'],
['Brands', 'Spree']
],
"images" => [
{
"url"=> "http=>//dummyimage.com/600x400/000/fff.jpg&text=Spree T-Shirt",
"position"=> 1,
"title"=> "Spree T-Shirt - Grey Small",
"type"=> "thumbnail",
"dimensions"=> {
"height"=> 220,
"width"=> 100
}
}
],
"variants"=> [
{
"name"=> "Ruby on Rails T-Shirt S",
"sku"=> "#{sku}-small",
"options"=> {
"size"=> "small",
"color"=> "white"
},
"images" => [
{
"url"=> "http=>//dummyimage.com/600x400/000/fff.jpg&text=Spree T-Shirt",
"position"=> 1,
"title"=> "Spree T-Shirt - Grey Small",
"type"=> "thumbnail",
"dimensions"=> {
"height"=> 220,
"width"=> 100
}
}
]
},
{
"name"=> "Ruby on Rails T-Shirt M",
"sku"=> "#{sku}-medium",
"options"=> {
"size"=> "medium",
"color"=> "black"
},
}
],
}
end
end
| 26.25 | 86 | 0.389286 |
b9677d885c032bc06123b5b6b367d6de13fd4d10
| 1,180 |
{
matrix_id: '1918',
name: 'photogrammetry2',
group: 'Luong',
description: 'Photogrammetry problem, B. Luong, FOGALE nanotech, France',
author: 'B. Luong',
editor: 'T. Davis',
date: '2008',
kind: 'computer graphics/vision problem',
problem_2D_or_3D: '1',
num_rows: '4472',
num_cols: '936',
nonzeros: '37056',
num_explicit_zeros: '0',
num_strongly_connected_components: '1',
num_dmperm_blocks: '1',
structural_full_rank: 'true',
structural_rank: '936',
pattern_symmetry: '0.000',
numeric_symmetry: '0.000',
rb_type: 'real',
structure: 'rectangular',
cholesky_candidate: 'no',
positive_definite: 'no',
notes: 'Photogrammetry problem from Bruno Luong, FOGALE nanotech, France.
This problem is nearly rank-deficient.
',
b_field: 'full 4472-by-1
',
norm: '2.833894e-04',
min_singular_value: '2.116259e-12',
condition_number: '1.339106e+08',
svd_rank: '936',
sprank_minus_rank: '0',
null_space_dimension: '0',
full_numerical_rank: 'yes',
image_files: 'photogrammetry2.png,photogrammetry2_svd.png,photogrammetry2_graph.gif,',
}
| 30.25641 | 90 | 0.649153 |
ab2e2983aaa84c86fc3a40d59caf2581c0140be9
| 2,011 |
# frozen_string_literal: true
RSpec.describe "La biblioteca si misma" do
def check_for_expendable_words(filename)
failing_line_message = []
useless_words = %w[
básicamente
claramente
sólo
solamente
obvio
obviamente
fácil
fácilmente
sencillamente
simplemente
]
pattern = /\b#{Regexp.union(useless_words)}\b/i
File.readlines(filename).each_with_index do |line, number|
next unless word_found = pattern.match(line)
failing_line_message << "#{filename}:#{number.succ} contiene '#{word_found}'. Esta palabra tiene un significado subjetivo y es mejor obviarla en textos técnicos."
end
failing_line_message unless failing_line_message.empty?
end
def check_for_specific_pronouns(filename)
failing_line_message = []
specific_pronouns = /\b(él|ella|ellos|ellas)\b/i
File.readlines(filename).each_with_index do |line, number|
next unless word_found = specific_pronouns.match(line)
failing_line_message << "#{filename}:#{number.succ} contiene '#{word_found}'. Use pronombres más genéricos en la documentación."
end
failing_line_message unless failing_line_message.empty?
end
it "mantiene la calidad de lenguaje de la documentación" do
included = /ronn/
error_messages = []
man_tracked_files.split("\x0").each do |filename|
next unless filename =~ included
error_messages << check_for_expendable_words(filename)
error_messages << check_for_specific_pronouns(filename)
end
expect(error_messages.compact).to be_well_formed
end
it "mantiene la calidad de lenguaje de oraciones usadas en el código fuente" do
error_messages = []
exempt = /vendor/
lib_tracked_files.split("\x0").each do |filename|
next if filename =~ exempt
error_messages << check_for_expendable_words(filename)
error_messages << check_for_specific_pronouns(filename)
end
expect(error_messages.compact).to be_well_formed
end
end
| 32.435484 | 168 | 0.717553 |
ac309aaea0496372e0494099a45f469f5c8aaa74
| 1,090 |
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
# coding: utf-8
Gem::Specification.new do |spec|
spec.name = "jekyll-theme-assets-updated"
spec.version = "1.1"
spec.authors = ["Pavel Tsurbeleu", "Kyle Kirkby"]
spec.email = ["[email protected]", "[email protected]"]
spec.summary = %q{Assets for a gem-based Jekyll theme}
spec.description = %q{A Jekyll plugin, that allows you to use private and public assets defined in a gem-based Jekyll theme.}
spec.homepage = "https://github.com/ptsurbeleu/jekyll-theme-assets/"
spec.license = "MIT"
spec.has_rdoc = false
spec.files = %W(Rakefile Gemfile README.md LICENSE) + Dir["lib/**/*"]
spec.require_paths = ["lib"]
spec.add_runtime_dependency "jekyll-assets", "~> 2.4.0"
spec.add_runtime_dependency "jekyll", ">= 3.0", "~> 3.1"
spec.add_development_dependency "bundler", "~> 1.14"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "minitest", "~> 5.0"
end
| 40.37037 | 129 | 0.661468 |
798583d8c217c68e4f75fdda57033c6d3dc15f1d
| 2,046 |
require 'rails_helper'
RSpec.describe Groups::Questions::Written::AnsweredController, vcr: true do
describe 'GET index' do
before(:each) do
get :index, params: { group_id: 'fpWTqVKh'}
end
it 'should have a response with http status ok (200)' do
expect(response).to have_http_status(:ok)
end
it 'assigns @answering_body, @answers and @answers_grouped_by_date' do
expect(assigns(:answering_body).type).to eq('https://id.parliament.uk/schema/AnsweringBody')
assigns(:answers).each do |answer|
expect(answer.type).to eq('https://id.parliament.uk/schema/Answer')
end
expect(assigns(:answers_grouped_by_date).keys.first).to be_a(Date)
expect(assigns(:answers_grouped_by_date).values.first.first.type).to eq('https://id.parliament.uk/schema/Answer')
end
context 'the answer does not have a date' do
it 'assigns assigns @answering_body, @answers and @answers_grouped_by_date' do
expect(assigns(:answering_body).type).to eq('https://id.parliament.uk/schema/AnsweringBody')
assigns(:answers).each do |answer|
expect(answer.type).to eq('https://id.parliament.uk/schema/Answer')
end
expect(assigns(:answers_grouped_by_date).keys.first).to eq(nil)
expect(assigns(:answers_grouped_by_date).values.first.first.type).to eq('https://id.parliament.uk/schema/Answer')
end
end
context 'there are no answers' do
it 'assigns @answering_body, @answers and @answers_grouped_by_date' do
expect(assigns(:answering_body).type).to eq('https://id.parliament.uk/schema/AnsweringBody')
expect(assigns(:answers).nodes).to eq []
expect(assigns(:answers_grouped_by_date).keys.first).to eq(nil)
end
end
context 'answering body is an empty array' do
it 'assigns assigns @answering_body' do
expect(assigns(:answering_body)).to eq nil
end
end
it 'renders the index template' do
expect(response).to render_template('index')
end
end
end
| 34.1 | 121 | 0.688172 |
e9ecba9dcf38433cfd7da2624505aba424a628ae
| 147 |
class UsersController < ApplicationController
get '/users/:slug' do
@user = User.find_by_slug(params[:slug])
erb :'/users/show'
end
end
| 14.7 | 45 | 0.70068 |
039634ab22b581a4f656f2b30728e811f2446b9d
| 163 |
class CreateDepartamentos < ActiveRecord::Migration
def change
create_table :departamentos do |t|
t.string :name
t.timestamps
end
end
end
| 16.3 | 51 | 0.693252 |
617551acbae95adba6143fef803a5302fca34294
| 182 |
class CreateAlbums < ActiveRecord::Migration
def change
create_table :albums do |t|
t.string :title
t.integer :cover_photo_id
t.timestamps
end
end
end
| 16.545455 | 44 | 0.67033 |
ed33a0df281942860c12bb3f935150005ec5db5c
| 215 |
class GoogleAnalyticsAddition < ActiveRecord::Migration
def self.up
add_column :franchises, :google_analytics_code, :string
end
def self.down
remove_column :franchises, :google_analytics_code
end
end
| 21.5 | 58 | 0.786047 |
1ca74b280b5bf76cb91a4b3cf0d827942ee482b3
| 11,744 |
#!/usr/bin/env ruby
require 'optparse'
require 'octokit'
require 'logger'
require 'json'
require 'date'
class CourseExtractor
def initialize(client, course_name, course_org, add_assignments, add_submissions, which_sub)
@client = client
@course_name = course_name
@course_org = course_org
@add_assignments = add_assignments
@add_submissions = add_submissions
@which_sub = which_sub
end
def Process_Course()
if !Does_Org_Exist()
STDERR.puts "WARNING: Course organization does not exist."
return
end
if !Check_Membership()
return
end
old_course_spec = Get_Course()
if old_course_spec.empty?
return
end
for project in old_course_spec["projects"]
lab_name = project["name"].gsub(/\W+/, '_')
if lab_name.length > 15
lab_name = "p#{project["id"]}"
end
repo_name = "assignment-#{lab_name}"
if @add_assignments
proj_repo_fullname = Init_Repo(repo_name)
Update_Proj_Spec(proj_repo_fullname, Modify_Spec(proj_repo_fullname, project) )
end
proj_id = project["id"]
if @add_submissions
Add_Student_Submissions(proj_id, lab_name)
end
puts " "
end
end
def Add_Student_Submissions(proj_id, lab_name)
course_sub_repo = "#{@course_name}_submissions"
if !Does_Repo_Exist("submit-cs-conversion/#{course_sub_repo}")
STDERR.puts "WARNING: submit-cs-conversion/#{course_sub_repo} does not exist."
return
end
begin
all_proj = JSON.parse(Base64.decode64( @client.contents( "submit-cs-conversion/#{course_sub_repo}",
:path => "#{@course_name}.json"
).content ))
rescue Exception => e
STDERR.puts "WARNING: Unable to FIND #{@course_name}.json at submit-cs-conversion/#{course_sub_repo}/#{@course_name}.json"
STDERR.puts e.message, e.backtrace.inspect
return
end
proj = all_proj["#{proj_id}"]
if proj == nil
STDERR.puts "WARNING: Unable to find submissions for #{lab_name}"
return
end
puts "Adding Student Submissions for #{lab_name}"
proj.each do |sub_type, submissions|
if sub_type == "consenting_users_with_solo_submissions"
submissions.each do |user, subs|
Add_One_Submission(user, subs, course_sub_repo, lab_name)
end
elsif sub_type == "consenting_users_with_group_submissions"
submissions.each do |user, subs|
Add_One_Submission(user, subs, course_sub_repo, lab_name)
end
end
end
end
def Add_One_Submission(user, subs, course_sub_repo, lab_name)
umail = user.split("@umail.ucsb.edu")
username = umail[0]
repo_name = "#{lab_name}-#{username}"
if Github_User(username)
sub_repo_fullname = Init_Repo(repo_name)
Add_Collaborator(sub_repo_fullname, username)
if @which_sub == "FIRST"
sub_to_send = subs[0]
puts "FIRST - SUB"
elsif @which_sub == "NEXT"
next_index = Get_Sub_Index(sub_repo_fullname, subs)
sub_to_send = subs[ next_index ]
puts "NEXT - SUB: #{next_index}"
else #LAST SUB
puts "LAST - SUB"
sub_to_send = subs[-1]
end
Create_Or_Update_File(sub_repo_fullname, ".anacapa/submission.json", JSON.pretty_generate(sub_to_send))
Create_Or_Update_File(sub_repo_fullname, "ReadMe.md", "https://submit.cs.ucsb.edu/submission/#{sub_to_send["id"]}")
for file in sub_to_send["files"]
if file.include? "sha"
sha_file_path = "#{@course_name}/SHA/#{file["sha"]}"
elsif file.include? "sha1"
sha_file_path = "#{@course_name}/SHA/#{file["sha1"]}"
elsif file.include? "file_hex"
sha_file_path = "#{@course_name}/SHA/#{file["file_hex"]}"
else
STDERR.puts "WARNING SHA file not found."
return
end
Extract_and_Save_File(sub_repo_fullname, "#{file["filename"]}", "#{course_sub_repo}", sha_file_path)
end
end
end
def Get_Sub_Index(repo_fullname, subs)
file = Get_File(repo_fullname, ".anacapa/submission.json")
if file != nil
file_contents = JSON.parse( Base64.decode64( file.content ) )
cur_id = file_contents["id"]
index = 0
for sub in subs
if cur_id == sub["id"]
break
end
index += 1
end
if subs[index] == subs[-1]
return index
else
return index + 1
end
else
puts "FILE = NIL"
return 0;
end
end
def Modify_Spec(proj_repo_fullname, old_hash)
puts "Modifying Spec for #{proj_repo_fullname}"
new_hash = Hash.new
new_hash["assignment_name"] = old_hash["name"]
new_hash["deadline"] = Time.now.strftime("%Y-%m-%dT21:33:00-08:00")
new_hash["maximum_group_size"] = old_hash["group_max"]
new_hash["expected_files"] = Array.new
new_hash["testables"] = Array.new
if old_hash.key?("status")
if old_hash["status"] == "ready"
new_hash["ready"] = true
else
new_hash["ready"] = false
end
else
new_hash["ready"] = false
end
for file in old_hash["expected_files"]
new_hash["expected_files"] << file["name"]
end
if old_hash.include?"execution_files_json"
for file in old_hash["execution_files_json"]
Extract_and_Save_File(proj_repo_fullname, ".anacapa/test_data/#{file["name"]}","submit-cs-json", "#{@course_name}/SHA/#{file["file_hex"]}")
end
end
if old_hash.include? "build_files_json"
for file in old_hash["build_files_json"]
Extract_and_Save_File(proj_repo_fullname,".anacapa/build_data/#{file["name"]}","submit-cs-json", "#{@course_name}/SHA/#{file["file_hex"]}")
end
end
if old_hash.include? "makefile"
Extract_and_Save_File(proj_repo_fullname, ".anacapa/build_data/makefile", "submit-cs-json", "#{@course_name}/SHA/#{old_hash["makefile"]["file_hex"]}")
end
for testable in old_hash["testables"]
testable_hash = Hash.new
testable_hash["test_name"] = testable["name"]
testable_hash["test_cases"] = Array.new
if testable["make_target"] != nil
testable_hash["build_command"] = "make " + testable["make_target"]
end
for test_case in testable["test_cases"]
test_case_hash = Hash.new
test_case_hash["name"] = test_case["name"]
test_case_hash["command"] = test_case["args"]
test_case_hash["diff_source"] = test_case["source"]
test_case_hash["expected"] = test_case["expected"]["sha1"]
test_case_hash["kind"] = test_case["output_type"]
if test_case.key?("hide_expected")
test_case_hash["hide_expected"] = test_case["hide_expected"]
else
test_case_hash["hide_expected"] = false
end
if test_case.key?("points")
test_case_hash["points"] = test_case["points"]
else
test_case_hash["points"] = 100
end
if test_case.key?("timeout")
test_case_hash["timeout"] = test_case["timeout"]
end
testable_hash["test_cases"] << test_case_hash
Extract_and_Save_File(proj_repo_fullname, ".anacapa/expected_outputs/#{test_case["expected"]["sha1"]}","submit-cs-json", "#{@course_name}/SHA/#{test_case["expected"]["sha1"]}")
end
new_hash["testables"] << testable_hash
end
return new_hash
end
def Does_Org_Exist()
begin
org = @client.organization(@course_org)
return true
rescue
return false
end
end
def Init_Repo(repo_name)
puts "Initializing Repo: #{repo_name}"
proj_repo_fullname = "#{@course_org}/#{repo_name}"
if ! Does_Repo_Exist(proj_repo_fullname)
begin
@client.create_repository( repo_name , {
:organization => @course_org,
:private => true
})
rescue Exception => e
STDERR.puts "WARNING: Unable to CREATE repository #{proj_repo_fullname}"
STDERR.puts e.message, e.backtrace.inspect
end
end
return proj_repo_fullname
end
def Does_Repo_Exist(proj_repo_fullname)
begin
proj_repo = @client.repo(proj_repo_fullname)
return true
rescue
return false
end
end
def Update_Proj_Spec(proj_repo_fullname, new_proj_spec)
old_proj_spec = Get_File(proj_repo_fullname, ".anacapa/assignment_spec.json")
if old_proj_spec == nil
begin
@client.create_contents(
proj_repo_fullname,
".anacapa/assignment_spec.json",
"Add Assignment_Spec JSON File to each project repo.",
JSON.pretty_generate(new_proj_spec) )
rescue Exception => e
STDERR.puts "WARNING: Unable to ADD assignment_spec.json"
STDERR.puts e.message, e.backtrace.inspect
end
else
begin
@client.update_contents(
proj_repo_fullname,
".anacapa/assignment_spec.json",
"Update Assignment_Spec JSON file for each project repo.",
old_proj_spec.sha,
JSON.pretty_generate(new_proj_spec) )
rescue Exception => e
STDERR.puts "WARNING: Unable to UPDATE assignment_spec.json"
STDERR.puts e.message, e.backtrace.inspect
end
end
end
def Extract_and_Save_File(proj_repo_fullname, file_path, source_repo, sha_file_path)
begin
file_contents = Base64.decode64( @client.contents( "submit-cs-conversion/#{source_repo}",
:path => "#{sha_file_path}"
).content )
rescue
STDERR.puts "WARNING: Unable to FIND submit-cs-conversion/#{source_repo}/#{sha_file_path}"
return
end
Create_Or_Update_File(proj_repo_fullname, file_path, file_contents)
end
def Create_Or_Update_File_Helper(repo_fullname, file_path, file_contents)
file = Get_File(repo_fullname, file_path)
if file == nil
begin
@client.create_contents(
repo_fullname,
file_path,
"Add #{file_path} in #{repo_fullname}.",
file_contents)
rescue Exception => e
STDERR.puts "WARNING: Unable to ADD #{file_path}."
STDERR.puts e.message, e.backtrace.inspect
raise e
end
else
begin
@client.update_contents(
repo_fullname,
file_path,
"Update #{file_path} in #{repo_fullname}" ,
file.sha,
file_contents)
rescue Exception => e
STDERR.puts "WARNING: Unable to UPDATE #{file_path}"
STDERR.puts e.message, e.backtrace.inspect
raise e
end
end
end
def Create_Or_Update_File(repo_fullname, file_path, file_contents)
num_tries = 0
max_tries = 3
done = false
while num_tries < max_tries && !done
begin
Create_Or_Update_File_Helper(repo_fullname, file_path, file_contents)
done = true
if num_tries > 0
STDERR.puts "SUCCEEDED!"
end
rescue
sleep(0.1)
num_tries += 1
if num_tries < max_tries
STDERR.puts "Retrying..."
else
STDERR.puts "GIVING UP!"
end
end
end
end
def Get_Course()
begin
course_json = JSON.parse( Base64.decode64( @client.contents(
"submit-cs-conversion/submit-cs-json",
:path => "#{@course_name}.json").content))
return course_json
rescue Exception => e
STDERR.puts "WARNING: Could not GET course at submit-cs-conversion/submit-cs-json/#{@course_name}.json"
STDERR.puts e.message, e.backtrace.inspect
return {}
end
end
def Get_File(proj_repo_fullname, file_path)
begin
file = @client.contents( proj_repo_fullname,
:path => file_path )
rescue
file = nil
end
return file
end
def Check_Membership()
if @client.organization_member?(@course_org, @client.user.login)
return true
else
STDERR.puts "WARNING: #{@client.user.login} is NOT an owner of the organization - " + @course_org
STDERR.puts "Check that you have an env.sh file with a personal access token that has repo access permission"
return false
end
end
def Github_User(username)
begin
@client.user(username)
return true
rescue Exception => e
STDERR.puts "WARNING: User #{username} is not user on github.ucsb.edu"
STDERR.puts e.message, e.backtrace.inspect
return false
end
end
def Add_Collaborator(repo_fullname, username)
begin
@client.add_collaborator(repo_fullname, username)
rescue Exception => e
STDERR.puts "WARNING: Unable to add #{username} as a collaborator to #{repo_fullname}"
STDERR.puts e.message, e.backtrace.inspect
end
end
end
| 22.671815 | 180 | 0.692268 |
03ea76bd5c6525c87b7c16e79e8ded6ca0c99ee0
| 831 |
def js_require_config_template
return <<template
var require = {
baseUrl: '/Scripts',
paths: {
jquery: 'jquery-1.9.1',
bootstrap: 'bootstrap',
knockout: 'knockout-3.2.0',
underscore: 'underscore',
bootstrapValidator: 'bootstrapValidator',
utils: 'Utils',
moment: 'moment',
bootstrapDateTimePicker: 'bootstrap-datetimepicker',
bsPagination: "bs_grid/bs_pagination/jquery.bs_pagination.min",
bsPaginationLocation: "bs_grid/bs_pagination/en.min",
juiFilter: "bs_grid/jui_filter/jquery.jui_filter_rules.min",
juiFilterLocation: "bs_grid/jui_filter/en.min",
jqUi: "bs_grid/jquery-ui.min",
jqBsGrid: "bs_grid/jquery.bs_grid.min",
jqBsGridLocation: "bs_grid/en.min"
}
};
template
end
| 34.625 | 72 | 0.636582 |
08eb0dc3c41c68d53435840a16f13afdc38398da
| 662 |
# Institution
Factory.define(:institution) do |f|
f.sequence(:title) { |n| "An Institution: #{n}" }
f.country 'GB'
end
Factory.define(:min_institution, class: Institution) do |f|
f.title "A Minimal Institution"
f.country "DE"
end
Factory.define(:max_institution, class: Institution) do |f|
f.title "A Maximal Institution"
f.country "GB"
f.city "Manchester"
f.address "Manchester Centre for Integrative Systems Biology, MIB/CEAS, The University of Manchester Faraday Building, Sackville Street, Manchester M60 1QD United Kingdom"
f.web_page "http://www.mib.ac.uk/"
f.discussion_links { [Factory.build(:discussion_link, label:'Slack')] }
end
| 33.1 | 173 | 0.732628 |
08884e8bf5fcc8ed93aaa5c86e80ef0e21dfb170
| 1,146 |
class ThinkingSphinx::Deltas::DefaultDelta
attr_reader :adapter, :options
def initialize(adapter, options = {})
@adapter, @options = adapter, options
end
def clause(delta_source = false)
return nil unless delta_source
"#{adapter.quoted_table_name}.#{quoted_column} = #{adapter.boolean_value delta_source}"
end
def delete(index, instance)
ThinkingSphinx::Deltas::DeleteJob.new(
index.name, index.document_id_for_key(instance.id)
).perform
end
def index(index)
ThinkingSphinx::Deltas::IndexJob.new(index.name).perform
end
def reset_query
(<<-SQL).strip.gsub(/\n\s*/, ' ')
UPDATE #{adapter.quoted_table_name}
SET #{quoted_column} = #{adapter.boolean_value false}
WHERE #{quoted_column} = #{adapter.boolean_value true}
SQL
end
def toggle(instance)
instance.send "#{column}=", true
end
def toggled?(instance)
instance.send "#{column}?"
end
private
def column
options[:column] || :delta
end
def config
ThinkingSphinx::Configuration.instance
end
def controller
config.controller
end
def quoted_column
adapter.quote column
end
end
| 19.758621 | 91 | 0.697208 |
1af4def911d3f033fccde780ffdce06a162ebbb3
| 3,315 |
describe EmailProcessor do
describe "#process" do
it "creates an entry based on the email token" do
user = create(:user)
email = create(
:griddler_email,
to: [{ token: user.reply_token }],
body: "I am great"
)
EmailProcessor.new(email).process
expect(user.newest_entry.body).to eq("I am great")
end
it "creates an entry even if the email token is uppercase" do
user = create(:user)
email = create(
:griddler_email,
to: [{ token: user.reply_token.upcase }],
body: "I am great"
)
EmailProcessor.new(email).process
expect(user.newest_entry.body).to eq("I am great")
end
it "parses the email body with an email reply parser" do
user = create(:user)
email = create(:griddler_email, to: [{ token: user.reply_token }])
expect(EmailReplyParser).to(
receive(:parse_reply).with(email.body).and_return(""))
EmailProcessor.new(email).process
end
context "when a user can't be found" do
it "raises an exception" do
user = create(:user)
email = create(:griddler_email, to: [{ token: "not-a-token" }])
expect do
EmailProcessor.new(email).process
end.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the entry can't be created" do
it "raises an exception" do
user = create(:user)
email = create(:griddler_email)
allow(user.entries).to receive(:create!).and_raise
expect do
EmailProcessor.new(email).process
end.to raise_error(ActiveRecord::ActiveRecordError)
end
end
it "sets the entry date to today's date in the user's time zone" do
Timecop.freeze(2014, 1, 1, 20) do # 8 PM UTC
user = create(:user, time_zone: "Guam") # UTC+10
email = create(:griddler_email, to: [{ token: user.reply_token }])
EmailProcessor.new(email).process
expect(user.newest_entry.date).to eq(Date.new(2014, 1, 2))
end
end
context "when the entry is a response to a past day's email" do
it "sets the entry date to the email's date" do
past_day = Date.new(last_year, 1, 2)
Timecop.freeze(last_year, 5, 10) do
user = create(:user)
email = create(
:griddler_email,
to: [{ token: user.reply_token }],
subject: "Re: #{PromptMailer::Subject.new(user, past_day)}"
)
EmailProcessor.new(email).process
expect(user.newest_entry.date).to eq(past_day)
end
end
end
context "when the entry is a response to an email from last year" do
it "sets the entry date to last year" do
end_of_last_year = Date.new(last_year, 12, 31)
Timecop.freeze(current_year, 1, 1) do
user = create(:user)
email = create(
:griddler_email,
to: [{ token: user.reply_token }],
subject: "Re: #{PromptMailer::Subject.new(user, end_of_last_year)}"
)
EmailProcessor.new(email).process
expect(user.newest_entry.date).to eq(end_of_last_year)
end
end
end
end
def current_year
Date.today.year
end
def last_year
current_year - 1
end
end
| 27.857143 | 79 | 0.601508 |
28ef1bce70584a01ee4e9648359f53de0c5e686d
| 1,581 |
#
# Author:: Matt Wrock (<[email protected]>)
# Copyright:: Copyright (c) 2016-2018 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require_relative "../../../spec_helper.rb"
require "openssl"
describe Ohai::System, "plugin fips" do
let(:enabled) { 0 }
let(:plugin) { get_plugin("windows/fips") }
let(:openssl_test_mode) { false }
subject do
plugin.run
plugin["fips"]["kernel"]["enabled"]
end
before(:each) do
allow(plugin).to receive(:collect_os).and_return(:windows)
end
around do |ex|
$FIPS_TEST_MODE = openssl_test_mode
ex.run
ensure
$FIPS_TEST_MODE = false
end
context "with OpenSSL.fips_mode == false" do
before { allow(OpenSSL).to receive(:fips_mode).and_return(false) }
it "does not set fips plugin" do
expect(subject).to be(false)
end
end
context "with OpenSSL.fips_mode == true" do
before { allow(OpenSSL).to receive(:fips_mode).and_return(true) }
it "sets fips plugin" do
expect(subject).to be(true)
end
end
end
| 26.79661 | 74 | 0.698925 |
395667077dc0172dd3ee25474ea5e1ecf8610622
| 3,217 |
require 'spec_helper_acceptance'
# Ensure time synchronization is in use - Section 2.2.1.1
describe package('ntp') do
it { should be_installed }
end
describe package('chrony') do
it { should be_installed }
end
# Ensure ntp is configured - Section 2.2.1.2
describe file('/etc/ntp.conf') do
it { should be_file }
it { should be_owned_by 'root' }
it { should be_grouped_into 'root' }
it { should be_mode 644 }
end
describe file('/etc/sysconfig/ntpd') do
it { should be_file }
it { should be_owned_by 'root' }
it { should be_grouped_into 'root' }
it { should be_mode 644 }
end
describe file('/usr/lib/systemd/system/ntpd.service') do
it { should be_file }
it { should be_owned_by 'root' }
it { should be_grouped_into 'root' }
it { should be_mode 644 }
its(:content) { should match /ExecStart=\/usr\/sbin\/ntpd -u ntp:ntp $OPTIONS/ }
end
# Ensure Chrony is configured - Section 2.2.1.3
describe file('/etc/chrony.conf') do
it { should be_file }
it { should be_owned_by 'root' }
it { should be_grouped_into 'root' }
it { should be_mode 644 }
end
describe file('/etc/sysconfig/chronyd') do
it { should be_file }
it { should be_owned_by 'root' }
it { should be_grouped_into 'root' }
it { should be_mode 644 }
its(:content) { should match /OPTIONS="-u chrony"/ }
end
# Ensure X Window System is not installed - Section 2.2.2
describe package('xorg-x11-server-Xorg') do
it { should_not be_installed }
end
# Ensure Avahi Server is not enabled - Section 2.2.3
describe service('avahi-daemon') do
it { should_not be_running }
end
# Ensure CUPS is not enabled - Section 2.2.4
describe service('cups') do
it { should_not be_running }
end
# Ensure DHCP Server is not enabled - Section 2.2.5
describe service('dhcpd') do
it { should_not running }
end
# Ensure LDAP Server is not enabled - Section 2.2.6
describe service('slapd') do
it { should_not be_running }
end
# Ensure NFS and RPC are not enabled - Section 2.2.7
describe service('nfs') do
it { should_not be_running }
end
describe service('nfs-server') do
it { should_not be_running }
end
describe service('rpcbind') do
it { should_not be_running }
end
# Ensure DNS Server is not enabled - Section 2.2.8
describe service('named') do
it { should_not be_running }
end
# Ensure FTP Server is not enabled - Section 2.2.9
describe package('vsftpd') do
it { should_not be_running }
end
# Ensure HTTP Server is not enabled - Section 2.2.10
describe service('httpd') do
it { should_not be_running }
end
# Ensure IMAP and POP3 Server are not enabled - Section 2.2.11
describe service('dovecot') do
it { should_not be_running }
end
# Ensure Samba is not enabled - Section 2.2.12
describe service('smb') do
it { should_not be_running }
end
# Ensure HTTP Proxy Server is not enabled - Section 2.2.13
describe service('squid') do
it { should_not be_running }
end
# Ensure SNMP Server is not enabled - Section 2.2.14
describe service('snmpd') do
it { should_not be_running }
end
# Ensure MTA is configured for local-only mode - Section 2.2.15
describe file('/etc/postfix/main.cf') do
it { should be_file }
end
| 25.330709 | 84 | 0.694125 |
796ed26f3acb2fabfcb87480835c7321cb5d05ac
| 5,739 |
# -------------------------------------------------------------------------- #
# Copyright 2002-2020, OpenNebula Project, OpenNebula Systems #
# #
# 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 "rexml/document"
include REXML
module Migrator
def db_version
"3.6.0"
end
def one_version
"OpenNebula 3.6.0"
end
def up
@db.run "ALTER TABLE cluster_pool RENAME TO old_cluster_pool;"
@db.run "CREATE TABLE cluster_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128), body TEXT, uid INTEGER, gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, UNIQUE(name));"
@db.fetch("SELECT * FROM old_cluster_pool") do |row|
doc = Document.new(row[:body])
doc.root.add_element("TEMPLATE")
@db[:cluster_pool].insert(
:oid => row[:oid],
:name => row[:name],
:body => doc.root.to_s,
:uid => row[:uid],
:gid => row[:gid],
:owner_u => row[:owner_u],
:group_u => row[:group_u],
:other_u => row[:other_u])
end
@db.run "DROP TABLE old_cluster_pool;"
@db.run "ALTER TABLE datastore_pool RENAME TO old_datastore_pool;"
@db.run "CREATE TABLE datastore_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128), body TEXT, uid INTEGER, gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, UNIQUE(name));"
system_tm = ""
@db.fetch("SELECT * FROM old_datastore_pool WHERE oid = 0") do |row|
doc = Document.new(row[:body])
doc.root.each_element("TM_MAD") { |e|
system_tm = e.text
}
doc.root.add_element("SYSTEM").text = "1"
@db[:datastore_pool].insert(
:oid => row[:oid],
:name => row[:name],
:body => doc.root.to_s,
:uid => row[:uid],
:gid => row[:gid],
:owner_u => row[:owner_u],
:group_u => row[:group_u],
:other_u => row[:other_u])
end
@db.fetch("SELECT * FROM old_datastore_pool WHERE oid > 0") do |row|
doc = Document.new(row[:body])
doc.root.add_element("SYSTEM").text = "0"
@db[:datastore_pool].insert(
:oid => row[:oid],
:name => row[:name],
:body => doc.root.to_s,
:uid => row[:uid],
:gid => row[:gid],
:owner_u => row[:owner_u],
:group_u => row[:group_u],
:other_u => row[:other_u])
end
@db.run "DROP TABLE old_datastore_pool;"
@db.run "ALTER TABLE vm_pool RENAME TO old_vm_pool;"
@db.run "CREATE TABLE vm_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128), body TEXT, uid INTEGER, gid INTEGER, last_poll INTEGER, state INTEGER, lcm_state INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER);"
@db.fetch("SELECT * FROM old_vm_pool") do |row|
doc = Document.new(row[:body])
doc.root.each_element("HISTORY_RECORDS/HISTORY") { |e|
e.add_element("TMMAD").text = system_tm
e.add_element("DS_ID").text = "0"
}
@db[:vm_pool].insert(
:oid => row[:oid],
:name => row[:name],
:body => doc.root.to_s,
:uid => row[:uid],
:gid => row[:gid],
:last_poll => row[:last_poll],
:state => row[:state],
:lcm_state => row[:lcm_state],
:owner_u => row[:owner_u],
:group_u => row[:group_u],
:other_u => row[:other_u])
end
@db.run "DROP TABLE old_vm_pool;"
@db.run "ALTER TABLE history RENAME TO old_history;"
@db.run "CREATE TABLE history (vid INTEGER, seq INTEGER, body TEXT, stime INTEGER, etime INTEGER, PRIMARY KEY(vid,seq));"
@db.fetch("SELECT * FROM old_history") do |row|
doc = Document.new(row[:body])
doc.root.add_element("TMMAD").text = system_tm
doc.root.add_element("DS_ID").text = "0"
@db[:history].insert(
:vid => row[:vid],
:seq => row[:seq],
:body => doc.root.to_s,
:stime => row[:stime],
:etime => row[:etime])
end
@db.run "DROP TABLE old_history;"
return true
end
end
| 39.040816 | 225 | 0.464889 |
1ae78113110c64adbd35f6677fa18dc1ee6beaa8
| 453 |
class CommentsController < ApplicationController
def new
@comment = Comment.new
render json: @comment
end
def create
@comment = Comment.new(comment_params)
if @comment.save
render json: @comment
else
render json: @comment
end
end
def destroy
@comment = Comment.find(params["id"])
@comment.destroy
end
private
def comment_params
params.require(:comment).permit(:content, :store_id)
end
end
| 13.727273 | 54 | 0.679912 |
7a9508294ca763c4a02fce5d8235d122f13dd054
| 39 |
module Fredify
VERSION = "0.0.1"
end
| 9.75 | 19 | 0.666667 |
038c1eeb4a34eca534beb8f48a38e7caf3311005
| 1,701 |
Rails.application.routes.draw do
#get 'photos/show'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
root 'places#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
resources :places, only: [:index, :show]
get 'photos/:id/show', to: 'photos#show', as: 'photos_show'
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
| 28.35 | 84 | 0.646091 |
f7219690722e7422cb7eeb41cf65a16c2f92bfb9
| 2,105 |
require 'spec_helper'
describe Profiles::KeysController do
let(:user) { create(:user) }
describe '#new' do
before { sign_in(user) }
it 'redirects to #index' do
get :new
expect(response).to redirect_to(profile_keys_path)
end
end
describe "#get_keys" do
describe "non existant user" do
it "does not generally work" do
get :get_keys, username: 'not-existent'
expect(response).not_to be_success
end
end
describe "user with no keys" do
it "does generally work" do
get :get_keys, username: user.username
expect(response).to be_success
end
it "renders all keys separated with a new line" do
get :get_keys, username: user.username
expect(response.body).to eq("")
end
it "responds with text/plain content type" do
get :get_keys, username: user.username
expect(response.content_type).to eq("text/plain")
end
end
describe "user with keys" do
let!(:key) { create(:key, user: user) }
let!(:another_key) { create(:another_key, user: user) }
let!(:deploy_key) { create(:deploy_key, user: user) }
it "does generally work" do
get :get_keys, username: user.username
expect(response).to be_success
end
it "renders all non deploy keys separated with a new line" do
get :get_keys, username: user.username
expect(response.body).not_to eq('')
expect(response.body).to eq(user.all_ssh_keys.join("\n"))
expect(response.body).to include(key.key.sub(' [email protected]', ''))
expect(response.body).to include(another_key.key)
expect(response.body).not_to include(deploy_key.key)
end
it "does not render the comment of the key" do
get :get_keys, username: user.username
expect(response.body).not_to match(/[email protected]/)
end
it "responds with text/plain content type" do
get :get_keys, username: user.username
expect(response.content_type).to eq("text/plain")
end
end
end
end
| 26.3125 | 78 | 0.634679 |
ac0d740f52209237092342bdfb3198420eb5c01a
| 799 |
require "language/node"
class MarkdownToc < Formula
desc "Generate a markdown TOC (table of contents) with Remarkable"
homepage "https://github.com/jonschlinkert/markdown-toc"
url "https://registry.npmjs.org/markdown-toc/-/markdown-toc-1.2.0.tgz"
sha256 "4a5bf3efafb21217889ab240caacd795a1101bfbe07cd8abb228cc44937acd9c"
license "MIT"
bottle do
sha256 cellar: :any_skip_relocation, all: "1fcb47b953cf9becfdcf24c6de36fbff454877e4c05ac47bc40be8d2df76ba0f"
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_equal "- [One](#one)\n- [Two](#two)",
shell_output("bash -c \"#{bin}/markdown-toc - <<< $'# One\\n\\n# Two'\"").strip
end
end
| 30.730769 | 112 | 0.720901 |
fffe435f6d4d6f0baf02a26050e199e32ae659a9
| 6,537 |
# frozen_string_literal: true
# encoding: utf-8
require 'spec_helper'
describe Mongo::Session::SessionPool do
min_server_fcv '3.6'
require_topology :replica_set, :sharded
clean_slate_for_all
let(:cluster) do
authorized_client.cluster.tap do |cluster|
# Cluster time assertions can fail if there are background operations
# that cause cluster time to be updated. This also necessitates clean
# state requirement.
authorized_client.close
end
end
describe '.create' do
let!(:pool) do
described_class.create(cluster)
end
it 'creates a session pool' do
expect(pool).to be_a(Mongo::Session::SessionPool)
end
it 'adds the pool as an instance variable on the cluster' do
expect(cluster.session_pool).to eq(pool)
end
end
describe '#initialize' do
let(:pool) do
described_class.new(cluster)
end
it 'sets the cluster' do
expect(pool.instance_variable_get(:@cluster)).to be(authorized_client.cluster)
end
end
describe '#inspect' do
let(:pool) do
described_class.new(cluster)
end
before do
s = pool.checkout
pool.checkin(s)
end
it 'includes the Ruby object_id in the formatted string' do
expect(pool.inspect).to include(pool.object_id.to_s)
end
it 'includes the pool size in the formatted string' do
expect(pool.inspect).to include('current_size=1')
end
end
describe 'checkout' do
let(:pool) do
described_class.new(cluster)
end
context 'when a session is checked out' do
let!(:session_a) do
pool.checkout
end
let!(:session_b) do
pool.checkout
end
before do
pool.checkin(session_a)
pool.checkin(session_b)
end
it 'is returned to the front of the queue' do
expect(pool.checkout).to be(session_b)
expect(pool.checkout).to be(session_a)
end
end
context 'when there are sessions about to expire in the queue' do
let(:old_session_a) do
pool.checkout
end
let(:old_session_b) do
pool.checkout
end
before do
pool.checkin(old_session_a)
pool.checkin(old_session_b)
allow(old_session_a).to receive(:last_use).and_return(Time.now - 1800)
allow(old_session_b).to receive(:last_use).and_return(Time.now - 1800)
end
context 'when a session is checked out' do
let(:checked_out_session) do
pool.checkout
end
it 'disposes of the old session and returns a new one' do
expect(checked_out_session).not_to be(old_session_a)
expect(checked_out_session).not_to be(old_session_b)
expect(pool.instance_variable_get(:@queue)).to be_empty
end
end
end
context 'when a sessions that is about to expire is checked in' do
let(:old_session_a) do
pool.checkout
end
let(:old_session_b) do
pool.checkout
end
before do
allow(old_session_a).to receive(:last_use).and_return(Time.now - 1800)
allow(old_session_b).to receive(:last_use).and_return(Time.now - 1800)
pool.checkin(old_session_a)
pool.checkin(old_session_b)
end
it 'disposes of the old sessions instead of adding them to the pool' do
expect(pool.checkout).not_to be(old_session_a)
expect(pool.checkout).not_to be(old_session_b)
expect(pool.instance_variable_get(:@queue)).to be_empty
end
end
end
describe '#end_sessions' do
let(:pool) do
described_class.create(client.cluster)
end
let!(:session_a) do
pool.checkout
end
let!(:session_b) do
pool.checkout
end
let(:subscriber) { EventSubscriber.new }
let(:client) do
authorized_client.tap do |client|
client.subscribe(Mongo::Monitoring::COMMAND, subscriber)
end
end
context 'when the number of ids is not larger than 10,000' do
before do
client.database.command(ping: 1)
pool.checkin(session_a)
pool.checkin(session_b)
end
let!(:cluster_time) do
client.cluster.cluster_time
end
let(:end_sessions_command) do
pool.end_sessions
subscriber.started_events.find { |c| c.command_name == 'endSessions'}
end
it 'sends the endSessions command with all the session ids' do
end_sessions_command
expect(end_sessions_command.command[:endSessions]).to include(BSON::Document.new(session_a.session_id))
expect(end_sessions_command.command[:endSessions]).to include(BSON::Document.new(session_b.session_id))
end
context 'when talking to a replica set or mongos' do
it 'sends the endSessions command with all the session ids and cluster time' do
start_time = client.cluster.cluster_time
end_sessions_command
end_time = client.cluster.cluster_time
expect(end_sessions_command.command[:endSessions]).to include(BSON::Document.new(session_a.session_id))
expect(end_sessions_command.command[:endSessions]).to include(BSON::Document.new(session_b.session_id))
# cluster time may have been advanced due to background operations
actual_cluster_time = Mongo::ClusterTime.new(end_sessions_command.command[:$clusterTime])
expect(actual_cluster_time).to be >= start_time
expect(actual_cluster_time).to be <= end_time
end
end
end
context 'when the number of ids is larger than 10_000' do
let(:ids) do
10_001.times.map do |i|
bytes = [SecureRandom.uuid.gsub(/\-/, '')].pack('H*')
BSON::Document.new(id: BSON::Binary.new(bytes, :uuid))
end
end
before do
queue = []
ids.each do |id|
queue << double('session', session_id: id)
end
pool.instance_variable_set(:@queue, queue)
expect(Mongo::Operation::Command).to receive(:new).at_least(:twice).and_call_original
end
let(:end_sessions_commands) do
subscriber.started_events.select { |c| c.command_name == 'endSessions'}
end
it 'sends the command more than once' do
pool.end_sessions
expect(end_sessions_commands.size).to eq(2)
expect(end_sessions_commands[0].command[:endSessions]).to eq(ids[0...10_000])
expect(end_sessions_commands[1].command[:endSessions]).to eq([ids[10_000]])
end
end
end
end
| 27.124481 | 113 | 0.653205 |
8780560844cc1fcc4e37b19acf37b3e905fe4ce2
| 2,569 |
RSpec.describe HashStruct, '.property' do
context 'qualified with coerce: :boolean' do
reading_and_writing_attributes_via do |way_to_read, way_to_write|
it 'defines a property that accepts true as-is' do
model = define_model { property :notify, coerce: :boolean }
expect(model)
.to have_attribute(:notify)
.that_maps(true => true)
.reading_via(way_to_read)
.writing_via(way_to_write)
end
it 'defines a property that accepts false as-is' do
model = define_model { property :notify, coerce: :boolean }
expect(model)
.to have_attribute(:notify)
.that_maps(false => false)
.reading_via(way_to_read)
.writing_via(way_to_write)
end
it 'defines a property that coerces truthy values to true' do
model = define_model { property :notify, coerce: :boolean }
expect(model)
.to have_attribute(:notify)
.that_maps('anything' => true, 1 => true, [1, 2, 3] => true)
.reading_via(way_to_read)
.writing_via(way_to_write)
end
# TODO: Should this be the case? Should nil turn into false or should it
# raise an error since the property is required?
it 'defines a property that coerces falsey values to false' do
model = define_model { property :notify, coerce: :boolean }
expect(model)
.to have_attribute(:notify)
.that_maps(false => false, nil => false)
.reading_via(way_to_read)
.writing_via(way_to_write)
end
end
reading_attributes_via do |way_to_read|
context 'and with a default provided' do
context 'when the attribute is not provided on initialization' do
it 'sets the attribute to the default, coercing it to a boolean' do
model = define_model do
property :notify, default: 'yes', coerce: :boolean
end
instance = model.new
expect(read_attribute_via(way_to_read, instance, :notify))
.to be(true)
end
end
context 'when the attribute is provided on initialization' do
it 'uses the provided value to set the attribute' do
model = define_model do
property :notify, default: true, coerce: :boolean
end
instance = model.new(notify: false)
expect(read_attribute_via(way_to_read, instance, :notify))
.to be(false)
end
end
end
end
end
end
| 33.802632 | 78 | 0.608408 |
915d09075c9678db3b7f27f622d07b2afaabb66c
| 337 |
cask 'sqlitemanager' do
version '4.7.0'
sha256 '04ba527cb257a6ff20ec86c088e7230d9860260ae37c3c30d8374c95d9d8eaaa'
url 'http://www.sqlabs.com/download/SQLiteManager.zip'
appcast 'http://www.sqlabs.com/news/sqlitemanager/'
name 'SQLiteManager'
homepage 'http://www.sqlabs.com/sqlitemanager.php'
app 'SQLiteManager.app'
end
| 28.083333 | 75 | 0.774481 |
62f96059acf24bbd1ef16e28f5002e989b4278b8
| 1,074 |
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Spotlight::BulkUpdatesCsvTemplateService do
subject(:service) { described_class.new(exhibit: exhibit) }
let(:exhibit) { FactoryBot.create(:exhibit) }
let!(:tag1) { FactoryBot.create(:tagging, tagger: exhibit, taggable: exhibit) }
let!(:tag2) { FactoryBot.create(:tagging, tagger: exhibit, taggable: exhibit) }
describe '#template' do
let(:view_context) { double('ViewContext', document_presenter: double('DocumentPresenter', heading: 'Document Title')) }
it 'has a row for every document (+ the header)' do
template = CSV.parse(service.template(view_context: view_context).to_a.join)
expect(template).to have_at_least(56).items
expect(template[0].join(',')).to match(/Item ID,Item Title,Visibility,Tag: tagging\d,Tag: tagging\d/)
end
it 'only has requested columns' do
template = CSV.parse(service.template(view_context: view_context, tags: false).to_a.join)
expect(template[0].join(',')).to eq 'Item ID,Item Title,Visibility'
end
end
end
| 39.777778 | 124 | 0.716015 |
61a7351797a46dd25bcd8f034fb2927192221506
| 665 |
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module DulceSampleApp
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
| 33.25 | 82 | 0.766917 |
91ff8a260bdafd9b370eaf65eec4baab5e2b23cd
| 642 |
# frozen_string_literal: true
require 'spec_helper'
describe 'cis_hardening::setup::sudo' do
on_supported_os.each do |os, os_facts|
context "on #{os}" do
let(:facts) { os_facts }
# Section 1.3 - Configure sudo
# Ensure sudo is installed - Section 1.3.1
it {
is_expected.to contain_package('sudo').with(
'ensure'
)
}
# Ensure sudo commands use pty - Section 1.3.2
it {
is_expected.to contain_file('/etc/sudoers.d/cis_sudoers_defaults.conf').with(
)
}
it { is_expected.to compile }
end
end
end
| 19.454545 | 87 | 0.565421 |
1cd25d88d4b5ae848675fee3d867fc94fe47021a
| 343 |
FactoryBot.define do
factory :climate_policy_milestone, class: 'ClimatePolicy::Milestone' do
association :policy, factory: :climate_policy
association :source, factory: :climate_policy_source
name { 'ECBC integrated in GRIHA ' }
responsible_authority { 'BEE' }
date { 'August 2010' }
status { 'Attained' }
end
end
| 28.583333 | 73 | 0.71137 |
bbb95d28a71c0f5ee6bf3ea87f8dc6dd94cac242
| 1,792 |
require 'ostruct'
module Vcloud
module Launcher
class Preamble
class MissingConfigurationError < StandardError ; end
class MissingTemplateError < StandardError ; end
attr_reader :preamble_vars, :script_path
def initialize(vapp_name, vm_config)
@vapp_name = vapp_name
bootstrap_config = vm_config[:bootstrap]
raise MissingConfigurationError if bootstrap_config.nil?
@script_path = bootstrap_config.fetch(:script_path, nil)
raise MissingTemplateError unless @script_path
# Missing vars is acceptable - noop template.
@preamble_vars = bootstrap_config.fetch(:vars, {})
extra_disks = vm_config.fetch(:extra_disks, {})
@preamble_vars.merge!(extra_disks: extra_disks)
@script_post_processor = bootstrap_config.fetch(:script_post_processor, nil)
end
def generate
@script_post_processor ? post_process_erb_output : interpolated_preamble
end
def interpolated_preamble
@interpolated_preamble = interpolate_erb_file
end
private
def interpolate_erb_file
erb_vars = OpenStruct.new({
vapp_name: @vapp_name,
vars: @preamble_vars,
})
binding_object = erb_vars.instance_eval { binding }
template_string = load_erb_file
ERB.new(template_string, nil, '>-').result(binding_object)
end
def load_erb_file
File.read(File.expand_path(@script_path))
end
def post_process_erb_output
# Open3.capture2, as we just need to return STDOUT of the post_processor_script
Open3.capture2(
File.expand_path(@script_post_processor),
stdin_data: interpolated_preamble).first
end
end
end
end
| 28.444444 | 87 | 0.672991 |
28210781c8b8209fccb465e7579435891884b48c
| 2,337 |
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'date'
require_relative 'lib/sensu-plugins-slack'
Gem::Specification.new do |s|
s.authors = ['Sensu-Plugins and contributors']
s.date = Date.today.to_s
s.description = 'Sensu plugins for interfacing with Slack chat'
s.email = '<[email protected]>'
s.executables = Dir.glob('bin/**/*.rb').map { |file| File.basename(file) }
s.files = Dir.glob('{bin,lib}/**/*') + %w(LICENSE README.md CHANGELOG.md)
s.homepage = 'https://github.com/sensu-plugins/sensu-plugins-slack'
s.license = 'MIT'
s.metadata = { 'maintainer' => 'sensu-plugin',
'development_status' => 'active',
'production_status' => 'unstable - testing recommended',
'release_draft' => 'false',
'release_prerelease' => 'false' }
s.name = 'sensu-plugins-slack'
s.platform = Gem::Platform::RUBY
s.post_install_message = 'You can use the embedded Ruby by setting EMBEDDED_RUBY=true in /etc/default/sensu'
s.require_paths = ['lib']
s.required_ruby_version = '>= 2.3.0'
s.summary = 'Sensu plugins for interfacing with Slack chat'
s.test_files = s.files.grep(%r{^(test|spec|features)/})
s.version = SensuPluginsSlack::Version::VER_STRING
s.add_runtime_dependency 'erubis', '2.7.0'
s.add_runtime_dependency 'sensu-plugin', '~> 4.0'
s.add_development_dependency 'bundler', '~> 2.1'
s.add_development_dependency 'codeclimate-test-reporter', '~> 1.0'
s.add_development_dependency 'github-markup', '~> 4.0'
s.add_development_dependency 'pry', '~> 0.10'
s.add_development_dependency 'rake', '~> 13.0'
s.add_development_dependency 'redcarpet', '~> 3.2'
s.add_development_dependency 'rubocop', '~> 0.40.0'
s.add_development_dependency 'rspec', '~> 3.1'
s.add_development_dependency 'yard', '~> 0.8'
end
| 51.933333 | 112 | 0.549422 |
61cb7ca8b5180d2e45c947d179a3ddf0511070eb
| 22,912 |
=begin
#ESP Documentation
#The Evident Security Platform API (version 2.0) is designed to allow users granular control over their Amazon Web Service security experience by allowing them to review alerts, monitor signatures, and create custom signatures.
OpenAPI spec version: v2_sdk
Generated by: https://github.com/swagger-api/swagger-codegen.git
=end
require "uri"
module ESP
class SuppressionsApi
attr_accessor :api_client
def initialize(api_client = ApiClient.default)
@api_client = api_client
end
# Create a suppression
#
# @param external_account_ids IDs of external accounts to be suppressed
# @param reason The reason for the suppresion
# @param regions Codes of regions to be suppressed
# @param [Hash] opts the optional parameters
# @option opts [String] :include Related objects that can be included in the response: organization, created_by, regions, external_accounts, signatures, custom_signatures See Including Objects for more information.
# @option opts [Array<Integer>] :custom_signature_ids IDs of custom signatures to be suppressed
# @option opts [BOOLEAN] :include_new_accounts When enabled, automatically adds new accounts to this suppression. This field can only be set by an organization level user.
# @option opts [String] :resource The resource string this suppression will suppress alerts for
# @option opts [Array<Integer>] :signature_ids IDs of signatures to be suppressed
# @return [Suppression]
def create(external_account_ids, reason, regions, opts = {})
data, _status_code, _headers = create_with_http_info(external_account_ids, reason, regions, opts)
return data
end
# Create a suppression
#
# @param external_account_ids IDs of external accounts to be suppressed
# @param reason The reason for the suppresion
# @param regions Codes of regions to be suppressed
# @param [Hash] opts the optional parameters
# @option opts [String] :include Related objects that can be included in the response: organization, created_by, regions, external_accounts, signatures, custom_signatures See Including Objects for more information.
# @option opts [Array<Integer>] :custom_signature_ids IDs of custom signatures to be suppressed
# @option opts [BOOLEAN] :include_new_accounts When enabled, automatically adds new accounts to this suppression. This field can only be set by an organization level user.
# @option opts [String] :resource The resource string this suppression will suppress alerts for
# @option opts [Array<Integer>] :signature_ids IDs of signatures to be suppressed
# @return [Array<(Suppression, Fixnum, Hash)>] Suppression data, response status code and response headers
def create_with_http_info(external_account_ids, reason, regions, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: SuppressionsApi.create ..."
end
# verify the required parameter 'external_account_ids' is set
fail ArgumentError, "Missing the required parameter 'external_account_ids' when calling SuppressionsApi.create" if external_account_ids.nil?
# verify the required parameter 'reason' is set
fail ArgumentError, "Missing the required parameter 'reason' when calling SuppressionsApi.create" if reason.nil?
# verify the required parameter 'regions' is set
fail ArgumentError, "Missing the required parameter 'regions' when calling SuppressionsApi.create" if regions.nil?
# resource path
local_var_path = "/api/v2/suppressions.json_api".sub('{format}','json_api')
# query parameters
query_params = {}
query_params[:'include'] = opts[:'include'] if !opts[:'include'].nil?
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/vnd.api+json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/vnd.api+json'])
# form parameters
form_params = {}
form_params["external_account_ids"] = @api_client.build_collection_param(external_account_ids, :multi)
form_params["reason"] = reason
form_params["regions"] = @api_client.build_collection_param(regions, :multi)
form_params["custom_signature_ids"] = @api_client.build_collection_param(opts[:'custom_signature_ids'], :multi) if !opts[:'custom_signature_ids'].nil?
form_params["include_new_accounts"] = opts[:'include_new_accounts'] if !opts[:'include_new_accounts'].nil?
form_params["resource"] = opts[:'resource'] if !opts[:'resource'].nil?
form_params["signature_ids"] = @api_client.build_collection_param(opts[:'signature_ids'], :multi) if !opts[:'signature_ids'].nil?
# http body (model)
post_body = nil
auth_names = []
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Suppression')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: SuppressionsApi#create\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Creates a suppression from an alert
# A successful call to this API creates a new suppression based on the supplied alert_id. The body of the request must contain a json api compliant hash of the suppression reason and an alert id.
# @param alert_id The ID for the alert you want to create a suppression for
# @param reason The reason for creating the suppression
# @param [Hash] opts the optional parameters
# @option opts [String] :include Related objects that can be included in the response: organization, created_by, regions, external_accounts, signatures, custom_signatures See Including Objects for more information.
# @return [Suppression]
def create_from_alert(alert_id, reason, opts = {})
data, _status_code, _headers = create_from_alert_with_http_info(alert_id, reason, opts)
return data
end
# Creates a suppression from an alert
# A successful call to this API creates a new suppression based on the supplied alert_id. The body of the request must contain a json api compliant hash of the suppression reason and an alert id.
# @param alert_id The ID for the alert you want to create a suppression for
# @param reason The reason for creating the suppression
# @param [Hash] opts the optional parameters
# @option opts [String] :include Related objects that can be included in the response: organization, created_by, regions, external_accounts, signatures, custom_signatures See Including Objects for more information.
# @return [Array<(Suppression, Fixnum, Hash)>] Suppression data, response status code and response headers
def create_from_alert_with_http_info(alert_id, reason, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: SuppressionsApi.create_from_alert ..."
end
# verify the required parameter 'alert_id' is set
fail ArgumentError, "Missing the required parameter 'alert_id' when calling SuppressionsApi.create_from_alert" if alert_id.nil?
# verify the required parameter 'reason' is set
fail ArgumentError, "Missing the required parameter 'reason' when calling SuppressionsApi.create_from_alert" if reason.nil?
# resource path
local_var_path = "/api/v2/suppressions/alerts.json_api".sub('{format}','json_api')
# query parameters
query_params = {}
query_params[:'include'] = opts[:'include'] if !opts[:'include'].nil?
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/vnd.api+json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/vnd.api+json'])
# form parameters
form_params = {}
form_params["alert_id"] = alert_id
form_params["reason"] = reason
# http body (model)
post_body = nil
auth_names = []
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Suppression')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: SuppressionsApi#create_from_alert\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Deactivate a suppression
#
# @param id Suppression ID
# @param [Hash] opts the optional parameters
# @option opts [String] :include Related objects that can be included in the response: organization, created_by, regions, external_accounts, signatures, custom_signatures See Including Objects for more information.
# @return [Suppression]
def deactivate(id, opts = {})
data, _status_code, _headers = deactivate_with_http_info(id, opts)
return data
end
# Deactivate a suppression
#
# @param id Suppression ID
# @param [Hash] opts the optional parameters
# @option opts [String] :include Related objects that can be included in the response: organization, created_by, regions, external_accounts, signatures, custom_signatures See Including Objects for more information.
# @return [Array<(Suppression, Fixnum, Hash)>] Suppression data, response status code and response headers
def deactivate_with_http_info(id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: SuppressionsApi.deactivate ..."
end
# verify the required parameter 'id' is set
fail ArgumentError, "Missing the required parameter 'id' when calling SuppressionsApi.deactivate" if id.nil?
# resource path
local_var_path = "/api/v2/suppressions/{id}/deactivate.json_api".sub('{format}','json_api').sub('{' + 'id' + '}', id.to_s)
# query parameters
query_params = {}
query_params[:'include'] = opts[:'include'] if !opts[:'include'].nil?
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/vnd.api+json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/vnd.api+json'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
data, status_code, headers = @api_client.call_api(:PATCH, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Suppression')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: SuppressionsApi#deactivate\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Get a list of Suppressions
#
# @param [Hash] opts the optional parameters
# @option opts [String] :include Related objects that can be included in the response: organization, created_by, regions, external_accounts, signatures, custom_signatures See Including Objects for more information.
# @option opts [Hash<String, String>] :filter Filter Params for Searching. Equality Searchable Attributes: [id, aasm_state, status, suppression_type, resource, reason] Matching Searchable Attributes: [resource, reason] Sortable Attributes: [updated_at, created_at, id, status] Searchable Associations: [regions, external_accounts, created_by, user, signatures, custom_signatures] See Searching Lists for more information. See the filter parameter of the association's list action to see what attributes are searchable on each association. See Conditions on Relationships in Searching Lists for more information.
# @option opts [String] :page Page Number and Page Size. Number is the page number of the collection to return, size is the number of items to return per page. (default to {:number=>1,+:size=>20})
# @return [PaginatedCollection]
def list(opts = {})
data, _status_code, _headers = list_with_http_info(opts)
return data
end
# Get a list of Suppressions
#
# @param [Hash] opts the optional parameters
# @option opts [String] :include Related objects that can be included in the response: organization, created_by, regions, external_accounts, signatures, custom_signatures See Including Objects for more information.
# @option opts [Hash<String, String>] :filter Filter Params for Searching. Equality Searchable Attributes: [id, aasm_state, status, suppression_type, resource, reason] Matching Searchable Attributes: [resource, reason] Sortable Attributes: [updated_at, created_at, id, status] Searchable Associations: [regions, external_accounts, created_by, user, signatures, custom_signatures] See Searching Lists for more information. See the filter parameter of the association's list action to see what attributes are searchable on each association. See Conditions on Relationships in Searching Lists for more information.
# @option opts [String] :page Page Number and Page Size. Number is the page number of the collection to return, size is the number of items to return per page.
# @return [Array<(PaginatedCollection, Fixnum, Hash)>] PaginatedCollection data, response status code and response headers
def list_with_http_info(opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: SuppressionsApi.list ..."
end
# resource path
local_var_path = "/api/v2/suppressions.json_api".sub('{format}','json_api')
# query parameters
query_params = {}
query_params[:'include'] = opts[:'include'] if !opts[:'include'].nil?
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/vnd.api+json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/vnd.api+json'])
# form parameters
form_params = {}
form_params["filter"] = opts[:'filter'] if !opts[:'filter'].nil?
form_params["page"] = opts[:'page'] if !opts[:'page'].nil?
# http body (model)
post_body = nil
auth_names = []
data, status_code, headers = @api_client.call_api(:PUT, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'PaginatedCollection')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: SuppressionsApi#list\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Show a single Suppression
#
# @param id Suppression ID
# @param [Hash] opts the optional parameters
# @option opts [String] :include Related objects that can be included in the response: organization, created_by, regions, external_accounts, signatures, custom_signatures See Including Objects for more information.
# @return [Suppression]
def show(id, opts = {})
data, _status_code, _headers = show_with_http_info(id, opts)
return data
end
# Show a single Suppression
#
# @param id Suppression ID
# @param [Hash] opts the optional parameters
# @option opts [String] :include Related objects that can be included in the response: organization, created_by, regions, external_accounts, signatures, custom_signatures See Including Objects for more information.
# @return [Array<(Suppression, Fixnum, Hash)>] Suppression data, response status code and response headers
def show_with_http_info(id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: SuppressionsApi.show ..."
end
# verify the required parameter 'id' is set
fail ArgumentError, "Missing the required parameter 'id' when calling SuppressionsApi.show" if id.nil?
# resource path
local_var_path = "/api/v2/suppressions/{id}.json_api".sub('{format}','json_api').sub('{' + 'id' + '}', id.to_s)
# query parameters
query_params = {}
query_params[:'include'] = opts[:'include'] if !opts[:'include'].nil?
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/vnd.api+json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/vnd.api+json'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Suppression')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: SuppressionsApi#show\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Update a(n) Suppression
#
# @param id Suppression ID
# @param [Hash] opts the optional parameters
# @option opts [String] :include Related objects that can be included in the response: organization, created_by, regions, external_accounts, signatures, custom_signatures See Including Objects for more information.
# @option opts [Array<Integer>] :custom_signature_ids IDs of custom signatures to be suppressed
# @option opts [Array<Integer>] :external_account_ids IDs of external accounts to be suppressed
# @option opts [BOOLEAN] :include_new_accounts When enabled, automatically adds new accounts to this suppression. This field can only be set by an organization level user.
# @option opts [String] :reason The reason for the suppresion
# @option opts [Array<String>] :regions Codes of regions to be suppressed
# @option opts [String] :resource The resource string this suppression will suppress alerts for
# @option opts [Array<Integer>] :signature_ids IDs of signatures to be suppressed
# @return [Suppression]
def update(id, opts = {})
data, _status_code, _headers = update_with_http_info(id, opts)
return data
end
# Update a(n) Suppression
#
# @param id Suppression ID
# @param [Hash] opts the optional parameters
# @option opts [String] :include Related objects that can be included in the response: organization, created_by, regions, external_accounts, signatures, custom_signatures See Including Objects for more information.
# @option opts [Array<Integer>] :custom_signature_ids IDs of custom signatures to be suppressed
# @option opts [Array<Integer>] :external_account_ids IDs of external accounts to be suppressed
# @option opts [BOOLEAN] :include_new_accounts When enabled, automatically adds new accounts to this suppression. This field can only be set by an organization level user.
# @option opts [String] :reason The reason for the suppresion
# @option opts [Array<String>] :regions Codes of regions to be suppressed
# @option opts [String] :resource The resource string this suppression will suppress alerts for
# @option opts [Array<Integer>] :signature_ids IDs of signatures to be suppressed
# @return [Array<(Suppression, Fixnum, Hash)>] Suppression data, response status code and response headers
def update_with_http_info(id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: SuppressionsApi.update ..."
end
# verify the required parameter 'id' is set
fail ArgumentError, "Missing the required parameter 'id' when calling SuppressionsApi.update" if id.nil?
# resource path
local_var_path = "/api/v2/suppressions/{id}.json_api".sub('{format}','json_api').sub('{' + 'id' + '}', id.to_s)
# query parameters
query_params = {}
query_params[:'include'] = opts[:'include'] if !opts[:'include'].nil?
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/vnd.api+json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/vnd.api+json'])
# form parameters
form_params = {}
form_params["custom_signature_ids"] = @api_client.build_collection_param(opts[:'custom_signature_ids'], :multi) if !opts[:'custom_signature_ids'].nil?
form_params["external_account_ids"] = @api_client.build_collection_param(opts[:'external_account_ids'], :multi) if !opts[:'external_account_ids'].nil?
form_params["include_new_accounts"] = opts[:'include_new_accounts'] if !opts[:'include_new_accounts'].nil?
form_params["reason"] = opts[:'reason'] if !opts[:'reason'].nil?
form_params["regions"] = @api_client.build_collection_param(opts[:'regions'], :multi) if !opts[:'regions'].nil?
form_params["resource"] = opts[:'resource'] if !opts[:'resource'].nil?
form_params["signature_ids"] = @api_client.build_collection_param(opts[:'signature_ids'], :multi) if !opts[:'signature_ids'].nil?
# http body (model)
post_body = nil
auth_names = []
data, status_code, headers = @api_client.call_api(:PATCH, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Suppression')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: SuppressionsApi#update\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
end
end
| 55.746959 | 621 | 0.709672 |
386583d7b225cf41e852e4370a4e5b37e3646e5b
| 250 |
class RESO::Lookup::OwnerPay < RESO::Enumeration
has_many :owner_pay_assignments, foreign_key: :enumeration_id
has_many :reso_property_financials, through: :owner_pay_assignments, source: :enumerable, source_type: "RESO::Property::Financial"
end
| 50 | 132 | 0.812 |
7a4154bc179f870b82f2f0cf2a582e7f0c9132cf
| 723 |
module RSpec
module Dmv
module LengthValidator
def generate_length_validation_test_cases(options)
rspec.context "length" do
matcher_options = []
matcher_options << { method: :is_at_least, param: options[:min] } if options[:min].present?
matcher_options << { method: :with_message, param: options[:message] } if options[:message].present?
matcher_options << { method: :is_at_most, param: options[:max] } if options[:max].present?
options[:attributes].each do |attribute|
example do
should ensure_length_of(attribute.to_sym).call_methods( matcher_options )
end
end
end
end
end
end
end
| 32.863636 | 110 | 0.629322 |
6a1bf54dda3e0f5ad67e6fcf3c23b5e488448c98
| 239 |
class BaseMailer < ActionMailer::Base
helper ApplicationHelper, NewslettersHelper
prepend_view_path Rails.root.join('app/mailers/views')
layout "base"
FROM = "#{CONFIG[:name]} <hello@#{CONFIG[:host]}>"
default from: FROM
end
| 19.916667 | 56 | 0.723849 |
e99143cdccb38ed075105fac7a59ac1ace5f47c6
| 2,676 |
# frozen_string_literal: true
module Neo4j::Driver::Internal
class SecuritySetting
include Scheme
attr_reader :encrypted, :trust_strategy, :customized
def initialize(encrypted, trust_strategy, customized)
@encrypted = encrypted
@trust_strategy = trust_strategy
@customized = customized
end
def create_security_plan(uri_scheme)
validate_scheme!(uri_scheme)
begin
if security_scheme?(uri_scheme)
assert_security_settings_not_user_configured(uri_scheme)
create_security_plan_from_scheme(uri_scheme)
else
create_security_plan_impl(encrypted, trust_strategy)
end
# rescue java.security.GeneralSecurityException, IOError
rescue IOError
raise Neo4j::Driver::Exceptions::ClientException, 'Unable to establish SSL parameters'
end
end
def create_security_plan_from_scheme(uri_scheme)
if high_trust_scheme?(uri_scheme)
org.neo4j.driver.internal.security.SecurityPlanImpl.forSystemCASignedCertificates(
true, org.neo4j.driver.internal.RevocationStrategy::NO_CHECKS
)
else
org.neo4j.driver.internal.security.SecurityPlanImpl.forAllCertificates(false, org.neo4j.driver.internal.RevocationStrategy::NO_CHECKS)
end
end
private
def assert_security_settings_not_user_configured(uri_scheme)
return unless customized
raise Neo4j::Driver::Exceptions::ClientException,
"Scheme #{uri_scheme} is not configurable with manual encryption and trust settings"
end
def create_security_plan_impl(encrypted, trust_strategy)
return Security::SecurityPlanImpl.insecure unless encrypted
hostname_verification_enabled = trust_strategy.hostname_verification_enabled?
revocation_strategy = trust_strategy.revocation_strategy
case trust_strategy.strategy
when Config::TrustStrategy::TRUST_CUSTOM_CA_SIGNED_CERTIFICATES
return Security::SecurityPlanImpl.forCustomCASignedCertificates(
trust_strategy.cert_file_to_java, hostname_verification_enabled, revocation_strategy
)
when Config::TrustStrategy::TRUST_SYSTEM_CA_SIGNED_CERTIFICATES
return Security::SecurityPlanImpl.forSystemCASignedCertificates(
hostname_verification_enabled, revocation_strategy
)
when Config::TrustStrategy::TRUST_ALL_CERTIFICATES
return Security::SecurityPlanImpl.forAllCertificates(
hostname_verification_enabled, revocation_strategy
)
else
raise ClientException, "Unknown TLS authentication strategy: #{trust_strategy.strategy}"
end
end
end
end
| 36.162162 | 142 | 0.746263 |
7acc3f38edbe76994177a0679bada85421215966
| 58 |
module Ci
module Git
BLANK_SHA = '0' * 40
end
end
| 9.666667 | 24 | 0.603448 |
1ae3b5d8d54e17b71767ffa970b258e78a54b64f
| 3,867 |
# frozen_string_literal: true
require("test_helper")
# users interests
class InterestControllerTest < FunctionalTestCase
# Test list feature from left-hand column.
def test_list_interests
login("rolf")
Interest.create(target: observations(:minimal_unknown_obs),
user: rolf, state: true)
Interest.create(target: names(:agaricus_campestris), user: rolf,
state: true)
get_with_dump(:list_interests)
assert_template("list_interests")
end
def test_set_interest_another_user
login("rolf")
get(:set_interest,
type: "Observation", id: observations(:minimal_unknown_obs),
user: mary.id)
assert_flash_error
end
def test_set_interest_no_object
login("rolf")
get(:set_interest, type: "Observation", id: 100, state: 1)
assert_flash_error
end
def test_set_interest_bad_type
login("rolf")
get(:set_interest, type: "Bogus", id: 1, state: 1)
assert_flash_error
end
def test_set_interest
peltigera = names(:peltigera)
minimal_unknown = observations(:minimal_unknown_obs)
detailed_unknown = observations(:detailed_unknown_obs)
# Succeed: Turn interest on in minimal_unknown.
login("rolf")
get(:set_interest, type: "Observation", id: minimal_unknown.id, state: 1,
user: rolf.id)
assert_flash_success
# Make sure rolf now has one Interest: interested in minimal_unknown.
rolfs_interests = Interest.where(user_id: rolf.id)
assert_equal(1, rolfs_interests.length)
assert_equal(minimal_unknown, rolfs_interests.first.target)
assert_equal(true, rolfs_interests.first.state)
# Succeed: Turn same interest off.
login("rolf")
get(:set_interest, type: "Observation", id: minimal_unknown.id, state: -1)
assert_flash_success
# Make sure rolf now has one Interest: NOT interested in minimal_unknown.
rolfs_interests = Interest.where(user_id: rolf.id)
assert_equal(1, rolfs_interests.length)
assert_equal(minimal_unknown, rolfs_interests.first.target)
assert_equal(false, rolfs_interests.first.state)
# Succeed: Turn another interest off from no interest.
login("rolf")
get(:set_interest, type: "Name", id: peltigera.id, state: -1)
assert_flash_success
# Make sure rolf now has two Interests.
rolfs_interests = Interest.where(user_id: rolf.id)
assert_equal(2, rolfs_interests.length)
assert_equal(minimal_unknown, rolfs_interests.first.target)
assert_equal(false, rolfs_interests.first.state)
assert_equal(peltigera, rolfs_interests.last.target)
assert_equal(false, rolfs_interests.last.state)
# Succeed: Delete interest in existing object that rolf hasn't expressed
# interest in yet.
login("rolf")
get(:set_interest, type: "Observation", id: detailed_unknown.id, state: 0)
assert_flash_success
assert_equal(2, Interest.where(user_id: rolf.id).length)
# Succeed: Delete first interest now.
login("rolf")
get(:set_interest, type: "Observation", id: minimal_unknown.id, state: 0)
assert_flash_success
# Make sure rolf now has one Interest: NOT interested in peltigera.
rolfs_interests = Interest.where(user_id: rolf.id)
assert_equal(1, rolfs_interests.length)
assert_equal(peltigera, rolfs_interests.last.target)
assert_equal(false, rolfs_interests.last.state)
# Succeed: Delete last interest.
login("rolf")
get(:set_interest, type: "Name", id: peltigera.id, state: 0)
assert_flash_success
assert_equal(0, Interest.where(user_id: rolf.id).length)
end
def test_destroy_notification
login("rolf")
n = notifications(:coprinus_comatus_notification)
assert(n)
id = n.id
get(:destroy_notification, id: id)
assert_raises(ActiveRecord::RecordNotFound) do
Notification.find(id)
end
end
end
| 33.626087 | 78 | 0.718386 |
ac91f5d52f25a1997d224ce1167d7fab483c4e2b
| 2,050 |
#!/usr/bin/env ruby
# -------------------------------------------------------------------------- */
# Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs #
# 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. */
# -------------------------------------------------------------------------- */
#
# Simple command to parse an XML document (b64 encoded) and return one or more
# elements (refer by xpath)
#
require 'base64'
require 'rexml/document'
require 'getoptlong'
require 'pp'
opts = opts = GetoptLong.new(
[ '--stdin', '-s', GetoptLong::NO_ARGUMENT ],
[ '--base64', '-b', GetoptLong::REQUIRED_ARGUMENT ]
)
source = :stdin
tmp64 = ""
begin
opts.each do |opt, arg|
case opt
when '--stdin'
source = :stdin
when '--base64'
source = :b64
tmp64 = arg
end
end
rescue Exception => e
exit(-1)
end
values = ""
case source
when :stdin
tmp = STDIN.read
when :b64
tmp = Base64::decode64(tmp64)
end
xml = REXML::Document.new(tmp).root
ARGV.each do |xpath|
element = xml.elements[xpath.dup]
values << element.text.to_s if !element.nil?
values << "\0"
end
puts values
exit 0
| 29.710145 | 79 | 0.498049 |
876ede2fc8e3333e424f46fde3e7140c226daf50
| 1,609 |
# encoding: utf-8
# require 'multi_json'
require 'nimbu-api/utils/json'
module Nimbu
# Raised when Nimbu returns any of the HTTP status codes
module Error
class ServiceError < NimbuError
include ::Nimbu::Utils::Json
attr_reader :http_headers
attr_reader :http_body
attr_reader :status
def initialize(response)
@http_headers = response[:response_headers]
@status = response[:status]
message = parse_response(response)
super(message)
end
def parse_response(response)
body = parse_body(response[:body])
"#{response[:method].to_s.upcase} #{response[:url].to_s}: #{response[:status]} #{body}"
end
def decode_body(body)
if body.respond_to?(:to_str) && body.length >= 2
decode body, :symbolize_keys => true
else
body
end
end
def parse_body(body)
body = decode_body(body)
return '' if body.nil? || body.empty?
if body[:error]
body[:error]
elsif body[:errors]
error = Array(body[:errors]).first
if error.kind_of?(Hash)
error[:message]
else
error
end
elsif body[:message]
body[:message]
else
''
end
end
def self.http_status_code(code)
define_method(:http_status_code) { code }
end
def self.errors
@errors ||= Hash[
descendants.map { |klass| [klass.new({}).http_status_code, klass] }
]
end
end
end # Error
end # Nimbu
| 22.661972 | 95 | 0.564326 |
e26636a444db39ec3300e2e1f7adddee24b5f85a
| 2,482 |
require File.dirname(__FILE__) + '/../../../../config/environment'
require 'test/unit'
require 'test_help'
class IFrameController < ActionController::Base
def normal
render :update do |page|
page.alert "foo"
end
end
def aliased
respond_to_parent do
render :text => 'woot'
end
end
def redirect
responds_to_parent do
redirect_to '/another/place'
end
end
def no_block
responds_to_parent
end
def empty_render
responds_to_parent do
end
render :text => ''
end
def quotes
responds_to_parent do
render :text => %(single' double" qs\\' qd\\" escaped\\\' doubleescaped\\\\')
end
end
def newlines
responds_to_parent do
render :text => "line1\nline2\\nline2"
end
end
def update
responds_to_parent do
render :update do |page|
page.alert 'foo'
page.alert 'bar'
end
end
end
def rescue_action(e)
raise e
end
end
class RespondsToParentTest < Test::Unit::TestCase
def setup
@controller = IFrameController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_normal
get :normal
assert_match /alert\("foo"\)/, @response.body
assert_no_match /window\.parent/, @response.body
end
def test_quotes_should_be_escaped
render :quotes
assert_match %r{eval\('single\\' double\\" qs\\\\\\' qd\\\\\\" escaped\\\\\\' doubleescaped\\\\\\\\\\'}, @response.body
end
def test_newlines_should_be_escaped
render :newlines
assert_match %r{eval\('line1\\nline2\\\\nline2'\)}, @response.body
end
def test_no_block_should_raise
assert_raises LocalJumpError do
get :no_block
end
end
def test_empty_render_should_not_expand_javascript
get :empty_render
assert_equal '', @response.body
end
def test_update_should_perform_combined_rjs
render :update
assert_match /alert\(\\"foo\\"\);\\nalert\(\\"bar\\"\)/, @response.body
end
def test_aliased_method_should_not_raise
assert_nothing_raised do
render :aliased
assert_match /eval\('woot'\)/, @response.body
end
end
protected
def render(action)
get action
assert_match /<script type='text\/javascript'/, @response.body
assert_match /with\(window\.parent\)/, @response.body
assert_match /document\.location\.replace\('about:blank'\)/, @response.body
end
end
| 21.396552 | 123 | 0.656728 |
035a2ffc843a9e8947da86bcd17a73a768bdbec7
| 1,448 |
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "html-pipeline"
s.version = "2.3.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Ryan Tomayko", "Jerry Cheung"]
s.date = "2016-01-20"
s.description = "GitHub HTML processing filters and utilities"
s.email = ["[email protected]", "[email protected]"]
s.homepage = "https://github.com/jch/html-pipeline"
s.licenses = ["MIT"]
s.post_install_message = "-------------------------------------------------\nThank you for installing html-pipeline!\nYou must bundle Filter gem dependencies.\nSee html-pipeline README.md for more details.\nhttps://github.com/jch/html-pipeline#dependencies\n-------------------------------------------------\n"
s.require_paths = ["lib"]
s.rubygems_version = "2.0.14"
s.summary = "Helpers for processing content through a chain of filters"
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<nokogiri>, [">= 1.4"])
s.add_runtime_dependency(%q<activesupport>, ["< 5", ">= 2"])
else
s.add_dependency(%q<nokogiri>, [">= 1.4"])
s.add_dependency(%q<activesupport>, ["< 5", ">= 2"])
end
else
s.add_dependency(%q<nokogiri>, [">= 1.4"])
s.add_dependency(%q<activesupport>, ["< 5", ">= 2"])
end
end
| 42.588235 | 312 | 0.620166 |
1a2ee1e27c1b4f0eff1dc25ca30a57be13334611
| 1,093 |
require 'active_support/core_ext/object' # provides the `try` method
module Draftsman
module Sinatra
# Register this module inside your Sinatra application to gain access to controller-level methods used by Draftsman
def self.registered(app)
app.helpers self
app.before { set_draftsman_whodunnit }
end
protected
# Returns the user who is responsible for any changes that occur.
# By default this calls `current_user` and returns the result.
#
# Override this method in your controller to call a different
# method, e.g. `current_person`, or anything you like.
def user_for_draftsman
return unless defined?(current_user)
ActiveSupport::VERSION::MAJOR >= 4 ? current_user.try!(:id) : current_user.try(:id)
rescue NoMethodError
current_user
end
private
# Tells Draftsman who is responsible for any changes that occur.
def set_draftsman_whodunnit
::Draftsman.whodunnit = user_for_draftsman if ::Draftsman.enabled?
end
end
::Sinatra.register Draftsman::Sinatra if defined?(::Sinatra)
end
| 29.540541 | 119 | 0.721866 |
080ac7f992ff43513a0444611a850a7ab12bc3ee
| 2,843 |
# -*- encoding: utf-8 -*-
# stub: kaminari 1.1.1 ruby lib
Gem::Specification.new do |s|
s.name = "kaminari".freeze
s.version = "1.1.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Akira Matsuda".freeze, "Yuki Nishijima".freeze, "Zachary Scott".freeze, "Hiroshi Shibata".freeze]
s.date = "2017-10-21"
s.description = "Kaminari is a Scope & Engine based, clean, powerful, agnostic, customizable and sophisticated paginator for Rails 4+".freeze
s.email = ["[email protected]".freeze]
s.homepage = "https://github.com/kaminari/kaminari".freeze
s.licenses = ["MIT".freeze]
s.required_ruby_version = Gem::Requirement.new(">= 2.0.0".freeze)
s.rubygems_version = "2.6.14.1".freeze
s.summary = "A pagination engine plugin for Rails 4+ and other modern frameworks".freeze
s.installed_by_version = "2.6.14.1" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<activesupport>.freeze, [">= 4.1.0"])
s.add_runtime_dependency(%q<kaminari-core>.freeze, ["= 1.1.1"])
s.add_runtime_dependency(%q<kaminari-actionview>.freeze, ["= 1.1.1"])
s.add_runtime_dependency(%q<kaminari-activerecord>.freeze, ["= 1.1.1"])
s.add_development_dependency(%q<test-unit-rails>.freeze, [">= 0"])
s.add_development_dependency(%q<bundler>.freeze, [">= 1.0.0"])
s.add_development_dependency(%q<rake>.freeze, [">= 0"])
s.add_development_dependency(%q<rr>.freeze, [">= 0"])
s.add_development_dependency(%q<capybara>.freeze, [">= 1.0"])
else
s.add_dependency(%q<activesupport>.freeze, [">= 4.1.0"])
s.add_dependency(%q<kaminari-core>.freeze, ["= 1.1.1"])
s.add_dependency(%q<kaminari-actionview>.freeze, ["= 1.1.1"])
s.add_dependency(%q<kaminari-activerecord>.freeze, ["= 1.1.1"])
s.add_dependency(%q<test-unit-rails>.freeze, [">= 0"])
s.add_dependency(%q<bundler>.freeze, [">= 1.0.0"])
s.add_dependency(%q<rake>.freeze, [">= 0"])
s.add_dependency(%q<rr>.freeze, [">= 0"])
s.add_dependency(%q<capybara>.freeze, [">= 1.0"])
end
else
s.add_dependency(%q<activesupport>.freeze, [">= 4.1.0"])
s.add_dependency(%q<kaminari-core>.freeze, ["= 1.1.1"])
s.add_dependency(%q<kaminari-actionview>.freeze, ["= 1.1.1"])
s.add_dependency(%q<kaminari-activerecord>.freeze, ["= 1.1.1"])
s.add_dependency(%q<test-unit-rails>.freeze, [">= 0"])
s.add_dependency(%q<bundler>.freeze, [">= 1.0.0"])
s.add_dependency(%q<rake>.freeze, [">= 0"])
s.add_dependency(%q<rr>.freeze, [">= 0"])
s.add_dependency(%q<capybara>.freeze, [">= 1.0"])
end
end
| 49.017241 | 143 | 0.652832 |
ab6f5089496d4222a1f74cce2be486f9a30ab05f
| 1,215 |
class Yank < Formula
desc "Copy terminal output to clipboard"
homepage "https://github.com/mptre/yank"
url "https://github.com/mptre/yank/archive/v1.2.0.tar.gz"
sha256 "c4a2f854f9e49e1df61491d3fab29ea595c7e3307394acb15f32b6d415840bce"
license "MIT"
bottle do
cellar :any_skip_relocation
sha256 "ef4da54ce9a56a1767b44dd88df6616c147730d74f390d5a661910dddf8785a7" => :catalina
sha256 "60431f02c576c640597975986ce62f9d157c49f160d7d6e23f917dc321ca8bac" => :mojave
sha256 "b87461e809f0bebd615d4da69c31509109de8f86d07d280dab07326293cc851f" => :high_sierra
sha256 "70a5de45249c1656653733fea8d7a92c2496b9ba8e7540eef86b3f805d0e933a" => :sierra
sha256 "a603aadd7c40a0b0be7c66b99fff6c837acdef9aac38a4628618a98ca2efc5e5" => :x86_64_linux
end
def install
system "make", "install", "PREFIX=#{prefix}", "YANKCMD=pbcopy"
end
test do
(testpath/"test.exp").write <<~EOS
spawn sh
set timeout 1
send "echo key=value | #{bin}/yank -d = | cat"
send "\r"
send "\016"
send "\r"
expect {
"value" { send "exit\r"; exit 0 }
timeout { send "exit\r"; exit 1 }
}
EOS
system "expect", "-f", "test.exp"
end
end
| 32.837838 | 94 | 0.701235 |
bf30f13c1a369399feb48a6e7a8d5fee9436934c
| 350 |
# encoding: UTF-8
module Simultaneous
module Command
class TaskComplete < CommandBase
def initialize(task_name)
@task_name = task_name
end
def run
Simultaneous::Server.task_complete(namespaced_task_name)
end
def debug
"TaskComplete :#{namespaced_task_name}\n"
end
end
end
end
| 18.421053 | 64 | 0.648571 |
d5eed0cdaf9e635df1e2516b8974287fedb44788
| 183 |
def count_primes(n)
return 0 if n<2
arr=Array.new(n,1)
2.upto(n) do |i|
j=i*i
break if j>=n
while j<n
arr[j]=0
j+=i
end
end
arr.inject(:+)-2
end
| 13.071429 | 20 | 0.513661 |
4a8c196cda3ee4714e61962bb644ab1ba0dd8960
| 1,094 |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe GraphqlDevise::MountMethod::OperationPreparer do
describe '#call' do
subject(:prepared_operations) do
described_class.new(
model: model,
selected_operations: selected,
preparer: preparer,
custom: custom,
additional_operations: additional
).call
end
let(:logout_class) { Class.new(GraphQL::Schema::Resolver) }
let(:model) { User }
let(:preparer) { double(:preparer, call: logout_class) }
let(:custom) { { login: double(:custom_login, graphql_name: nil) } }
let(:additional) { { user_additional: double(:user_additional) } }
let(:selected) do
{
login: { klass: double(:login_default) },
logout: { klass: logout_class }
}
end
it 'is expected to return all provided operation keys' do
expect(prepared_operations.keys).to contain_exactly(
:user_login,
:user_logout,
:user_additional
)
end
end
end
| 28.789474 | 78 | 0.604205 |
39234ed61aa815ad8fa3fde4c14e514900a9b81f
| 1,715 |
require 'net/http'
require 'json'
helpers do
def read_joke(category)
# Joke.order("RANDOM()").first.joke # is slow
# Joke.offset(rand(Joke.count)).first.joke # is better/faster
# Joke.where('categories LIKE ?', '%' + "#{category}" + '%').order("random()").first.joke
Joke.where('categories LIKE ?', '%' + "#{category}" + '%').offset(rand(Joke.where('categories LIKE ?', '%' + "#{category}" + '%').count)).first.joke
end
def clean_joke(string)
string.gsub(""", "'")
end
def fetch_joke
uri = URI(@url)
response = Net::HTTP.get_response(uri)
if response.code == "200"
joke = JSON.parse(response.body)['value']['joke']
p joke
return clean_joke(joke)
else
clean_joke(read_joke(params[:Body]))
end
end
def fetch_dad_joke
uri = URI(@url)
req = Net::HTTP::Get.new(uri)
req['accept'] = 'text/plain'
req['user-agent'] = 'github.com/justincadburywong/chucknorrisidb'
response = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) {|http|
http.request(req)
}
if response.code == "200"
p response.body
return response.body
end
end
# As a contingency to back up all of the jokes
def save_joke(response)
if !Joke.find_by(joke: response['joke'])
Joke.create(joke: response['value']['joke'], categories: response['value']['categories'])
end
end
def scrape_api
counter = 1
100.times do
@url = "http://api.icndb.com/jokes/#{counter}"
uri = URI(@url)
response = Net::HTTP.get_response(uri)
if JSON.parse(response.body)['type'] == "success"
save_joke(JSON.parse(response.body))
end
counter +=1
end
end
end
| 26.796875 | 152 | 0.610496 |
e9f157ea41a920385a5f7d3d89c2d77a015252d2
| 7,854 |
require_relative "./test_helper"
class BootstrapOtherComponentsTest < ActionView::TestCase
include BootstrapForm::Helper
setup :setup_test_fixture
test "static control" do
output = @horizontal_builder.static_control :email
expected = <<-HTML.strip_heredoc
<div class="form-group form-row">
<label class="col-form-label col-sm-2 required" for="user_email">Email</label>
<div class="col-sm-10">
<input class="form-control-plaintext" id="user_email" name="user[email]" readonly="readonly" type="text" value="[email protected]"/>
</div>
</div>
HTML
assert_equivalent_xml expected, output
end
test "static control can have custom_id" do
output = @horizontal_builder.static_control :email, id: "custom_id"
expected = <<-HTML.strip_heredoc
<div class="form-group form-row">
<label class="col-form-label col-sm-2 required" for="custom_id">Email</label>
<div class="col-sm-10">
<input class="form-control-plaintext" id="custom_id" name="user[email]" readonly="readonly" type="text" value="[email protected]"/>
</div>
</div>
HTML
assert_equivalent_xml expected, output
end
test "static control doesn't require an actual attribute" do
output = @horizontal_builder.static_control nil, label: "My Label", value: "this is a test"
expected = <<-HTML.strip_heredoc
<div class="form-group form-row">
<label class="col-form-label col-sm-2" for="user_">My Label</label>
<div class="col-sm-10">
<input class="form-control-plaintext" id="user_" name="user[]" readonly="readonly" type="text" value="this is a test"/>
</div>
</div>
HTML
assert_equivalent_xml expected, output
end
test "static control doesn't require a name" do
output = @horizontal_builder.static_control label: "Custom Label", value: "Custom Control"
expected = <<-HTML.strip_heredoc
<div class="form-group form-row">
<label class="col-form-label col-sm-2" for="user_">Custom Label</label>
<div class="col-sm-10">
<input class="form-control-plaintext" id="user_" name="user[]" readonly="readonly" type="text" value="Custom Control"/>
</div>
</div>
HTML
assert_equivalent_xml expected, output
end
test "static control support a nil value" do
output = @horizontal_builder.static_control label: "Custom Label", value: nil
expected = <<-HTML.strip_heredoc
<div class="form-group form-row">
<label class="col-form-label col-sm-2" for="user_">Custom Label</label>
<div class="col-sm-10">
<input class="form-control-plaintext" id="user_" name="user[]" readonly="readonly" type="text"/>
</div>
</div>
HTML
assert_equivalent_xml expected, output
end
test "static control won't overwrite a control_class that is passed by the user" do
output = @horizontal_builder.static_control :email, control_class: "test_class"
expected = <<-HTML.strip_heredoc
<div class="form-group form-row">
<label class="col-form-label col-sm-2 required" for="user_email">Email</label>
<div class="col-sm-10">
<input class="test_class form-control-plaintext" id="user_email" name="user[email]" readonly="readonly" type="text" value="[email protected]"/>
</div>
</div>
HTML
assert_equivalent_xml expected, output
end
test "custom control does't wrap given block in a p tag" do
output = @horizontal_builder.custom_control :email do
"this is a test"
end
expected = <<-HTML.strip_heredoc
<div class="form-group form-row">
<label class="col-form-label col-sm-2 required" for="user_email">Email</label>
<div class="col-sm-10">this is a test</div>
</div>
HTML
assert_equivalent_xml expected, output
end
test "custom control doesn't require an actual attribute" do
output = @horizontal_builder.custom_control nil, label: "My Label" do
"this is a test"
end
expected = <<-HTML.strip_heredoc
<div class="form-group form-row">
<label class="col-form-label col-sm-2" for="user_">My Label</label>
<div class="col-sm-10">this is a test</div>
</div>
HTML
assert_equivalent_xml expected, output
end
test "custom control doesn't require a name" do
output = @horizontal_builder.custom_control label: "Custom Label" do
"Custom Control"
end
expected = <<-HTML.strip_heredoc
<div class="form-group form-row">
<label class="col-form-label col-sm-2" for="user_">Custom Label</label>
<div class="col-sm-10">Custom Control</div>
</div>
HTML
assert_equivalent_xml expected, output
end
test "regular button uses proper css classes" do
expected = %q(<button class="btn btn-secondary" name="button" type="submit"><span>I'm HTML!</span> in a button!</button>)
assert_equivalent_xml expected,
@builder.button("<span>I'm HTML!</span> in a button!".html_safe)
end
test "regular button can have extra css classes" do
expected = %q(<button class="btn btn-secondary test-button" name="button" type="submit"><span>I'm HTML!</span> in a button!</button>)
assert_equivalent_xml expected,
@builder.button("<span>I'm HTML!</span> in a button!".html_safe, extra_class: "test-button")
end
test "submit button defaults to rails action name" do
expected = '<input class="btn btn-secondary" name="commit" type="submit" value="Create User" />'
assert_equivalent_xml expected, @builder.submit
end
test "submit button uses default button classes" do
expected = '<input class="btn btn-secondary" name="commit" type="submit" value="Submit Form" />'
assert_equivalent_xml expected, @builder.submit("Submit Form")
end
test "submit button can have extra css classes" do
expected = '<input class="btn btn-secondary test-button" name="commit" type="submit" value="Submit Form" />'
assert_equivalent_xml expected, @builder.submit("Submit Form", extra_class: "test-button")
end
test "override submit button classes" do
expected = '<input class="btn btn-primary" name="commit" type="submit" value="Submit Form" />'
assert_equivalent_xml expected, @builder.submit("Submit Form", class: "btn btn-primary")
end
test "primary button uses proper css classes" do
expected = '<input class="btn btn-primary" name="commit" type="submit" value="Submit Form" />'
assert_equivalent_xml expected, @builder.primary("Submit Form")
end
test "primary button can have extra css classes" do
expected = '<input class="btn btn-primary test-button" name="commit" type="submit" value="Submit Form" />'
assert_equivalent_xml expected, @builder.primary("Submit Form", extra_class: "test-button")
end
test "primary button can render as HTML button" do
expected = %q(<button class="btn btn-primary" name="button" type="submit"><span>I'm HTML!</span> Submit Form</button>)
assert_equivalent_xml expected,
@builder.primary("<span>I'm HTML!</span> Submit Form".html_safe,
render_as_button: true)
end
test "primary button with content block renders as HTML button" do
output = @builder.primary do
"<span>I'm HTML!</span> Submit Form".html_safe
end
expected = %q(<button class="btn btn-primary" name="button" type="submit"><span>I'm HTML!</span> Submit Form</button>)
assert_equivalent_xml expected, output
end
test "override primary button classes" do
expected = '<input class="btn btn-primary disabled" name="commit" type="submit" value="Submit Form" />'
assert_equivalent_xml expected, @builder.primary("Submit Form", class: "btn btn-primary disabled")
end
end
| 40.071429 | 153 | 0.670486 |
01652dfe0d6a93cf7f986084ed2528e50604d4d1
| 987 |
cask 'folx' do
version '5.1.13671'
sha256 '45535464ba360fb7625bd6eb6736ba68ef7daed37833ef62c8170b16d511dd97'
url "http://www.eltima.com/download/folx-update/downloader_mac_#{version}.dmg"
appcast 'http://mac.eltima.com/download/folx-updater/folx.xml',
checkpoint: 'de10550065e2316573a16d23e031b6f4dd59ea655033922216ac8ab4910b0c5e'
name 'Folx'
homepage 'http://mac.eltima.com/download-manager.html'
auto_updates true
app 'Folx.app'
zap delete: [
'~/Library/Application Support/Eltima Software/Folx3',
'~/Library/Caches/com.eltima.Folx3',
'~/Library/Internet Plug-Ins/Folx3Plugin.plugin',
'~/Library/Logs/Folx.log',
'~/Library/Logs/Folx3.log',
'~/Library/Preferences/com.eltima.Folx3.plist',
'~/Library/Preferences/com.eltima.FolxAgent.plist',
'~/Library/Saved Application State/com.eltima.Folx3.savedState',
]
end
| 37.961538 | 88 | 0.653495 |
185635af1e70b6f4c3761e165c517fb20ca2d977
| 4,025 |
# frozen_string_literal: true
# = Checklist
#
# This class calculates a checklist of species observed by users,
# projects, etc.
#
# == Methods
#
# num_genera:: Number of genera seen.
# num_species:: Number of species seen.
# genera:: List of genera (text_name) seen.
# species:: List of species (text_name) seen.
#
# == Usage
#
# data = Checklist::ForUser.new(user)
# puts "Life List: #{data.num_species} species in #{data.num_genera} genera."
#
################################################################################
class Checklist
# Build list of species observed by entire site.
class ForSite < Checklist
end
# Build list of species observed by one User.
class ForUser < Checklist
def initialize(user)
return (@user = user) if user.is_a?(User)
raise "Expected User instance, got #{user.inspect}."
end
def query
super(
conditions: ["o.user_id = #{@user.id}"]
)
end
end
# Build list of species observed by one Project.
class ForProject < Checklist
def initialize(project)
return (@project = project) if project.is_a?(Project)
raise "Expected Project instance, got #{project.inspect}."
end
def query
super(
tables: ["observations_projects op"],
conditions: ["op.observation_id = o.id",
"op.project_id = #{@project.id}"]
)
end
end
# Build list of species observed by one SpeciesList.
class ForSpeciesList < Checklist
def initialize(list)
return (@list = list) if list.is_a?(SpeciesList)
raise "Expected SpeciesList instance, got #{list.inspect}."
end
def query
super(
tables: ["observations_species_lists os"],
conditions: ["os.observation_id = o.id",
"os.species_list_id = #{@list.id}"]
)
end
end
##############################################################################
def initialize
@genera = @species = nil
end
def num_genera
calc_checklist unless @genera
@genera.length
end
def num_species
calc_checklist unless @species
@species.length
end
def genera
calc_checklist unless @genera
@genera.values.sort
end
def species
calc_checklist unless @species
@species.values.sort
end
private
def calc_checklist
@genera = {}
@species = {}
synonyms = count_nonsynonyms_and_gather_synonyms
count_synonyms(synonyms)
end
def count_nonsynonyms_and_gather_synonyms
synonyms = {}
Name.connection.select_rows(query).each do |text_name, syn_id, deprecated|
if syn_id && deprecated == 1
# wait until we find an accepted synonym
text_name = synonyms[syn_id] ||= nil
elsif syn_id
# use the first accepted synonym we encounter
text_name = synonyms[syn_id] ||= text_name
else
# count non-synonyms immediately
count_species(text_name)
end
end
synonyms
end
def count_synonyms(synonyms)
synonyms.each do |syn_id, text_name|
text_name ||= Name.connection.select_values(%(
SELECT text_name FROM names
WHERE synonym_id = #{syn_id}
AND rank IN (#{ranks_to_consider})
ORDER BY deprecated ASC
)).first
count_species(text_name)
end
end
def count_species(text_name)
if text_name.present?
g, s = text_name.split(" ", 3)
@genera[g] = g
@species[[g, s]] = "#{g} #{s}"
end
end
def ranks_to_consider
Name.ranks.values_at(:Species, :Subspecies, :Variety, :Form).join(", ")
end
def query(args = {})
tables = [
"names n",
"observations o"
]
conditions = [
"n.id = o.name_id",
"n.rank IN (#{ranks_to_consider})"
]
tables += args[:tables] || []
conditions += args[:conditions] || []
%(
SELECT n.text_name, n.synonym_id, n.deprecated
FROM #{tables.join(", ")}
WHERE (#{conditions.join(") AND (")})
)
end
end
| 23.676471 | 80 | 0.594286 |
1cc3f49bee9efb94d7fb8a100a078c7015239a64
| 1,701 |
# (c) Copyright 2006-2007 Nick Sieger <[email protected]>
# See the file LICENSE.txt included with the distribution for
# software license details.
require File.dirname(__FILE__) + "/../../spec_helper.rb"
require 'rexml/document'
describe "Output capture" do
before(:each) do
@suite = CI::Reporter::TestSuite.new "test"
end
it "should save stdout and stderr messages written during the test run" do
@suite.start
puts "Hello"
$stderr.print "Hi"
@suite.finish
@suite.stdout.should == "Hello\n"
@suite.stderr.should == "Hi"
end
it "should include system-out and system-err elements in the xml output" do
@suite.start
puts "Hello"
$stderr.print "Hi"
@suite.finish
root = REXML::Document.new(@suite.to_xml).root
root.elements.to_a('//system-out').length.should == 1
root.elements.to_a('//system-err').length.should == 1
root.elements.to_a('//system-out').first.cdatas.first.to_s.should == "Hello\n"
root.elements.to_a('//system-err').first.cdatas.first.to_s.should == "Hi"
end
it "should return $stdout and $stderr to original value after finish" do
out, err = $stdout, $stderr
@suite.start
$stdout.object_id.should_not == out.object_id
$stderr.object_id.should_not == err.object_id
@suite.finish
$stdout.object_id.should == out.object_id
$stderr.object_id.should == err.object_id
end
it "should capture only during run of owner test suite" do
$stdout.print "A"
$stderr.print "A"
@suite.start
$stdout.print "B"
$stderr.print "B"
@suite.finish
$stdout.print "C"
$stderr.print "C"
@suite.stdout.should == "B"
@suite.stderr.should == "B"
end
end
| 29.842105 | 82 | 0.670782 |
5db77c19f9a68e7f5d2fc8e6ecf04111d7641982
| 32 |
name 'patching'
version '0.1.0'
| 10.666667 | 15 | 0.6875 |
913395001b0f5c34558f9d8ccd805b320b5f5c27
| 267 |
class User < ApplicationRecord
has_many :completed_words
has_many :sight_words, through: :completed_words
has_secure_password
validates :username, uniqueness: true
def completion_update
self.update(completion_status: self.completed_words.count)
end
end
| 16.6875 | 60 | 0.812734 |
79dcd5f77bdce20114223bfaa9f86a3534e18f1d
| 1,690 |
class Libgphoto2 < Formula
desc "Gphoto2 digital camera library"
homepage "http://www.gphoto.org/proj/libgphoto2/"
url "https://downloads.sourceforge.net/project/gphoto/libgphoto/2.5.23/libgphoto2-2.5.23.tar.bz2"
sha256 "d8af23364aa40fd8607f7e073df74e7ace05582f4ba13f1724d12d3c97e8852d"
bottle do
sha256 "d5e55b07bcb538aed536da66d79c6366a58e0e106b5835846cf5d8bd06aa02b7" => :catalina
sha256 "b758f4caa384721d7593bec1314dd9e05fa05f69a74e7edd702dc3e9fabb4377" => :mojave
sha256 "efb624c0e1495dce73b72b24868a5fab80836aa162b37951c2ad04eba093b5c5" => :high_sierra
sha256 "21dc9f114533994fbeedd7893a8c40b2ec42f2a46bd14d2c40d463e397e9c69b" => :sierra
sha256 "3dceac74ce0ab8c74a2aa200547fc614f5ded947332e4ad6586651211f1de42a" => :x86_64_linux
end
head do
url "https://github.com/gphoto/libgphoto2.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "gettext" => :build
end
depends_on "pkg-config" => :build
depends_on "gd"
depends_on "libtool"
depends_on "libusb-compat"
def install
system "autoreconf", "-fvi" if build.head?
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <gphoto2/gphoto2-camera.h>
int main(void) {
Camera *camera;
return gp_camera_new(&camera);
}
EOS
system ENV.cc, "test.c",
*("-I#{include}" unless OS.mac?),
*("-Wl,-rpath,#{lib}" unless OS.mac?),
"-L#{lib}", "-lgphoto2", "-o", "test"
system "./test"
end
end
| 33.137255 | 99 | 0.683432 |
7ab0c95dcf0abd2512cf4b2e3fb28e99cee133c0
| 548 |
namespace :feedbin do
desc "run db:reset, flush redis and restart pow"
task :reset do
FileUtils.mkdir_p(File.join(Rails.root, 'tmp'))
restart_file = File.join(Rails.root, 'tmp', 'restart.txt')
Kernel.system "touch #{restart_file}"
Kernel.system "rake --trace db:drop"
Kernel.system "rake --trace db:reset"
Kernel.system "redis-cli 'flushdb'"
Kernel.system "redis-cli -n 2 'flushdb'"
Kernel.system "echo 'flush_all' | nc localhost 11211"
Kernel.system "curl -XDELETE 'http://127.0.0.1:9200/_all/'"
end
end
| 36.533333 | 63 | 0.678832 |
1d261f27ddf6cf4c1eb0e707fdb25300aa822744
| 1,202 |
class Kubectx < Formula
desc "Tool that can switch between kubectl contexts easily and create aliases"
homepage "https://github.com/ahmetb/kubectx"
url "https://github.com/ahmetb/kubectx/archive/v0.4.1.tar.gz"
sha256 "bdde688a6382c7e0e23fdecb204cb48ce8204cad213fdaf45c0fb5d929f76937"
head "https://github.com/ahmetb/kubectx.git"
bottle :unneeded
option "with-short-names", "link as \"kctx\" and \"kns\" instead"
depends_on "kubernetes-cli" => :recommended
def install
bin.install "kubectx" => build.with?("short-names") ? "kctx" : "kubectx"
bin.install "kubens" => build.with?("short-names") ? "kns" : "kubens"
bash_completion.install "completion/kubectx.bash" => "kubectx"
bash_completion.install "completion/kubens.bash" => "kubens"
zsh_completion.install "completion/kubectx.zsh" => "_kubectx"
zsh_completion.install "completion/kubens.zsh" => "_kubens"
fish_completion.install "completion/kubectx.fish" => "_kubectx"
fish_completion.install "completion/kubens.fish" => "_kubens"
end
test do
assert_match "USAGE:", shell_output("#{bin}/kubectx -h 2>&1", 1)
assert_match "USAGE:", shell_output("#{bin}/kubens -h 2>&1", 1)
end
end
| 38.774194 | 80 | 0.711314 |
877cea76b7f12a78b0d88ce9198652a64bcf70f3
| 558 |
module DbpediaGemExtension
attr_accessor :refcount
def parse
self.refcount = read '> Refcount'
super
end
end
module Dbpedia
class SearchResult < Dbpedia::Parser
prepend DbpediaGemExtension
end
end
module DbpediaGemClientExtenstion
def initialize
super
if !DBPEDIA_LOOKUP_URL.nil?
search = {
'keyword' => DBPEDIA_LOOKUP_URL + '/KeywordSearch',
'prefix' => DBPEDIA_LOOKUP_URL + '/PrefixSearch'
}
@uris = {'search' => search}
end
@uris
end
end
module Dbpedia
class Client
prepend DbpediaGemClientExtenstion
end
end
| 16.411765 | 56 | 0.732975 |
b9fcbdd475db9d2168f027d2f952212ca5f731aa
| 6,432 |
#!/usr/bin/env ruby
$config_template = <<-CONFIG_TEMPLATE
eclair.chain=#CHAIN#
eclair.node-alias=#ALIAS#
eclair.enable-db-backup=false
eclair.server.public-ips.1=127.0.0.1
eclair.server.port=#PORT#
eclair.api.enabled=true
eclair.api.password=bar
eclair.api.port=#API_PORT#
eclair.bitcoind.port=18444
eclair.bitcoind.rpcport=18443
eclair.bitcoind.zmqblock="tcp://127.0.0.1:29000"
eclair.bitcoind.zmqtx="tcp://127.0.0.1:29001"
eclair.mindepth-blocks=1
eclair.max-htlc-value-in-flight-msat=100000000000
eclair.router.broadcast-interval=2 seconds
eclair.to-remote-delay-blocks=24
eclair.multi-part-payment-expiry=20 seconds
eclair.features.basic_mpp=disabled
eclair.features.option_data_loss_protect=optional
eclair.features.initial_routing_sync=optional
eclair.features.gossip_queries=optional
eclair.features.gossip_queries_ex=optional
eclair.features.var_onion_optin=optional
eclair.features.ptlc=optional
CONFIG_TEMPLATE
def print_help
puts "#{$0} (init|start|stop) [options]"
puts "\tinit\tInitialize the network setup"
puts "\tstart\tStart the network"
puts "\tstop\tstop the network"
exit
end
def print_init_help
puts "usage: #{$0} init [options]"
puts "\t--num-nodes=<2-26>\t\t\tNumber of nodes (default 3) "
puts "\t--eclair-zip=<path>\t\t\tPath to Eclair distribution zip file"
puts "\t--work-dir=<path>\t\t\tPath to the work directory"
puts "\t--chain=<regtest|testnet|mainnet>\tBitcoin chain"
exit
end
def print_start_help
puts "usage: #{$0} start [options]"
puts "\t--work-dir=<path>\t\t\tPath to the work directory"
exit
end
def print_stop_help
puts "usage: #{$0} stop [options]"
puts "\t--work-dir=<path>\t\t\tPath to the work directory"
exit
end
def process_argv_option(option, options, print_help)
opt = option.split("=")
case opt.first
when "-h"
print_help
when "--help"
print_help
when "--num-nodes"
self.send(print_help) if opt.size != 2
options[:num_nodes] = opt.last.to_i
self.send(print_help) if options[:num_nodes] < 2
when "--chain"
options[:chain] = true
self.send(print_help) if opt.size != 2
chain = opt.last
self.send(print_help) unless ["regtest", "testnet", "mainnet"].include?(chain)
options[:chain] = chain
when "--eclair-zip"
self.send(print_help) if opt.size != 2
options[:eclair_zip] = opt.last
when "--work-dir"
self.send(print_help) if opt.size != 2
options[:work_dir] = opt.last
end
end
def find_eclair_zip
dirs = [".", "eclair-node/target", "../eclair-node/target"]
dirs.each do |top_dir|
files = Dir.glob("#{top_dir}/eclair-node-*-bin.zip")
return files.first if not files.empty?
end
nil
end
def process_init_argv(argv)
options = {}
argv.each { |option| process_argv_option(option, options, :print_init_help) }
options[:num_nodes] = 3 if options[:num_nodes].nil?
options[:chain] = "regtest" if options[:chain].nil?
options[:work_dir] = "." if options[:work_dir].nil?
if options[:eclair_zip].nil?
zip = find_eclair_zip
unless zip.nil?
options[:eclair_zip] = zip
else
puts "Use --eclair-zip to specify path to Eclair distribution zip file"
exit
end
end
options
end
def process_argv(argv, print_help)
options = {}
argv.each { |option| process_argv_option(option, options, print_help) }
options[:work_dir] = "." if options[:work_dir].nil?
options
end
def process_start_argv(argv)
process_argv(argv, :print_start_help)
end
def process_stop_argv(argv)
process_argv(argv, :print_stop_help)
end
def get_launch_script(args)
script = Dir.glob("#{args[:work_dir]}/eclair-node-*/bin/eclair-node.sh").first
if script.nil?
puts "Cannot find eclair launch script"
exit
end
script
end
def get_cli_script(args)
script = Dir.glob("#{args[:work_dir]}/eclair-node-*/bin/eclair-cli").first
if script.nil?
puts "Cannot find eclair CLI script"
exit
end
File.absolute_path(script)
end
def init(args)
puts "Unzipping #{args[:eclair_zip]}"
unless system("unzip #{args[:eclair_zip]} > /dev/null")
puts "Cannot unzip #{args[:eclair_zip]}: error code #{$?}"
exit
end
bin_dir = args[:work_dir]
Dir.mkdir(bin_dir) unless Dir.exist?(bin_dir)
cli_script = get_cli_script(args)
nodes_root_dir = "#{args[:work_dir]}/nodes"
Dir.mkdir(nodes_root_dir) unless Dir.exist?(nodes_root_dir)
node_dirs = (0..(args[:num_nodes] - 1)).map { |i| "#{nodes_root_dir}/#{(65 + i).chr}" }
node_dirs.each { |dir| Dir.mkdir(dir) unless Dir.exist?(dir) }
node_dirs.zip((0..(args[:num_nodes] - 1)).map { |i| i}).each do |dir, i|
node_alias = dir.split("/").last
port = 9835 + i
api_port = 8800 + i
conf = $config_template
.sub('#CHAIN#', args[:chain])
.sub('#ALIAS#', node_alias)
.sub('#PORT#', port.to_s)
.sub('#API_PORT#', api_port.to_s)
File.open("#{dir}/eclair.conf", 'w') do |file|
file.write(conf)
end
cli = "#{bin_dir}/eclair-cli-#{(97 + i).chr}"
f = File.new(cli, "w");
f.chmod(0755)
File.open(cli, 'w') do |file|
file.write('#!/bin/bash' +
"\n\n#{cli_script} -p bar -a 127.0.0.1:#{api_port} $1 $2 $3 $4 $5 $6 $7 $8 $9")
end
end
end
def pid_file(args)
"#{args[:work_dir]}/nodes/pids"
end
def start(args)
script = get_launch_script(args)
node_dirs = Dir.glob("#{args[:work_dir]}/nodes/*")
pids = []
node_dirs.each do |dir|
unless dir.end_with?("pids")
ENV['DISABLE_SECP256K1'] = 'true'
cmd = "#{script} -Declair.datadir=#{dir}"
puts "Starting #{cmd}"
pid = fork { exec(cmd) }
pids << pid
end
end
File.open(pid_file(args), 'w') do |file|
pids.each { |pid| file.write("#{pid}\n") }
end
end
def stop(args)
pids = []
if File.exist?(pid_file(args))
IO.readlines(pid_file(args)).each do |line|
pids << line.chomp.to_i
end
pids.each do |pid|
puts "Stopping process #{pid}"
Process.kill("HUP", pid)
end
File.delete(pid_file(args))
end
end
command, *argv = ARGV
case command
when "init"
args = process_init_argv(argv)
init(args)
when "start"
args = process_start_argv(argv)
start(args)
when "stop"
args = process_stop_argv(argv)
stop(args)
else
print_help
end
| 25.831325 | 89 | 0.651119 |
ed53b976ac08c67100318a2579dd48c1536e41c1
| 1,784 |
################################################################################
# (C) Copyright 2016-2017 Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
require 'spec_helper'
type_class = Puppet::Type.type(:oneview_logical_switch)
def lsg_config
{
name: 'Logical Switch',
ensure: 'present',
data:
{
'name' => 'Logical Switch',
'logicalSwitchGroupUri' => '1'
}
}
end
describe type_class, integration: true do
let(:params) { %i[name data provider] }
it 'should have expected parameters' do
params.each do |param|
expect(type_class.parameters).to be_include(param)
end
end
it 'should require a name' do
expect do
type_class.new({})
end.to raise_error(Puppet::Error, 'Title or name must be provided')
end
it 'should require a data hash' do
modified_config = lsg_config
modified_config[:data] = ''
expect do
type_class.new(modified_config)
end.to raise_error('Parameter data failed on Oneview_logical_switch[Logical Switch]: Validate method failed for class data: Inserted '\
'value for data is not valid')
end
end
| 31.298246 | 139 | 0.631726 |
9129623789636b7ecd6bfc84596c27c67526b0e8
| 1,498 |
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Cosmosdb::Mgmt::V2019_12_12
module Models
#
# Cosmos DB SQL userDefinedFunction resource object
#
class SqlUserDefinedFunctionResource
include MsRestAzure
# @return [String] Name of the Cosmos DB SQL userDefinedFunction
attr_accessor :id
# @return [String] Body of the User Defined Function
attr_accessor :body
#
# Mapper for SqlUserDefinedFunctionResource class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'SqlUserDefinedFunctionResource',
type: {
name: 'Composite',
class_name: 'SqlUserDefinedFunctionResource',
model_properties: {
id: {
client_side_validation: true,
required: true,
serialized_name: 'id',
type: {
name: 'String'
}
},
body: {
client_side_validation: true,
required: false,
serialized_name: 'body',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 26.280702 | 70 | 0.538718 |
6a906f237f18c5d24e1ccb23b773c535afe80489
| 118 |
class AddQuantity < ActiveRecord::Migration[5.1]
def change
add_column :products, :quantity, :integer
end
end
| 19.666667 | 48 | 0.737288 |
621314d2ce7db070a0051b40b0ea97183f41ace8
| 537 |
require 'rails_helper'
describe SolrDocument do
let(:solr_doc) { SolrDocument.new(attributes) }
describe "on_campus?" do
subject { solr_doc.on_campus? }
context "when restricted to on campus" do
let(:attributes) { { Hydra.config.permissions.read.group => [OnCampusAccess::OnCampus] } }
it { is_expected.to be true }
end
context "when not restricted to on campus" do
let(:attributes) { { Hydra.config.permissions.read.group => ['public'] } }
it { is_expected.to be false }
end
end
end
| 28.263158 | 96 | 0.670391 |
ac78a6da89a17911d03939789169a5f4cf6914dc
| 2,602 |
# coding: utf-8
require "object_pascal_analyzer"
require 'nkf'
require "object_pascal_analyzer/pascal_file"
module ObjectPascalAnalyzer
class PascalFileLoader
attr_reader :path
attr_reader :pascal_file
def initialize(path, name)
@path = path
@pascal_file = PascalFile.new(name)
@function_stack = []
@current = nil
end
IMPLEMENTATION_PATTERN = /\s*implementation/i
def execute
found_implementation = false
source_text = read_file(path)
source_text.lines.each do |line|
if found_implementation
process(line)
else
if IMPLEMENTATION_PATTERN =~ line
found_implementation = true
end
end
end
pascal_file
end
def read_file(path)
# https://docs.ruby-lang.org/ja/2.3.0/class/NKF.html
encode = NKF.guess(File.read(path))
# https://docs.ruby-lang.org/ja/2.3.0/method/IO/s/read.html
# https://docs.ruby-lang.org/ja/latest/method/Kernel/m/open.html
File.read(path, mode: "r:utf-8:#{encode.to_s}")
rescue EncodingError
# 変換不可能な不正な文字コードを含んでいる場合、それらを空白文字に置換した文字列を返します
File.read(path).encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "")
end
# Object pascal の識別子
# http://docs.embarcadero.com/products/rad_studio/cbuilder6/JA/oplg.pdf
# http://wiki.freepascal.org/Identifiers/ja
FUNCTION_PATTERN = /\s*(?:function|procedure)\s+([\w\.]+)/i
METHOD_PATTERN = /\A(\w+)\.(\w+)\z/i
EMPTY_PATTERN = /\A\s*\n\z/
COMMENT_PATTERN = /\A\s*\/\/.*\n\z/
def process(line)
case line
when EMPTY_PATTERN then @current.empty_line if @current
when COMMENT_PATTERN then @current.comment_line if @current
else
func = line.scan(FUNCTION_PATTERN).flatten.first
if func
$stderr.puts "===== #{func} =====" if DEBUG
@function_stack.push(@current) if @current
@current = new_function(func)
elsif @current
@current.process(line){ @current = @function_stack.pop } # functionの定義を終える際に呼び出されるブロックを指定
end
end
end
def new_function(func)
class_name, meth = func.scan(METHOD_PATTERN).flatten
if class_name
func_name = meth
elsif @current
class_name = @current.klass.name
func_name = "%s/%s" % [@current.name, func]
else
class_name = 'unit' # class_name ならクラス用のメソッドではなくユニットの関数
func_name = func
end
klass = pascal_file.class_by(class_name)
return klass.function_by(func_name)
end
end
end
| 28.911111 | 99 | 0.635665 |
1cfe4e595bc57cfa538f162ffd0cf18c157832b7
| 2,776 |
module Grenadine
class Image
def initialize(process_id)
@process_id = process_id
end
attr_reader :process_id
def valid?
File.exist? pid_1_path
end
def images_dir_path
"#{self.class.images_dir}/#{process_id}"
end
def self.images_dir
ENV['GREN_IMAGES_DIR'] || "/var/lib/grenadine/images"
end
def pid_1_path
"#{images_dir_path}/core-1.img"
end
def pid_1_img
if valid?
@img ||= File.open(pid_1_path, 'r')
end
end
def json_from_crit
@data ||= JSON.parse(`crit decode -i #{pid_1_path}`)
end
def comm
json_from_crit["entries"][0]["tc"]["comm"]
rescue
"<unknown>"
end
def ctime
if pid_1_img
Time.at(GrenadineUtil.get_ctime(pid_1_img.fileno))
end
end
def page_size
files = `find #{images_dir_path}/pages*.img -type f`.lines.map{|l| l.chomp}
raw = GrenadineUtil.get_page_size(files)
if raw >= 1024 * 1024 * 1024
"%.2fGiB" % (raw.to_f / (1024 * 1024 * 1024))
elsif raw >= 1024 * 1024
"%.2fMiB" % (raw.to_f / (1024 * 1024))
elsif raw >= 1024
"%.2fKiB" % (raw.to_f / 1024)
else
raw
end
end
def to_fmt_arg
[process_id, ctime, comm[0..9], page_size]
end
HDR_FORMAT = "%3s\t%-32s\t%-25s\t%-10s\t%-8s"
FORMAT = "%3d\t%-32s\t%-25s\t%-10s\t%-8s"
def self.find_index(i)
self.find_all[i]
end
def self.find_all(limit=nil)
if `ls #{self.images_dir} | wc -l`.to_i == 0
return []
end
images = []
`find #{self.images_dir}/* -type d`.each_line do |path|
process_id = File.basename(path.chomp)
images << Image.new(process_id)
end
if limit
images.select{|i| i.valid? }.sort_by{|i| i.ctime }.reverse[0, limit]
else
images.select{|i| i.valid? }.sort_by{|i| i.ctime }.reverse
end
end
def self.list(argv)
@limit = 10
o = GetoptLong.new(
['-h', '--help', GetoptLong::NO_ARGUMENT],
['-l', '--limit', GetoptLong::OPTIONAL_ARGUMENT],
)
o.ARGV = argv
o.each do |optname, optarg| # run parse
case optname
when '-l'
@limit = optarg.to_i
when '-h'
help_list
exit
end
end
puts HDR_FORMAT % %w(IDX IMAGE_ID CTIME COMM MEM_SIZE)
self.find_all(@limit).each_with_index do |img, i|
puts FORMAT % [i, *img.to_fmt_arg]
end
end
def self.help_list
puts <<-HELP
grenadine list: List available process images
Usage:
grenadine list [OPTIONS]
Options
-h, --help Show this help
-l, --limit NUM Limit images to show. Default to -l=10
HELP
end
end
end
| 22.569106 | 81 | 0.56196 |
261e9b1f900f9f518d3e1382876f15fbadb87595
| 4,124 |
#-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
require 'spec_helper'
describe 'Multi-value custom fields creation', type: :feature, js: true do
let(:admin) { FactoryGirl.create(:admin) }
def drag_and_drop(handle, to)
scroll_to_element(handle)
page
.driver
.browser
.action
.move_to(handle.native)
.click_and_hold(handle.native)
.perform
scroll_to_element(to)
page
.driver
.browser
.action
.move_to(to.native)
.release
.perform
end
before do
login_as(admin)
visit custom_fields_path
end
it 'can create and reorder custom field list values' do
# Create CF
click_on 'Create a new custom field'
fill_in 'custom_field_name', with: 'My List CF'
select 'List', from: 'custom_field_field_format'
expect(page).to have_selector('input#custom_field_custom_options_attributes_0_value')
fill_in 'custom_field_custom_options_attributes_0_value', with: 'A'
# Add new row
find('#add-custom-option').click
expect(page).to have_selector('input#custom_field_custom_options_attributes_1_value')
fill_in 'custom_field_custom_options_attributes_1_value', with: 'B'
# Add new row
find('#add-custom-option').click
expect(page).to have_selector('input#custom_field_custom_options_attributes_2_value')
fill_in 'custom_field_custom_options_attributes_2_value', with: 'C'
click_on 'Save'
# Edit again
page.find('a', text: 'My List CF').click
expect(page).to have_selector('input#custom_field_custom_options_attributes_0_value[value=A]')
expect(page).to have_selector('input#custom_field_custom_options_attributes_1_value[value=B]')
expect(page).to have_selector('input#custom_field_custom_options_attributes_2_value[value=C]')
# Expect correct values
cf = CustomField.last
expect(cf.name).to eq('My List CF')
expect(cf.possible_values.map(&:value)).to eq %w(A B C)
# Drag and drop
# We need to hack a target for where to drag the row to
page.execute_script <<-JS
jQuery('#custom-field-dragula-container')
.append('<tr class="__drag_and_drop_end_of_list"><td colspan="4" style="height: 100px"></td></tr>');
JS
rows = page.all('tr.custom-option-row')
expect(rows.length).to eq(3)
drag_and_drop rows[0].find('.dragula-handle'), page.find('.__drag_and_drop_end_of_list')
sleep 1
page.execute_script <<-JS
jQuery('.__drag_and_drop_end_of_list').remove()
JS
click_on 'Save'
# Edit again
expect(page).to have_selector('input#custom_field_custom_options_attributes_0_value[value=B]')
expect(page).to have_selector('input#custom_field_custom_options_attributes_1_value[value=C]')
expect(page).to have_selector('input#custom_field_custom_options_attributes_2_value[value=A]')
cf.reload
expect(cf.name).to eq('My List CF')
expect(cf.possible_values.map(&:value)).to eq %w(B C A)
end
end
| 33.803279 | 108 | 0.724782 |
7ac34cb07f8d1a9ac5a60d65a9e64310dc152cd0
| 1,219 |
require 'progress_bar'
puts 'Fetching rooms...'
@rooms = MatriculaWeb::Seeder.rooms
@buildings = MatriculaWeb::Seeder.buildings # Necessary to cross data
bar = ProgressBar.new(@rooms.count)
@rooms.each do |room|
bar.increment!
@code = room['codigo']
@name = room['sigla']
@capacity = room['capacidade']
@department_code = room['codigo_orgao']
@building_code = room['codigo_projecao']
@building_info = @buildings.find {|building| building['codigo'] == @building_code }
@building = Building.find_by(:code => @building_info['sigla'])
@department = Department.find_by(:code => @department_code)
unless @department != nil
# Dummy department is created
@campus = Campus.find_or_create_by(name: 'Darcy Ribeiro')
@department = Department.find_or_create_by(code: @department_code, name: 'Prefeitura', campus_id: @campus.id)
end
Room.create(
code: @code,
name: @name,
capacity: @capacity,
active: true,
time_grid_id: 1,
department_id: @department.id,
building_id: @building.id,
category_ids: [] # Due to MW limitations, it is not possible to know the equipments in the room
)
end
| 31.25641 | 117 | 0.658737 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.