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
|
---|---|---|---|---|---|
91de77babdc7b68bf1507df79f2164041eb01a0d | 212 | class AddPhoneOnlyToQuestionType < ActiveRecord::Migration[4.2]
def self.up
add_column :question_types, :phone_only, :boolean
end
def self.down
remove_column :question_types, :phone_only
end
end
| 21.2 | 63 | 0.759434 |
f8faf425f3c3dd180a7faebd87137008ef3369f6 | 10,226 | # Methods and variables for interacting with the gnuplot process. Most of
# these methods are for sending data to a gnuplot process, not for reading from
# it. Most of the methods are implemented as added methods to the built in
# classes.
require 'matrix'
module Gnuplot
# Trivial implementation of the which command that uses the PATH environment
# variable to attempt to find the given application. The application must
# be executable and reside in one of the directories in the PATH environment
# to be found. The first match that is found will be returned.
#
# bin [String] The name of the executable to search for.
#
# Return the full path to the first match or nil if no match is found.
#
def Gnuplot.which ( bin )
if RUBY_PLATFORM =~ /mswin|mingw/
all = [bin, bin + '.exe']
else
all = [bin]
end
for exec in all
if which_helper(exec)
return which_helper(exec)
end
end
return nil
end
def Gnuplot.which_helper bin
return bin if File::executable? bin
path = ENV['PATH']
path.split(File::PATH_SEPARATOR).each do |dir|
candidate = File::join dir, bin.strip
return candidate if File::executable? candidate
end
# This is an implementation that works when the which command is
# available.
#
# IO.popen("which #{bin}") { |io| return io.readline.chomp }
return nil
end
# Find the path to the gnuplot executable. The name of the executable can
# be specified using the RB_GNUPLOT environment variable but will default to
# the command 'gnuplot'.
#
# persist [bool] Add the persist flag to the gnuplot executable
#
# Return the path to the gnuplot executable or nil if one cannot be found.
def Gnuplot.gnuplot( persist = true )
exe_loc = which( ENV['RB_GNUPLOT'] || 'gnuplot' )
raise 'gnuplot executable not found on path' unless exe_loc
cmd = '"' + exe_loc + '"'
cmd += " -persist" if persist
cmd
end
# Open a gnuplot process that exists in the current PATH. If the persist
# flag is true then the -persist flag is added to the command line. The
# path to the gnuplot executable is determined using the 'which' command.
#
# See the gnuplot documentation for information on the persist flag.
#
# <b>todo</b> Add a method to pass the gnuplot path to the function.
def Gnuplot.open( persist=true )
cmd = Gnuplot.gnuplot( persist )
IO::popen( cmd, "w+") { |io|
yield io
io.close_write
@output = io.read
}
return @output
end
# Holds command information and performs the formatting of that command
# information to a Gnuplot process. When constructing a new plot for
# gnuplot, this is the first object that must be instantiated. On this
# object set the various properties and add data sets.
class Plot
attr_accessor :cmd, :data, :settings
QUOTED = [ "title", "output", "xlabel", "x2label", "ylabel", "y2label", "clabel", "cblabel", "zlabel" ]
def initialize (io = nil, cmd = "plot")
@cmd = cmd
@settings = []
@arbitrary_lines = []
@data = []
@styles = []
yield self if block_given?
puts "writing this to gnuplot:\n" + to_gplot + "\n" if $VERBOSE
if io
io << to_gplot
io << store_datasets
end
end
attr_accessor :arbitrary_lines
# Invoke the set method on the plot using the name of the invoked method
# as the set variable and any arguments that have been passed as the
# value. See the +set+ method for more details.
def method_missing( methId, *args )
set methId.id2name, *args
end
# Set a variable to the given value. +Var+ must be a gnuplot variable and
# +value+ must be the value to set it to. Automatic quoting will be
# performed if the variable requires it.
#
# This is overloaded by the +method_missing+ method so see that for more
# readable code.
def set ( var, value = "" )
value = "\"#{value}\"" if QUOTED.include? var unless value =~ /^'.*'$/
@settings << [ :set, var, value ]
end
# Unset a variable. +Var+ must be a gnuplot variable.
def unset ( var )
@settings << [ :unset, var ]
end
# Return the current value of the variable. This will return the setting
# that is currently in the instance, not one that's been given to a
# gnuplot process.
def [] ( var )
v = @settings.rassoc( var )
if v.nil? or v.first == :unset
nil
else
v[2]
end
end
class Style
attr_accessor :linestyle, :linetype, :linewidth, :linecolor,
:pointtype, :pointsize, :fill, :index
alias :ls :linestyle
alias :lt :linetype
alias :lw :linewidth
alias :lc :linecolor
alias :pt :pointtype
alias :ps :pointsize
alias :fs :fill
alias :ls= :linestyle=
alias :lt= :linetype=
alias :lw= :linewidth=
alias :lc= :linecolor=
alias :pt= :pointtype=
alias :ps= :pointsize=
alias :fs= :fill=
STYLES = [:ls, :lt, :lw, :lc, :pt, :ps, :fs]
def Style.increment_index
@index ||= 0
@index += 1
@index
end
def initialize
STYLES.each do |s|
send("#{s}=", nil)
end
yield self if block_given?
# only set the index if the user didn't do it
@index = Style::increment_index if index.nil?
end
def to_s
str = "set style line #{index}"
STYLES.each do |s|
style = send(s)
if not style.nil?
str << " #{s} #{style}"
end
end
str
end
end
# Create a gnuplot linestyle
def style &blk
s = Style.new &blk
@styles << s
s
end
def add_data ( ds )
@data << ds
end
def to_gplot (io = "")
@settings.each do |setting|
io << setting.map(&:to_s).join(" ") << "\n"
end
@styles.each{|s| io << s.to_s << "\n"}
@arbitrary_lines.each{|line| io << line << "\n" }
io
end
def store_datasets (io = "")
if @data.size > 0
io << @cmd << " " << @data.collect { |e| e.plot_args }.join(", ")
io << "\n"
v = @data.collect { |ds| ds.to_gplot }
io << v.compact.join("e\n")
end
io
end
end
# Analogous to Plot class, holds command information and performs the formatting of that command
# information to a Gnuplot process. Should be used when for drawing 3D plots.
class SPlot < Plot
def initialize (io = nil, cmd = "splot")
super
end
# Currently using the implementation from parent class Plot.
# Leaving the method explicit here, though, as to allow an specific
# implementation for SPlot in the future.
def to_gplot (io = "")
super
end
end
# Container for a single dataset being displayed by gnuplot. Each object
# has a reference to the actual data being plotted as well as settings that
# control the "plot" command. The data object must support the to_gplot
# command.
#
# +data+ The data that will be plotted. The only requirement is that the
# object understands the to_gplot method.
#
# The following attributes correspond to their related string in the gnuplot
# command. See the gnuplot documentation for more information on this.
#
# title, with
#
# @todo Use the delegator to delegate to the data property.
class DataSet
attr_accessor :title, :with, :using, :data, :linewidth, :linecolor, :matrix, :smooth, :axes, :index, :linestyle
alias :ls :linestyle
alias :ls= :linestyle=
def initialize (data = nil)
@data = data
@linestyle = @title = @with = @using = @linewidth = @linecolor = @matrix =
@smooth = @axes = @index = nil # avoid warnings
yield self if block_given?
end
def notitle
@title = "notitle"
end
def plot_args (io = "")
# Order of these is important or gnuplot barfs on 'em
io << ( (@data.instance_of? String) ? @data : "'-'" )
io << " index #{@index}" if @index
io << " using #{@using}" if @using
io << " axes #{@axes}" if @axes
io << case @title
when /notitle/ then " notitle"
when nil then ""
else " title '#{@title}'"
end
io << " matrix" if @matrix
io << " smooth #{@smooth}" if @smooth
io << " with #{@with}" if @with
io << " linecolor #{@linecolor}" if @linecolor
io << " linewidth #{@linewidth}" if @linewidth
io << " linestyle #{@linestyle.index}" if @linestyle
io
end
def to_gplot
case @data
when nil then nil
when String then nil
else @data.to_gplot
end
end
def to_gsplot
case @data
when nil then nil
when String then nil
else @data.to_gsplot
end
end
end
end
class Array
def to_gplot
if ( self[0].kind_of? Array ) then
tmp = self[0].zip( *self[1..-1] )
tmp.collect { |a| a.join(" ") }.join("\n") + "\ne"
elsif ( self[0].kind_of? Numeric ) then
s = ""
self.length.times { |i| s << "#{self[i]}\n" }
s
else
self[0].zip( *self[1..-1] ).to_gplot
end
end
def to_gsplot
f = ""
if ( self[0].kind_of? Array ) then
x = self[0]
y = self[1]
d = self[2]
x.each_with_index do |xv, i|
y.each_with_index do |yv, j|
f << [ xv, yv, d[i][j] ].join(" ") << "\n"
end
# f << "\n"
end
elsif ( self[0].kind_of? Numeric ) then
self.length.times do |i| f << "#{self[i]}\n" end
else
self[0].zip( *self[1..-1] ).to_gsplot
end
f
end
end
class Matrix
def to_gplot (x = nil, y = nil)
xgrid = x || (0...self.column_size).to_a
ygrid = y || (0...self.row_size).to_a
f = ""
ygrid.length.times do |j|
y = ygrid[j]
xgrid.length.times do |i|
if ( self[j,i] ) then
f << "#{xgrid[i]} #{y} #{self[j,i]}\n"
end
end
end
f
end
end
| 26.086735 | 115 | 0.584588 |
1875474ecbfc2f608ccbfa62f8a95c32a001c754 | 119 | # frozen_string_literal: true
FactoryBot.define do
factory :source do
name { "SR Player's Handbook" }
end
end
| 14.875 | 35 | 0.714286 |
2871028335a1d54e49b407f4973e511057770ddc | 1,064 | helper = Nrsysmond::InstallHelper.new(node)
template '/opt/local/etc/nrsysmond.cfg' do
source 'nrsysmond.cfg.erb'
owner 'root'
group helper.process_group
mode 0640
variables(
license: node['nrsysmond']['license'],
logfile: node['nrsysmond']['logfile'],
loglevel: node['nrsysmond']['loglevel'],
proxy: node['nrsysmond']['proxy'],
ssl: node['nrsysmond']['ssl'],
ssl_ca_path: node['nrsysmond']['ssl_ca_path'],
ssl_ca_bundle: node['nrsysmond']['ssl_ca_bundle'],
pidfile: node['nrsysmond']['pidfile'],
collector_host: node['nrsysmond']['collector_host'],
timeout: node['nrsysmond']['timeout']
)
notifies :restart, 'service[nrsysmond]'
end
if helper.use_pkgin?
package 'nrsysmond' do
version helper.latest_pkgin_version.to_s
end
else
execute 'remove old nrsysmond' do
command 'pkg_delete nrsysmond'
only_if { helper.remove_old_version? }
end
execute 'install nrsysmond' do
command 'pkg_add -f %s' % helper.pkg_url
not_if { helper.already_installed? }
end
end
service 'nrsysmond'
| 26.6 | 56 | 0.693609 |
1a3be8e3c2badf08fc1d2d9229143129173f3928 | 125 | module Twilio
module REST
class ConnectApps < ListResource; end
class ConnectApp < InstanceResource; end
end
end
| 17.857143 | 44 | 0.744 |
d5d5fe62e7f0b32aa4a71a98b284fb2b4d9943e8 | 352 | cask 'cinch' do
version '1.2.3'
sha256 '62589f8f7d08e537dcadea97a4cb35243db2b8a63efc25a21317814f732c5c11'
url "https://www.irradiatedsoftware.com/downloads/Cinch_#{version}.zip"
appcast 'https://www.irradiatedsoftware.com/updates/profiles/cinch.php'
name 'Cinch'
homepage 'https://www.irradiatedsoftware.com/cinch/'
app 'Cinch.app'
end
| 29.333333 | 75 | 0.772727 |
081df23f394dd400d8aa8c5ecf69f0f1c1d09909 | 606 | # rubocop:disable RemoveIndex
class RemoveKeysFingerprintIndexIfExists < ActiveRecord::Migration
include Gitlab::Database::MigrationHelpers
disable_ddl_transaction!
# https://gitlab.com/gitlab-org/gitlab-ee/merge_requests/250
# That MR was added on gitlab-ee so we need to check if the index
# already exists because we want to do is create an unique index instead.
def up
if index_exists?(:keys, :fingerprint)
remove_index :keys, :fingerprint
end
end
def down
unless index_exists?(:keys, :fingerprint)
add_concurrent_index :keys, :fingerprint
end
end
end
| 26.347826 | 75 | 0.744224 |
334f2cff9b656100f163c2dc786dbbee74cb43c2 | 1,783 | class Cpprestsdk < Formula
desc "C++ libraries for cloud-based client-server communication"
homepage "https://github.com/Microsoft/cpprestsdk"
url "https://github.com/Microsoft/cpprestsdk/archive/v2.9.1.tar.gz"
sha256 "537358760acd782f4d2ed3a85d92247b4fc423aff9c85347dc31dbb0ab9bab16"
head "https://github.com/Microsoft/cpprestsdk.git", :branch => "development"
bottle do
cellar :any
sha256 "35da0bc8f94e1faca8c2d0972d354f2fe15141383157cd5c63205a1d74928c74" => :sierra
sha256 "fd091b4222e5c2e512d23c2c86b8f6a3b5064b4bd024b2a154a28e53b11dd1b6" => :el_capitan
sha256 "cd0b08daf4d0e02334d57d38e62254a95c82f554011a52ab914da953e5a226e9" => :yosemite
end
depends_on "boost"
depends_on "openssl"
depends_on "cmake" => :build
def install
system "cmake", "-DBUILD_SAMPLES=OFF", "-DBUILD_TESTS=OFF", "Release", *std_cmake_args
system "make", "install"
end
test do
(testpath/"test.cc").write <<-EOS.undent
#include <iostream>
#include <cpprest/http_client.h>
int main() {
web::http::client::http_client client(U("https://github.com/"));
std::cout << client.request(web::http::methods::GET).get().extract_string().get() << std::endl;
}
EOS
flags = ["-stdlib=libc++", "-std=c++11", "-I#{include}",
"-I#{Formula["boost"].include}",
"-I#{Formula["openssl"].include}", "-L#{lib}",
"-L#{Formula["openssl"].lib}", "-L#{Formula["boost"].lib}",
"-lssl", "-lcrypto", "-lboost_random", "-lboost_chrono",
"-lboost_thread-mt", "-lboost_system-mt", "-lboost_regex",
"-lboost_filesystem", "-lcpprest"] + ENV.cflags.to_s.split
system ENV.cxx, "-o", "test_cpprest", "test.cc", *flags
system "./test_cpprest"
end
end
| 39.622222 | 103 | 0.661245 |
d58eac224edfd63a71695aa03062cff34f941b35 | 184 | require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe "DriverPool" do
it "should be a hash" do
Sauce.driver_pool.should be_an_instance_of Hash
end
end | 23 | 68 | 0.75 |
3371fe7d5ef0619dcfa8f39f278e65387caa28cf | 1,458 | module Issues
class UpdateService < Issues::BaseService
def execute(issue)
state = params[:state_event]
case state
when 'reopen'
Issues::ReopenService.new(project, current_user, {}).execute(issue)
when 'close'
Issues::CloseService.new(project, current_user, {}).execute(issue)
when 'task_check'
issue.update_nth_task(params[:task_num].to_i, true)
when 'task_uncheck'
issue.update_nth_task(params[:task_num].to_i, false)
end
params[:assignee_id] = "" if params[:assignee_id] == "-1"
params[:milestone_id] = "" if params[:milestone_id] == "-1"
old_labels = issue.labels.to_a
if params.present? && issue.update_attributes(params.except(:state_event,
:task_num))
issue.reset_events_cache
if issue.labels != old_labels
create_labels_note(
issue, issue.labels - old_labels, old_labels - issue.labels)
end
if issue.previous_changes.include?('milestone_id')
create_milestone_note(issue)
end
if issue.previous_changes.include?('assignee_id')
create_assignee_note(issue)
notification_service.reassigned_issue(issue, current_user)
end
issue.notice_added_references(issue.project, current_user)
execute_hooks(issue, 'update')
end
issue
end
end
end
| 30.375 | 79 | 0.620027 |
e22691f4a7b47f0886555d70a3147ec82d08359e | 39,581 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2020_08_01
#
# IpGroups
#
class IpGroups
include MsRestAzure
#
# Creates and initializes a new instance of the IpGroups class.
# @param client service class for accessing basic functionality.
#
def initialize(client)
@client = client
end
# @return [NetworkManagementClient] reference to the NetworkManagementClient
attr_reader :client
#
# Gets the specified ipGroups.
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param expand [String] Expands resourceIds (of Firewalls/Network Security
# Groups etc.) back referenced by the IpGroups resource.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [IpGroup] operation results.
#
def get(resource_group_name, ip_groups_name, expand:nil, custom_headers:nil)
response = get_async(resource_group_name, ip_groups_name, expand:expand, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets the specified ipGroups.
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param expand [String] Expands resourceIds (of Firewalls/Network Security
# Groups etc.) back referenced by the IpGroups resource.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def get_with_http_info(resource_group_name, ip_groups_name, expand:nil, custom_headers:nil)
get_async(resource_group_name, ip_groups_name, expand:expand, custom_headers:custom_headers).value!
end
#
# Gets the specified ipGroups.
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param expand [String] Expands resourceIds (of Firewalls/Network Security
# Groups etc.) back referenced by the IpGroups resource.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def get_async(resource_group_name, ip_groups_name, expand:nil, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'ip_groups_name is nil' if ip_groups_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'ipGroupsName' => ip_groups_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version,'$expand' => expand},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_08_01::Models::IpGroup.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Creates or updates an ipGroups in a specified resource group.
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param parameters [IpGroup] Parameters supplied to the create or update
# IpGroups operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [IpGroup] operation results.
#
def create_or_update(resource_group_name, ip_groups_name, parameters, custom_headers:nil)
response = create_or_update_async(resource_group_name, ip_groups_name, parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param parameters [IpGroup] Parameters supplied to the create or update
# IpGroups operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Concurrent::Promise] promise which provides async access to http
# response.
#
def create_or_update_async(resource_group_name, ip_groups_name, parameters, custom_headers:nil)
# Send request
promise = begin_create_or_update_async(resource_group_name, ip_groups_name, parameters, custom_headers:custom_headers)
promise = promise.then do |response|
# Defining deserialization method.
deserialize_method = lambda do |parsed_response|
result_mapper = Azure::Network::Mgmt::V2020_08_01::Models::IpGroup.mapper()
parsed_response = @client.deserialize(result_mapper, parsed_response)
end
# Waiting for response.
@client.get_long_running_operation_result(response, deserialize_method)
end
promise
end
#
# Updates tags of an IpGroups resource.
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param parameters [TagsObject] Parameters supplied to the update ipGroups
# operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [IpGroup] operation results.
#
def update_groups(resource_group_name, ip_groups_name, parameters, custom_headers:nil)
response = update_groups_async(resource_group_name, ip_groups_name, parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Updates tags of an IpGroups resource.
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param parameters [TagsObject] Parameters supplied to the update ipGroups
# operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def update_groups_with_http_info(resource_group_name, ip_groups_name, parameters, custom_headers:nil)
update_groups_async(resource_group_name, ip_groups_name, parameters, custom_headers:custom_headers).value!
end
#
# Updates tags of an IpGroups resource.
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param parameters [TagsObject] Parameters supplied to the update ipGroups
# operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def update_groups_async(resource_group_name, ip_groups_name, parameters, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'ip_groups_name is nil' if ip_groups_name.nil?
fail ArgumentError, 'parameters is nil' if parameters.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::Network::Mgmt::V2020_08_01::Models::TagsObject.mapper()
request_content = @client.serialize(request_mapper, parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'ipGroupsName' => ip_groups_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:patch, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_08_01::Models::IpGroup.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Deletes the specified ipGroups.
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
def delete(resource_group_name, ip_groups_name, custom_headers:nil)
response = delete_async(resource_group_name, ip_groups_name, custom_headers:custom_headers).value!
nil
end
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Concurrent::Promise] promise which provides async access to http
# response.
#
def delete_async(resource_group_name, ip_groups_name, custom_headers:nil)
# Send request
promise = begin_delete_async(resource_group_name, ip_groups_name, custom_headers:custom_headers)
promise = promise.then do |response|
# Defining deserialization method.
deserialize_method = lambda do |parsed_response|
end
# Waiting for response.
@client.get_long_running_operation_result(response, deserialize_method)
end
promise
end
#
# Gets all IpGroups in a resource group.
#
# @param resource_group_name [String] The name of the resource group.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<IpGroup>] operation results.
#
def list_by_resource_group(resource_group_name, custom_headers:nil)
first_page = list_by_resource_group_as_lazy(resource_group_name, custom_headers:custom_headers)
first_page.get_all_items
end
#
# Gets all IpGroups in a resource group.
#
# @param resource_group_name [String] The name of the resource group.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_by_resource_group_with_http_info(resource_group_name, custom_headers:nil)
list_by_resource_group_async(resource_group_name, custom_headers:custom_headers).value!
end
#
# Gets all IpGroups in a resource group.
#
# @param resource_group_name [String] The name of the resource group.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_by_resource_group_async(resource_group_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_08_01::Models::IpGroupListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets all IpGroups in a subscription.
#
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [Array<IpGroup>] operation results.
#
def list(custom_headers:nil)
first_page = list_as_lazy(custom_headers:custom_headers)
first_page.get_all_items
end
#
# Gets all IpGroups in a subscription.
#
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_with_http_info(custom_headers:nil)
list_async(custom_headers:custom_headers).value!
end
#
# Gets all IpGroups in a subscription.
#
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_async(custom_headers:nil)
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.Network/ipGroups'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_08_01::Models::IpGroupListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Creates or updates an ipGroups in a specified resource group.
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param parameters [IpGroup] Parameters supplied to the create or update
# IpGroups operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [IpGroup] operation results.
#
def begin_create_or_update(resource_group_name, ip_groups_name, parameters, custom_headers:nil)
response = begin_create_or_update_async(resource_group_name, ip_groups_name, parameters, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Creates or updates an ipGroups in a specified resource group.
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param parameters [IpGroup] Parameters supplied to the create or update
# IpGroups operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def begin_create_or_update_with_http_info(resource_group_name, ip_groups_name, parameters, custom_headers:nil)
begin_create_or_update_async(resource_group_name, ip_groups_name, parameters, custom_headers:custom_headers).value!
end
#
# Creates or updates an ipGroups in a specified resource group.
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param parameters [IpGroup] Parameters supplied to the create or update
# IpGroups operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def begin_create_or_update_async(resource_group_name, ip_groups_name, parameters, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'ip_groups_name is nil' if ip_groups_name.nil?
fail ArgumentError, 'parameters is nil' if parameters.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
# Serialize Request
request_mapper = Azure::Network::Mgmt::V2020_08_01::Models::IpGroup.mapper()
request_content = @client.serialize(request_mapper, parameters)
request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'ipGroupsName' => ip_groups_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
body: request_content,
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:put, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 201
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_08_01::Models::IpGroup.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
# Deserialize Response
if status_code == 201
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_08_01::Models::IpGroup.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Deletes the specified ipGroups.
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
#
def begin_delete(resource_group_name, ip_groups_name, custom_headers:nil)
response = begin_delete_async(resource_group_name, ip_groups_name, custom_headers:custom_headers).value!
nil
end
#
# Deletes the specified ipGroups.
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def begin_delete_with_http_info(resource_group_name, ip_groups_name, custom_headers:nil)
begin_delete_async(resource_group_name, ip_groups_name, custom_headers:custom_headers).value!
end
#
# Deletes the specified ipGroups.
#
# @param resource_group_name [String] The name of the resource group.
# @param ip_groups_name [String] The name of the ipGroups.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def begin_delete_async(resource_group_name, ip_groups_name, custom_headers:nil)
fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
fail ArgumentError, 'ip_groups_name is nil' if ip_groups_name.nil?
fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?
fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ipGroups/{ipGroupsName}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
path_params: {'resourceGroupName' => resource_group_name,'ipGroupsName' => ip_groups_name,'subscriptionId' => @client.subscription_id},
query_params: {'api-version' => @client.api_version},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:delete, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200 || status_code == 202 || status_code == 204
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
result
end
promise.execute
end
#
# Gets all IpGroups in a resource group.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [IpGroupListResult] operation results.
#
def list_by_resource_group_next(next_page_link, custom_headers:nil)
response = list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets all IpGroups in a resource group.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_by_resource_group_next_with_http_info(next_page_link, custom_headers:nil)
list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# Gets all IpGroups in a resource group.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_by_resource_group_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_08_01::Models::IpGroupListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets all IpGroups in a subscription.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [IpGroupListResult] operation results.
#
def list_next(next_page_link, custom_headers:nil)
response = list_next_async(next_page_link, custom_headers:custom_headers).value!
response.body unless response.nil?
end
#
# Gets all IpGroups in a subscription.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [MsRestAzure::AzureOperationResponse] HTTP response information.
#
def list_next_with_http_info(next_page_link, custom_headers:nil)
list_next_async(next_page_link, custom_headers:custom_headers).value!
end
#
# Gets all IpGroups in a subscription.
#
# @param next_page_link [String] The NextLink from the previous successful call
# to List operation.
# @param [Hash{String => String}] A hash of custom headers that will be added
# to the HTTP request.
#
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def list_next_async(next_page_link, custom_headers:nil)
fail ArgumentError, 'next_page_link is nil' if next_page_link.nil?
request_headers = {}
request_headers['Content-Type'] = 'application/json; charset=utf-8'
# Set Headers
request_headers['x-ms-client-request-id'] = SecureRandom.uuid
request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?
path_template = '{nextLink}'
request_url = @base_url || @client.base_url
options = {
middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
skip_encoding_path_params: {'nextLink' => next_page_link},
headers: request_headers.merge(custom_headers || {}),
base_url: request_url
}
promise = @client.make_request_async(:get, path_template, options)
promise = promise.then do |result|
http_response = result.response
status_code = http_response.status
response_content = http_response.body
unless status_code == 200
error_model = JSON.load(response_content)
fail MsRest::HttpOperationError.new(result.request, http_response, error_model)
end
result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?
# Deserialize Response
if status_code == 200
begin
parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content)
result_mapper = Azure::Network::Mgmt::V2020_08_01::Models::IpGroupListResult.mapper()
result.body = @client.deserialize(result_mapper, parsed_response)
rescue Exception => e
fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result)
end
end
result
end
promise.execute
end
#
# Gets all IpGroups in a resource group.
#
# @param resource_group_name [String] The name of the resource group.
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [IpGroupListResult] which provide lazy access to pages of the
# response.
#
def list_by_resource_group_as_lazy(resource_group_name, custom_headers:nil)
response = list_by_resource_group_async(resource_group_name, custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
#
# Gets all IpGroups in a subscription.
#
# @param custom_headers [Hash{String => String}] A hash of custom headers that
# will be added to the HTTP request.
#
# @return [IpGroupListResult] which provide lazy access to pages of the
# response.
#
def list_as_lazy(custom_headers:nil)
response = list_async(custom_headers:custom_headers).value!
unless response.nil?
page = response.body
page.next_method = Proc.new do |next_page_link|
list_next_async(next_page_link, custom_headers:custom_headers)
end
page
end
end
end
end
| 43.210699 | 145 | 0.697178 |
03e66a26c2b0452bcb8e51cd634146aedb349205 | 1,124 | # -*- coding: binary -*-
require 'erb'
module Rex
module Proto
module Http
###
#
# This class is used to wrapper the calling of a procedure when a request
# arrives.
#
###
class Handler::Proc < Handler
#
# Initializes the proc handler with the supplied procedure
#
def initialize(server, procedure, virt_dir = false)
super(server)
self.procedure = procedure
self.virt_dir = virt_dir || false
end
#
# Returns true if the procedure is representing a virtual directory.
#
def relative_resource_required?
virt_dir
end
#
# Called when a request arrives.
#
def on_request(cli, req)
begin
procedure.call(cli, req)
rescue Errno::EPIPE
elog("Proc::on_request: Client closed connection prematurely", LogSource)
rescue
elog("Proc::on_request: #{$!.class}: #{$!}\n\n#{[email protected]("\n")}", LogSource)
if self.server and self.server.context
exploit = self.server.context['MsfExploit']
if exploit
exploit.print_error("Exception handling request: #{$!}")
end
end
end
end
protected
attr_accessor :procedure # :nodoc:
attr_accessor :virt_dir # :nodoc:
end
end
end
end
| 18.129032 | 78 | 0.69306 |
4abde4837768e309722fc61e99763640c90659be | 405 | cask "mindforger" do
version "1.52.0"
sha256 "bae855dad678b54a557829877320ee892958be0e20de8661a6d4ee7e3b62bcd0"
url "https://github.com/dvorka/mindforger/releases/download/#{version}/mindforger-macos-#{version}.dmg",
verified: "github.com/dvorka/mindforger/"
name "MindForger"
desc "Thinking notebook and Markdown IDE"
homepage "https://www.mindforger.com/"
app "mindforger.app"
end
| 31.153846 | 106 | 0.758025 |
ed44be05a7ffb78c690d46f3ad97bb95f6a71c6a | 11,208 | =begin
The wallee API allows an easy interaction with the wallee web service.
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.
=end
require 'date'
module Wallee
#
class Account
# Active means that this account and all accounts in the hierarchy are active.
attr_accessor :active
# This property is true when all accounts in the hierarchy are active or restricted active.
attr_accessor :active_or_restricted_active
# The ID of a user that deleted this entity.
attr_accessor :deleted_by
# The date and time when this entity was deleted.
attr_accessor :deleted_on
# The ID is the primary key of the entity. The ID identifies the entity uniquely.
attr_accessor :id
# The name of the account identifies the account within the administrative interface.
attr_accessor :name
# The account which is responsible for administering the account.
attr_accessor :parent_account
# The planned purge date indicates when the entity is permanently removed. When the date is null the entity is not planned to be removed.
attr_accessor :planned_purge_date
# Restricted active means that at least one account in the hierarchy is only restricted active, but all are either restricted active or active.
attr_accessor :restricted_active
# This is the scope to which the account belongs to.
attr_accessor :scope
#
attr_accessor :state
# This property restricts the number of subaccounts which can be created within this account.
attr_accessor :subaccount_limit
# The account type defines which role and capabilities it has.
attr_accessor :type
# The version number indicates the version of the entity. The version is incremented whenever the entity is changed.
attr_accessor :version
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'active' => :'active',
:'active_or_restricted_active' => :'activeOrRestrictedActive',
:'deleted_by' => :'deletedBy',
:'deleted_on' => :'deletedOn',
:'id' => :'id',
:'name' => :'name',
:'parent_account' => :'parentAccount',
:'planned_purge_date' => :'plannedPurgeDate',
:'restricted_active' => :'restrictedActive',
:'scope' => :'scope',
:'state' => :'state',
:'subaccount_limit' => :'subaccountLimit',
:'type' => :'type',
:'version' => :'version'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'active' => :'BOOLEAN',
:'active_or_restricted_active' => :'BOOLEAN',
:'deleted_by' => :'Integer',
:'deleted_on' => :'DateTime',
:'id' => :'Integer',
:'name' => :'String',
:'parent_account' => :'Account',
:'planned_purge_date' => :'DateTime',
:'restricted_active' => :'BOOLEAN',
:'scope' => :'Integer',
:'state' => :'AccountState',
:'subaccount_limit' => :'Integer',
:'type' => :'AccountType',
:'version' => :'Integer'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.has_key?(:'active')
self.active = attributes[:'active']
end
if attributes.has_key?(:'activeOrRestrictedActive')
self.active_or_restricted_active = attributes[:'activeOrRestrictedActive']
end
if attributes.has_key?(:'deletedBy')
self.deleted_by = attributes[:'deletedBy']
end
if attributes.has_key?(:'deletedOn')
self.deleted_on = attributes[:'deletedOn']
end
if attributes.has_key?(:'id')
self.id = attributes[:'id']
end
if attributes.has_key?(:'name')
self.name = attributes[:'name']
end
if attributes.has_key?(:'parentAccount')
self.parent_account = attributes[:'parentAccount']
end
if attributes.has_key?(:'plannedPurgeDate')
self.planned_purge_date = attributes[:'plannedPurgeDate']
end
if attributes.has_key?(:'restrictedActive')
self.restricted_active = attributes[:'restrictedActive']
end
if attributes.has_key?(:'scope')
self.scope = attributes[:'scope']
end
if attributes.has_key?(:'state')
self.state = attributes[:'state']
end
if attributes.has_key?(:'subaccountLimit')
self.subaccount_limit = attributes[:'subaccountLimit']
end
if attributes.has_key?(:'type')
self.type = attributes[:'type']
end
if attributes.has_key?(:'version')
self.version = attributes[:'version']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
if [email protected]? && @name.to_s.length > 200
invalid_properties.push('invalid value for "name", the character length must be smaller than or equal to 200.')
end
if [email protected]? && @name.to_s.length < 3
invalid_properties.push('invalid value for "name", the character length must be great than or equal to 3.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if [email protected]? && @name.to_s.length > 200
return false if [email protected]? && @name.to_s.length < 3
true
end
# Custom attribute writer method with validation
# @param [Object] name Value to be assigned
def name=(name)
if !name.nil? && name.to_s.length > 200
fail ArgumentError, 'invalid value for "name", the character length must be smaller than or equal to 200.'
end
if !name.nil? && name.to_s.length < 3
fail ArgumentError, 'invalid value for "name", the character length must be great than or equal to 3.'
end
@name = name
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
active == o.active &&
active_or_restricted_active == o.active_or_restricted_active &&
deleted_by == o.deleted_by &&
deleted_on == o.deleted_on &&
id == o.id &&
name == o.name &&
parent_account == o.parent_account &&
planned_purge_date == o.planned_purge_date &&
restricted_active == o.restricted_active &&
scope == o.scope &&
state == o.state &&
subaccount_limit == o.subaccount_limit &&
type == o.type &&
version == o.version
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[active, active_or_restricted_active, deleted_by, deleted_on, id, name, parent_account, planned_purge_date, restricted_active, scope, state, subaccount_limit, type, version].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = Wallee.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map{ |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 32.393064 | 184 | 0.632316 |
bfe088534635a834ecf9db1dfda9d117dc0177dd | 842 | require 'rails_helper'
RSpec.describe FeedPostsController, type: :controller do
let(:user) { create :user }
before { sign_in user }
describe '#index' do
subject { get :index }
let!(:post) { create :post, user: user }
it 'assigns @posts' do
subject
expect(assigns(:posts)).to eq([post])
end
it { is_expected.to render_template(:index) }
context 'when the ajax request comes' do
subject { get :index, xhr: true, format: :json }
it 'returns json' do
subject
expect(response.header['Content-Type']).to include('application/json')
end
end
context 'when the user is not logged in' do
before { sign_out user }
it 'redirect to log in page' do
subject
is_expected.to redirect_to(new_user_session_path)
end
end
end
end | 22.157895 | 78 | 0.627078 |
269ad63582e46589f097934020bc1ead0745cd2a | 2,848 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2019_02_01
module Models
#
# Response for ListVirtualNetworkTap API service call.
#
class VirtualNetworkTapListResult
include MsRestAzure
include MsRest::JSONable
# @return [Array<VirtualNetworkTap>] A list of VirtualNetworkTaps in a
# resource group.
attr_accessor :value
# @return [String] The URL to get the next set of results.
attr_accessor :next_link
# return [Proc] with next page method call.
attr_accessor :next_method
#
# Gets the rest of the items for the request, enabling auto-pagination.
#
# @return [Array<VirtualNetworkTap>] operation results.
#
def get_all_items
items = @value
page = self
while page.next_link != nil && !page.next_link.strip.empty? do
page = page.get_next_page
items.concat(page.value)
end
items
end
#
# Gets the next page of results.
#
# @return [VirtualNetworkTapListResult] with next page content.
#
def get_next_page
response = @next_method.call(@next_link).value! unless @next_method.nil?
unless response.nil?
@next_link = response.body.next_link
@value = response.body.value
self
end
end
#
# Mapper for VirtualNetworkTapListResult class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'VirtualNetworkTapListResult',
type: {
name: 'Composite',
class_name: 'VirtualNetworkTapListResult',
model_properties: {
value: {
client_side_validation: true,
required: false,
serialized_name: 'value',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'VirtualNetworkTapElementType',
type: {
name: 'Composite',
class_name: 'VirtualNetworkTap'
}
}
}
},
next_link: {
client_side_validation: true,
required: false,
serialized_name: 'nextLink',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 28.48 | 80 | 0.535112 |
bf823f68b3739b22df65544fb508482552239e7c | 788 | class Iroha < Formula
desc "Hyperledger Iroha — distributed ledger technology platform"
homepage "http://iroha.tech/en"
url "https://github.com/hyperledger/iroha.git", :branch => "master"
head "https://github.com/hyperledger/iroha.git"
version "v1.0_alpha"
depends_on "cmake" => :build
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "golang" => :build
depends_on "libtool"
depends_on "tbb"
depends_on "postgres"
depends_on "boost"
depends_on "grpc"
def install
system "cmake -H. -Bbuild"
system "cmake --build build -- -j8 irohad iroha-cli"
bin.install "build/bin/irohad"
bin.install "build/bin/iroha-cli"
pkgshare.install "build/libs"
end
test do
system "#{bin}/iroha-cli", "--help"
end
end
| 26.266667 | 69 | 0.678934 |
1daedc11aab36b20344230e0bf47eaf4d353bb9e | 32,303 | # frozen_string_literal: true
# Copyright 2021 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!
module Google
module Cloud
module Language
module V1beta1
# Represents the input to API methods.
# @!attribute [rw] type
# @return [::Google::Cloud::Language::V1beta1::Document::Type]
# Required. If the type is not set or is `TYPE_UNSPECIFIED`,
# returns an `INVALID_ARGUMENT` error.
# @!attribute [rw] content
# @return [::String]
# The content of the input in string format.
# @!attribute [rw] gcs_content_uri
# @return [::String]
# The Google Cloud Storage URI where the file content is located.
# This URI must be of the form: gs://bucket_name/object_name. For more
# details, see https://cloud.google.com/storage/docs/reference-uris.
# NOTE: Cloud Storage object versioning is not supported.
# @!attribute [rw] language
# @return [::String]
# The language of the document (if not specified, the language is
# automatically detected). Both ISO and BCP-47 language codes are
# accepted.<br>
# [Language
# Support](https://cloud.google.com/natural-language/docs/languages) lists
# currently supported languages for each API method. If the language (either
# specified by the caller or automatically detected) is not supported by the
# called API method, an `INVALID_ARGUMENT` error is returned.
class Document
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
# The document types enum.
module Type
# The content type is not specified.
TYPE_UNSPECIFIED = 0
# Plain text
PLAIN_TEXT = 1
# HTML
HTML = 2
end
end
# Represents a sentence in the input document.
# @!attribute [rw] text
# @return [::Google::Cloud::Language::V1beta1::TextSpan]
# The sentence text.
# @!attribute [rw] sentiment
# @return [::Google::Cloud::Language::V1beta1::Sentiment]
# For calls to [AnalyzeSentiment][] or if
# {::Google::Cloud::Language::V1beta1::AnnotateTextRequest::Features#extract_document_sentiment AnnotateTextRequest.Features.extract_document_sentiment}
# is set to true, this field will contain the sentiment for the sentence.
class Sentence
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# Represents a phrase in the text that is a known entity, such as
# a person, an organization, or location. The API associates information, such
# as salience and mentions, with entities.
# @!attribute [rw] name
# @return [::String]
# The representative name for the entity.
# @!attribute [rw] type
# @return [::Google::Cloud::Language::V1beta1::Entity::Type]
# The entity type.
# @!attribute [rw] metadata
# @return [::Google::Protobuf::Map{::String => ::String}]
# Metadata associated with the entity.
#
# Currently, Wikipedia URLs and Knowledge Graph MIDs are provided, if
# available. The associated keys are "wikipedia_url" and "mid", respectively.
# @!attribute [rw] salience
# @return [::Float]
# The salience score associated with the entity in the [0, 1.0] range.
#
# The salience score for an entity provides information about the
# importance or centrality of that entity to the entire document text.
# Scores closer to 0 are less salient, while scores closer to 1.0 are highly
# salient.
# @!attribute [rw] mentions
# @return [::Array<::Google::Cloud::Language::V1beta1::EntityMention>]
# The mentions of this entity in the input document. The API currently
# supports proper noun mentions.
class Entity
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
# @!attribute [rw] key
# @return [::String]
# @!attribute [rw] value
# @return [::String]
class MetadataEntry
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# The type of the entity.
module Type
# Unknown
UNKNOWN = 0
# Person
PERSON = 1
# Location
LOCATION = 2
# Organization
ORGANIZATION = 3
# Event
EVENT = 4
# Work of art
WORK_OF_ART = 5
# Consumer goods
CONSUMER_GOOD = 6
# Other types
OTHER = 7
end
end
# Represents the smallest syntactic building block of the text.
# @!attribute [rw] text
# @return [::Google::Cloud::Language::V1beta1::TextSpan]
# The token text.
# @!attribute [rw] part_of_speech
# @return [::Google::Cloud::Language::V1beta1::PartOfSpeech]
# Parts of speech tag for this token.
# @!attribute [rw] dependency_edge
# @return [::Google::Cloud::Language::V1beta1::DependencyEdge]
# Dependency tree parse for this token.
# @!attribute [rw] lemma
# @return [::String]
# [Lemma](https://en.wikipedia.org/wiki/Lemma_%28morphology%29) of the token.
class Token
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# Represents the feeling associated with the entire text or entities in
# the text.
# @!attribute [rw] polarity
# @return [::Float]
# DEPRECATED FIELD - This field is being deprecated in
# favor of score. Please refer to our documentation at
# https://cloud.google.com/natural-language/docs for more information.
# @!attribute [rw] magnitude
# @return [::Float]
# A non-negative number in the [0, +inf) range, which represents
# the absolute magnitude of sentiment regardless of score (positive or
# negative).
# @!attribute [rw] score
# @return [::Float]
# Sentiment score between -1.0 (negative sentiment) and 1.0
# (positive sentiment).
class Sentiment
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# Represents part of speech information for a token.
# @!attribute [rw] tag
# @return [::Google::Cloud::Language::V1beta1::PartOfSpeech::Tag]
# The part of speech tag.
# @!attribute [rw] aspect
# @return [::Google::Cloud::Language::V1beta1::PartOfSpeech::Aspect]
# The grammatical aspect.
# @!attribute [rw] case
# @return [::Google::Cloud::Language::V1beta1::PartOfSpeech::Case]
# The grammatical case.
# @!attribute [rw] form
# @return [::Google::Cloud::Language::V1beta1::PartOfSpeech::Form]
# The grammatical form.
# @!attribute [rw] gender
# @return [::Google::Cloud::Language::V1beta1::PartOfSpeech::Gender]
# The grammatical gender.
# @!attribute [rw] mood
# @return [::Google::Cloud::Language::V1beta1::PartOfSpeech::Mood]
# The grammatical mood.
# @!attribute [rw] number
# @return [::Google::Cloud::Language::V1beta1::PartOfSpeech::Number]
# The grammatical number.
# @!attribute [rw] person
# @return [::Google::Cloud::Language::V1beta1::PartOfSpeech::Person]
# The grammatical person.
# @!attribute [rw] proper
# @return [::Google::Cloud::Language::V1beta1::PartOfSpeech::Proper]
# The grammatical properness.
# @!attribute [rw] reciprocity
# @return [::Google::Cloud::Language::V1beta1::PartOfSpeech::Reciprocity]
# The grammatical reciprocity.
# @!attribute [rw] tense
# @return [::Google::Cloud::Language::V1beta1::PartOfSpeech::Tense]
# The grammatical tense.
# @!attribute [rw] voice
# @return [::Google::Cloud::Language::V1beta1::PartOfSpeech::Voice]
# The grammatical voice.
class PartOfSpeech
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
# The part of speech tags enum.
module Tag
# Unknown
UNKNOWN = 0
# Adjective
ADJ = 1
# Adposition (preposition and postposition)
ADP = 2
# Adverb
ADV = 3
# Conjunction
CONJ = 4
# Determiner
DET = 5
# Noun (common and proper)
NOUN = 6
# Cardinal number
NUM = 7
# Pronoun
PRON = 8
# Particle or other function word
PRT = 9
# Punctuation
PUNCT = 10
# Verb (all tenses and modes)
VERB = 11
# Other: foreign words, typos, abbreviations
X = 12
# Affix
AFFIX = 13
end
# The characteristic of a verb that expresses time flow during an event.
module Aspect
# Aspect is not applicable in the analyzed language or is not predicted.
ASPECT_UNKNOWN = 0
# Perfective
PERFECTIVE = 1
# Imperfective
IMPERFECTIVE = 2
# Progressive
PROGRESSIVE = 3
end
# The grammatical function performed by a noun or pronoun in a phrase,
# clause, or sentence. In some languages, other parts of speech, such as
# adjective and determiner, take case inflection in agreement with the noun.
module Case
# Case is not applicable in the analyzed language or is not predicted.
CASE_UNKNOWN = 0
# Accusative
ACCUSATIVE = 1
# Adverbial
ADVERBIAL = 2
# Complementive
COMPLEMENTIVE = 3
# Dative
DATIVE = 4
# Genitive
GENITIVE = 5
# Instrumental
INSTRUMENTAL = 6
# Locative
LOCATIVE = 7
# Nominative
NOMINATIVE = 8
# Oblique
OBLIQUE = 9
# Partitive
PARTITIVE = 10
# Prepositional
PREPOSITIONAL = 11
# Reflexive
REFLEXIVE_CASE = 12
# Relative
RELATIVE_CASE = 13
# Vocative
VOCATIVE = 14
end
# Depending on the language, Form can be categorizing different forms of
# verbs, adjectives, adverbs, etc. For example, categorizing inflected
# endings of verbs and adjectives or distinguishing between short and long
# forms of adjectives and participles
module Form
# Form is not applicable in the analyzed language or is not predicted.
FORM_UNKNOWN = 0
# Adnomial
ADNOMIAL = 1
# Auxiliary
AUXILIARY = 2
# Complementizer
COMPLEMENTIZER = 3
# Final ending
FINAL_ENDING = 4
# Gerund
GERUND = 5
# Realis
REALIS = 6
# Irrealis
IRREALIS = 7
# Short form
SHORT = 8
# Long form
LONG = 9
# Order form
ORDER = 10
# Specific form
SPECIFIC = 11
end
# Gender classes of nouns reflected in the behaviour of associated words.
module Gender
# Gender is not applicable in the analyzed language or is not predicted.
GENDER_UNKNOWN = 0
# Feminine
FEMININE = 1
# Masculine
MASCULINE = 2
# Neuter
NEUTER = 3
end
# The grammatical feature of verbs, used for showing modality and attitude.
module Mood
# Mood is not applicable in the analyzed language or is not predicted.
MOOD_UNKNOWN = 0
# Conditional
CONDITIONAL_MOOD = 1
# Imperative
IMPERATIVE = 2
# Indicative
INDICATIVE = 3
# Interrogative
INTERROGATIVE = 4
# Jussive
JUSSIVE = 5
# Subjunctive
SUBJUNCTIVE = 6
end
# Count distinctions.
module Number
# Number is not applicable in the analyzed language or is not predicted.
NUMBER_UNKNOWN = 0
# Singular
SINGULAR = 1
# Plural
PLURAL = 2
# Dual
DUAL = 3
end
# The distinction between the speaker, second person, third person, etc.
module Person
# Person is not applicable in the analyzed language or is not predicted.
PERSON_UNKNOWN = 0
# First
FIRST = 1
# Second
SECOND = 2
# Third
THIRD = 3
# Reflexive
REFLEXIVE_PERSON = 4
end
# This category shows if the token is part of a proper name.
module Proper
# Proper is not applicable in the analyzed language or is not predicted.
PROPER_UNKNOWN = 0
# Proper
PROPER = 1
# Not proper
NOT_PROPER = 2
end
# Reciprocal features of a pronoun.
module Reciprocity
# Reciprocity is not applicable in the analyzed language or is not
# predicted.
RECIPROCITY_UNKNOWN = 0
# Reciprocal
RECIPROCAL = 1
# Non-reciprocal
NON_RECIPROCAL = 2
end
# Time reference.
module Tense
# Tense is not applicable in the analyzed language or is not predicted.
TENSE_UNKNOWN = 0
# Conditional
CONDITIONAL_TENSE = 1
# Future
FUTURE = 2
# Past
PAST = 3
# Present
PRESENT = 4
# Imperfect
IMPERFECT = 5
# Pluperfect
PLUPERFECT = 6
end
# The relationship between the action that a verb expresses and the
# participants identified by its arguments.
module Voice
# Voice is not applicable in the analyzed language or is not predicted.
VOICE_UNKNOWN = 0
# Active
ACTIVE = 1
# Causative
CAUSATIVE = 2
# Passive
PASSIVE = 3
end
end
# Represents dependency parse tree information for a token.
# @!attribute [rw] head_token_index
# @return [::Integer]
# Represents the head of this token in the dependency tree.
# This is the index of the token which has an arc going to this token.
# The index is the position of the token in the array of tokens returned
# by the API method. If this token is a root token, then the
# `head_token_index` is its own index.
# @!attribute [rw] label
# @return [::Google::Cloud::Language::V1beta1::DependencyEdge::Label]
# The parse label for the token.
class DependencyEdge
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
# The parse label enum for the token.
module Label
# Unknown
UNKNOWN = 0
# Abbreviation modifier
ABBREV = 1
# Adjectival complement
ACOMP = 2
# Adverbial clause modifier
ADVCL = 3
# Adverbial modifier
ADVMOD = 4
# Adjectival modifier of an NP
AMOD = 5
# Appositional modifier of an NP
APPOS = 6
# Attribute dependent of a copular verb
ATTR = 7
# Auxiliary (non-main) verb
AUX = 8
# Passive auxiliary
AUXPASS = 9
# Coordinating conjunction
CC = 10
# Clausal complement of a verb or adjective
CCOMP = 11
# Conjunct
CONJ = 12
# Clausal subject
CSUBJ = 13
# Clausal passive subject
CSUBJPASS = 14
# Dependency (unable to determine)
DEP = 15
# Determiner
DET = 16
# Discourse
DISCOURSE = 17
# Direct object
DOBJ = 18
# Expletive
EXPL = 19
# Goes with (part of a word in a text not well edited)
GOESWITH = 20
# Indirect object
IOBJ = 21
# Marker (word introducing a subordinate clause)
MARK = 22
# Multi-word expression
MWE = 23
# Multi-word verbal expression
MWV = 24
# Negation modifier
NEG = 25
# Noun compound modifier
NN = 26
# Noun phrase used as an adverbial modifier
NPADVMOD = 27
# Nominal subject
NSUBJ = 28
# Passive nominal subject
NSUBJPASS = 29
# Numeric modifier of a noun
NUM = 30
# Element of compound number
NUMBER = 31
# Punctuation mark
P = 32
# Parataxis relation
PARATAXIS = 33
# Participial modifier
PARTMOD = 34
# The complement of a preposition is a clause
PCOMP = 35
# Object of a preposition
POBJ = 36
# Possession modifier
POSS = 37
# Postverbal negative particle
POSTNEG = 38
# Predicate complement
PRECOMP = 39
# Preconjunt
PRECONJ = 40
# Predeterminer
PREDET = 41
# Prefix
PREF = 42
# Prepositional modifier
PREP = 43
# The relationship between a verb and verbal morpheme
PRONL = 44
# Particle
PRT = 45
# Associative or possessive marker
PS = 46
# Quantifier phrase modifier
QUANTMOD = 47
# Relative clause modifier
RCMOD = 48
# Complementizer in relative clause
RCMODREL = 49
# Ellipsis without a preceding predicate
RDROP = 50
# Referent
REF = 51
# Remnant
REMNANT = 52
# Reparandum
REPARANDUM = 53
# Root
ROOT = 54
# Suffix specifying a unit of number
SNUM = 55
# Suffix
SUFF = 56
# Temporal modifier
TMOD = 57
# Topic marker
TOPIC = 58
# Clause headed by an infinite form of the verb that modifies a noun
VMOD = 59
# Vocative
VOCATIVE = 60
# Open clausal complement
XCOMP = 61
# Name suffix
SUFFIX = 62
# Name title
TITLE = 63
# Adverbial phrase modifier
ADVPHMOD = 64
# Causative auxiliary
AUXCAUS = 65
# Helper auxiliary
AUXVV = 66
# Rentaishi (Prenominal modifier)
DTMOD = 67
# Foreign words
FOREIGN = 68
# Keyword
KW = 69
# List for chains of comparable items
LIST = 70
# Nominalized clause
NOMC = 71
# Nominalized clausal subject
NOMCSUBJ = 72
# Nominalized clausal passive
NOMCSUBJPASS = 73
# Compound of numeric modifier
NUMC = 74
# Copula
COP = 75
# Dislocated relation (for fronted/topicalized elements)
DISLOCATED = 76
end
end
# Represents a mention for an entity in the text. Currently, proper noun
# mentions are supported.
# @!attribute [rw] text
# @return [::Google::Cloud::Language::V1beta1::TextSpan]
# The mention text.
# @!attribute [rw] type
# @return [::Google::Cloud::Language::V1beta1::EntityMention::Type]
# The type of the entity mention.
class EntityMention
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
# The supported types of mentions.
module Type
# Unknown
TYPE_UNKNOWN = 0
# Proper name
PROPER = 1
# Common noun (or noun compound)
COMMON = 2
end
end
# Represents an output piece of text.
# @!attribute [rw] content
# @return [::String]
# The content of the output text.
# @!attribute [rw] begin_offset
# @return [::Integer]
# The API calculates the beginning offset of the content in the original
# document according to the
# {::Google::Cloud::Language::V1beta1::EncodingType EncodingType} specified in the
# API request.
class TextSpan
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# The sentiment analysis request message.
# @!attribute [rw] document
# @return [::Google::Cloud::Language::V1beta1::Document]
# Input document.
# @!attribute [rw] encoding_type
# @return [::Google::Cloud::Language::V1beta1::EncodingType]
# The encoding type used by the API to calculate sentence offsets for the
# sentence sentiment.
class AnalyzeSentimentRequest
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# The sentiment analysis response message.
# @!attribute [rw] document_sentiment
# @return [::Google::Cloud::Language::V1beta1::Sentiment]
# The overall sentiment of the input document.
# @!attribute [rw] language
# @return [::String]
# The language of the text, which will be the same as the language specified
# in the request or, if not specified, the automatically-detected language.
# See {::Google::Cloud::Language::V1beta1::Document#language Document.language}
# field for more details.
# @!attribute [rw] sentences
# @return [::Array<::Google::Cloud::Language::V1beta1::Sentence>]
# The sentiment for all the sentences in the document.
class AnalyzeSentimentResponse
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# The entity analysis request message.
# @!attribute [rw] document
# @return [::Google::Cloud::Language::V1beta1::Document]
# Input document.
# @!attribute [rw] encoding_type
# @return [::Google::Cloud::Language::V1beta1::EncodingType]
# The encoding type used by the API to calculate offsets.
class AnalyzeEntitiesRequest
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# The entity analysis response message.
# @!attribute [rw] entities
# @return [::Array<::Google::Cloud::Language::V1beta1::Entity>]
# The recognized entities in the input document.
# @!attribute [rw] language
# @return [::String]
# The language of the text, which will be the same as the language specified
# in the request or, if not specified, the automatically-detected language.
# See {::Google::Cloud::Language::V1beta1::Document#language Document.language}
# field for more details.
class AnalyzeEntitiesResponse
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# The syntax analysis request message.
# @!attribute [rw] document
# @return [::Google::Cloud::Language::V1beta1::Document]
# Input document.
# @!attribute [rw] encoding_type
# @return [::Google::Cloud::Language::V1beta1::EncodingType]
# The encoding type used by the API to calculate offsets.
class AnalyzeSyntaxRequest
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# The syntax analysis response message.
# @!attribute [rw] sentences
# @return [::Array<::Google::Cloud::Language::V1beta1::Sentence>]
# Sentences in the input document.
# @!attribute [rw] tokens
# @return [::Array<::Google::Cloud::Language::V1beta1::Token>]
# Tokens, along with their syntactic information, in the input document.
# @!attribute [rw] language
# @return [::String]
# The language of the text, which will be the same as the language specified
# in the request or, if not specified, the automatically-detected language.
# See {::Google::Cloud::Language::V1beta1::Document#language Document.language}
# field for more details.
class AnalyzeSyntaxResponse
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# The request message for the text annotation API, which can perform multiple
# analysis types (sentiment, entities, and syntax) in one call.
# @!attribute [rw] document
# @return [::Google::Cloud::Language::V1beta1::Document]
# Input document.
# @!attribute [rw] features
# @return [::Google::Cloud::Language::V1beta1::AnnotateTextRequest::Features]
# The enabled features.
# @!attribute [rw] encoding_type
# @return [::Google::Cloud::Language::V1beta1::EncodingType]
# The encoding type used by the API to calculate offsets.
class AnnotateTextRequest
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
# All available features for sentiment, syntax, and semantic analysis.
# Setting each one to true will enable that specific analysis for the input.
# @!attribute [rw] extract_syntax
# @return [::Boolean]
# Extract syntax information.
# @!attribute [rw] extract_entities
# @return [::Boolean]
# Extract entities.
# @!attribute [rw] extract_document_sentiment
# @return [::Boolean]
# Extract document-level sentiment.
class Features
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
end
# The text annotations response message.
# @!attribute [rw] sentences
# @return [::Array<::Google::Cloud::Language::V1beta1::Sentence>]
# Sentences in the input document. Populated if the user enables
# {::Google::Cloud::Language::V1beta1::AnnotateTextRequest::Features#extract_syntax AnnotateTextRequest.Features.extract_syntax}.
# @!attribute [rw] tokens
# @return [::Array<::Google::Cloud::Language::V1beta1::Token>]
# Tokens, along with their syntactic information, in the input document.
# Populated if the user enables
# {::Google::Cloud::Language::V1beta1::AnnotateTextRequest::Features#extract_syntax AnnotateTextRequest.Features.extract_syntax}.
# @!attribute [rw] entities
# @return [::Array<::Google::Cloud::Language::V1beta1::Entity>]
# Entities, along with their semantic information, in the input document.
# Populated if the user enables
# {::Google::Cloud::Language::V1beta1::AnnotateTextRequest::Features#extract_entities AnnotateTextRequest.Features.extract_entities}.
# @!attribute [rw] document_sentiment
# @return [::Google::Cloud::Language::V1beta1::Sentiment]
# The overall sentiment for the document. Populated if the user enables
# {::Google::Cloud::Language::V1beta1::AnnotateTextRequest::Features#extract_document_sentiment AnnotateTextRequest.Features.extract_document_sentiment}.
# @!attribute [rw] language
# @return [::String]
# The language of the text, which will be the same as the language specified
# in the request or, if not specified, the automatically-detected language.
# See {::Google::Cloud::Language::V1beta1::Document#language Document.language}
# field for more details.
class AnnotateTextResponse
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# Represents the text encoding that the caller uses to process the output.
# Providing an `EncodingType` is recommended because the API provides the
# beginning offsets for various outputs, such as tokens and mentions, and
# languages that natively use different text encodings may access offsets
# differently.
module EncodingType
# If `EncodingType` is not specified, encoding-dependent information (such as
# `begin_offset`) will be set at `-1`.
NONE = 0
# Encoding-dependent information (such as `begin_offset`) is calculated based
# on the UTF-8 encoding of the input. C++ and Go are examples of languages
# that use this encoding natively.
UTF8 = 1
# Encoding-dependent information (such as `begin_offset`) is calculated based
# on the UTF-16 encoding of the input. Java and Javascript are examples of
# languages that use this encoding natively.
UTF16 = 2
# Encoding-dependent information (such as `begin_offset`) is calculated based
# on the UTF-32 encoding of the input. Python is an example of a language
# that uses this encoding natively.
UTF32 = 3
end
end
end
end
end
| 32.761663 | 165 | 0.555862 |
62ca297afaa4ff008979b3b64c97f4e366a812c0 | 823 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v6/resources/income_range_view.proto
require 'google/protobuf'
require 'google/api/field_behavior_pb'
require 'google/api/resource_pb'
require 'google/api/annotations_pb'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/ads/googleads/v6/resources/income_range_view.proto", :syntax => :proto3) do
add_message "google.ads.googleads.v6.resources.IncomeRangeView" do
optional :resource_name, :string, 1
end
end
end
module Google
module Ads
module GoogleAds
module V6
module Resources
IncomeRangeView = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v6.resources.IncomeRangeView").msgclass
end
end
end
end
end
| 29.392857 | 146 | 0.750911 |
ac36fdec0148a4e6163d11f2d61e8b07530a7910 | 1,161 | module HealthDataStandards
module Import
module C32
class ImmunizationImporter < CDA::SectionImporter
def initialize(entry_finder=CDA::EntryFinder.new("//cda:section[cda:templateId/@root='2.16.840.1.113883.3.88.11.83.117']/cda:entry/cda:substanceAdministration"))
super(entry_finder)
@code_xpath = "./cda:consumable/cda:manufacturedProduct/cda:manufacturedMaterial/cda:code"
@description_xpath = "./cda:consumable/cda:manufacturedProduct/cda:manufacturedMaterial/cda:code/cda:originalText/cda:reference[@value]"
@entry_class = Immunization
end
def create_entry(entry_element, nrh = CDA::NarrativeReferenceHandler.new)
immunization = super
extract_negation(entry_element, immunization)
extract_performer(entry_element, immunization)
immunization
end
private
def extract_performer(parent_element, immunization)
performer_element = parent_element.at_xpath("./cda:performer")
immunization.performer = import_actor(performer_element) if performer_element
end
end
end
end
end | 40.034483 | 169 | 0.699397 |
ab8504c25bc5d6af3a1280454b058635967a048f | 298 | module Spree
StoreController.class_eval do
# Check if all products in cart are still live.
# Also, delete line item if any of the products from cart is expired.
def check_active_products_in_order
current_order.delete_inactive_items unless current_order.nil?
end
end
end
| 24.833333 | 73 | 0.755034 |
18bde5dd897a3fda180b80f328f82fc286bdaa48 | 17,333 | require 'formula'
# This is a non-functional example formula to showcase all features and
# therefore, its overly complex and dupes stuff just to comment on it.
# You may want to use `brew create` to start your own new formula!
# Documentation: https://github.com/Homebrew/homebrew/wiki/Formula-Cookbook
## Naming -- Every Homebrew formula is a class of the type `Formula`.
# Ruby classes have to start Upper case and dashes are not allowed.
# So we transform: `example-formula.rb` into `ExampleFormula`. Further,
# Homebrew does enforce that the name of the file and the class correspond.
# Check with `brew search` that the name is free. A file may contain multiple
# classes (we call them sub-formulae) but the main one is the class that
# corresponds to the filename.
class ExampleFormula < Formula
homepage 'http://www.example.com' # used by `brew home example-formula`.
# The url of the archive. Prefer https (security and proxy issues):
url 'https://packed.sources.and.we.prefer.https.example.com/archive-1.2.3.tar.bz2'
mirror 'https://in.case.the.host.is.down.example.com' # `mirror` is optional.
# Optionally specify the download strategy `:using => ...`
# `:git`, `:hg`, `:svn`, `:bzr`, `:cvs`,
# `:curl` (normal file download. Will also extract.)
# `:nounzip` (without extracting)
# `:post` (download via an HTTP POST)
# `S3DownloadStrategy` (download from S3 using signed request)
# `UnsafeSubversionDownloadStrategy` (svn with invalid certs)
url 'https://some.dont.provide.archives.example.com', :using => :git, :tag => '1.2.3'
# version is seldom needed, because its usually autodetected from the URL/tag.
version '1.2-final'
# For integrity and security, we verify the hash (`openssl dgst -sha1 <FILE>`)
# You may also use sha256 if the software uses sha256 on their homepage.
# Leave it empty at first and `brew install` will tell you the expected.
sha1 'cafebabe78901234567890123456789012345678'
# Optionally, specify a repository to be used. Brew then generates a
# `--HEAD` option. Remember to also test it.
# The download strategies (:using =>) are the same as for `url`.
head 'https://we.prefer.https.over.git.example.com/.git'
head 'https://example.com/.git', :branch => 'name_of_branch', :revision => 'abc123'
head 'https://hg.is.awesome.but.git.has.won.example.com/', :using => :hg # If autodetect fails.
# The optional devel block is only executed if the user passes `--devel`.
# Use this to specify a not-yet-released version of a software.
devel do
url 'https://example.com/archive-2.0-beta.tar.gz'
sha1 '1234567890123456789012345678901234567890'
end
## Options
# Options can be used as arguemnts to `brew install`.
# To switch features on/off: `'enable-something'` or `'disable-otherthing'`.
# To use another software: `'with-other-software'` or `'without-foo'`
# Note, that for dependencies that are `:optional` or `:recommended`, options
# are generated automatically.
# Build a universal (On newer intel Macs this means a combined 32bit and
# 64bit binary/library). Todo: better explain what this means for PPC.
option :universal
option 'enable-spam', 'The description goes here without a dot at the end'
option 'with-qt', 'Text here overwrites the autogenerated one from `depends_on "qt"`'
# Only show an option if the Command Line Tools are installed:
option 'with-dtrace', 'Experimental DTrace support' if MacOS::CLT.installed?
## Bottles
# Bottles are pre-built and added by the Homebrew maintainers for you.
# If you maintain your own repository, you can add your own bottle links.
# Read in the wiki about how to provide bottles:
# <https://github.com/Homebrew/homebrew/wiki/Bottles>
bottle do
root_url 'http://mikemcquaid.com' # Optional root to calculate bottle URLs
prefix '/opt/homebrew' # Optional HOMEBREW_PREFIX in which the bottles were built.
cellar '/opt/homebrew/Cellar' # Optional HOMEBREW_CELLAR in which the bottles were built.
revision 1 # Making the old bottle outdated without bumping the version of the formula.
sha1 'd3d13fe6f42416765207503a946db01378131d7b' => :mountain_lion
sha1 'cdc48e79de2dee796bb4ba1ad987f6b35ce1c1ee' => :lion
sha1 'a19b544c8c645d7daad1d39a070a0eb86dfe9b9c' => :snow_leopard
sha1 '583dc9d98604c56983e17d66cfca2076fc56312b' => :snow_leopard_32
end
def pour_bottle?
# Only needed if this formula has to check if using the pre-built
# bottle is fine.
true
end
## keg_only
# Software that will not be sym-linked into the `brew --prefix` will only
# live in it's Cellar. Other formulae can depend on it and then brew will
# add the necessary includes and libs (etc.) during the brewing of that
# other formula. But generally, keg_only formulae are not in your PATH
# and not seen by compilers if you build your own software outside of
# Homebrew. This way, we don't shadow software provided by OS X.
keg_only :provided_by_osx
keg_only "because I want it so"
## Dependencies
# The dependencies for this formula. Use strings for the names of other
# formulae. Homebrew provides some :special dependencies for stuff that
# requires certain extra handling (often changing some ENV vars or
# deciding if to use the system provided version or not.)
# `:build` means this dep is only needed during build.
depends_on 'cmake' => :build
# Explictly name formulae in other taps.
depends_on 'homebrew/dupes/tcl-tk'
# `:recommended` dependencies are built by default. But a `--without-...`
# option is generated to opt-out.
depends_on 'readline' => :recommended
# `:optional` dependencies are NOT built by default but a `--with-...`
# options is generated.
depends_on 'glib' => :optional
# If you need to specify that another formula has to be built with/out
# certain options (note, no `--` needed before the option):
depends_on 'zeromq' => 'with-pgm'
depends_on 'qt' => ['with-qtdbus', 'developer'] # Multiple options.
# Optional and enforce that boost is built with `--with-c++11`.
depends_on 'boost' => [:optional, 'with-c++11']
# If a dependency is only needed in certain cases:
depends_on 'sqlite' if MacOS.version == :leopard
depends_on :xcode # If the formula really needs full Xcode.
depends_on :clt # If the formula really needs the CLTs for Xcode.
depends_on :tex # Homebrew does not provide a Tex Distribution.
depends_on :fortran # Checks that `gfortran` is available or `FC` is set.
depends_on :mpi => :cc # Needs MPI with `cc`
depends_on :mpi => [:cc, :cxx, :optional] # Is optional. MPI with `cc` and `cxx`.
depends_on :macos => :lion # Needs at least Mac OS X "Lion" aka. 10.7.
depends_on :arch => :intel # If this formula only builds on intel architecture.
depends_on :arch => :x86_64 # If this formula only build on intel x86 64bit.
depends_on :arch => :ppc # Only builds on PowerPC?
depends_on :ld64 # Sometimes ld fails on `MacOS.version < :leopard`. Then use this.
depends_on :x11 # X11/XQuartz components.
depends_on :libpng # Often, not all of X11 is needed.
depends_on :fontconfig
# autoconf/automake is sometimes needed for --HEAD checkouts:
depends_on :autoconf if build.head?
depends_on :automake if build.head?
depends_on :bsdmake
depends_on :libtool
depends_on :libltdl
depends_on :mysql => :recommended
depends_on :cairo if build.devel?
depends_on :pixman if build.devel?
# It is possible to only depend on something if
# `build.with?` or `build.without? 'another_formula'`:
depends_on :mysql # allows brewed or external mysql to be used
depends_on :postgresql if build.without? 'sqlite'
depends_on :hg # Mercurial (external or brewed) is needed
# If any Python >= 2.6 < 3.x is okay (either from OS X or brewed):
depends_on :python
# Python 3.x if the `--with-python3` is given to `brew install example`
depends_on :python3 => :optional
# Modules/Packages from other languages, such as :chicken, :jruby, :lua,
# :node, :ocaml, :perl, :python, :rbx, :ruby, can be specified by
depends_on 'some_module' => :lua
## Conflicts
# If this formula conflicts with another one:
conflicts_with 'imagemagick', :because => 'because this is just a stupid example'
## Failing with a certain compiler?
# If it is failing for certain compiler:
fails_with :llvm do # :llvm is really llvm-gcc
build 2334
cause "Segmentation fault during linking."
end
fails_with :clang do
build 425
cause 'multiple configure and compile errors'
end
## Patches
# Optionally define a `patches` method returning `DATA` and/or a string with
# the url to a patch or a list thereof.
def patches
# DATA is the embedded diff that comes after __END__ in this file!
# In this example we only need the patch for older clang than 425:
DATA unless MacOS.clang_build_version >= 425
end
# More than the one embedded patch? Use a dict with keys :p0, :p1 and/or
# p2: as you need, for example:
def patches
{:p0 => [
'https://trac.macports.org/export/yeah/we/often/steal/a/patch.diff',
'https://github.com/example/foobar/commit/d46a8c6265c4c741aaae2b807a41ea31bc097052.diff',
DATA ],
# For gists, please use the link to a specific hash, so nobody can change it unnoticed.
:p2 => ['https://raw.github.com/gist/4010022/ab0697dc87a40e65011e2192439609c17578c5be/tags.patch']
}
end
## The install method.
def install
# Now the sources (from `url`) are downloaded, hash-checked and
# Homebrew has changed into a temporary directory where the
# archive has been unpacked or the repository has been cloned.
# Print a warning (do this rarely)
opoo 'Dtrace features are experimental!' if build.with? 'dtrace'
# Sometimes we have to change a bit before we install. Mostly we
# prefer a patch but if you need the `prefix` of this formula in the
# patch you have to resort to `inreplace`, because in the patch
# you don't have access to any var defined by the formula. Only
# HOMEBREW_PREFIX is available in the embedded patch.
# inreplace supports reg. exes.
inreplace 'somefile.cfg', /look[for]what?/, "replace by #{bin}/tool"
# To call out to the system, we use the `system` method and we prefer
# you give the args separately as in the line below, otherwise a subshell
# has to be opened first.
system "./bootstrap.sh", "--arg1", "--prefix=#{prefix}"
# For Cmake, we have some necessary defaults in `std_cmake_args`:
system "cmake", ".", *std_cmake_args
# If the arguments given to configure (or make or cmake) are depending
# on options defined above, we usually make a list first and then
# use the `args << if <condition>` to append to:
args = ["--option1", "--option2"]
args << "--i-want-spam" if build.include? "enable-spam"
args << "--qt-gui" if build.with? "qt" # "--with-qt" ==> build.with? "qt"
args << "--some-new-stuff" if build.head? # if head is used instead of url.
args << "--universal-binary" if build.universal?
# The `build.with?` and `build.without?` are smart enough to do the
# right thing™ with respect to defaults defined via `:optional` and
# `:recommended` dependencies.
# If you need to give the path to lib/include of another brewed formula
# please use the `opt_prefix` instead of the `prefix` of that other
# formula. The reasoning behind this is that `prefix` has the exact
# version number and if you update that other formula, things might
# break if they remember that exact path. In contrast to that, the
# `$(brew --prefix)/opt/formula` is the same path for all future
# versions of the formula!
args << "--with-readline=#{Formula.factory('readline').opt_prefix}/lib" if build.with? "readline"
# Most software still uses `configure` and `make`.
# Check with `./configure --help` what our options are.
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--prefix=#{prefix}",
*args # our custom arg list (needs `*` to unpack)
# If your formula's build system is not thread safe:
ENV.deparallelize
# A general note: The commands here are executed line by line, so if
# you change some variable or call a method like ENV.deparallelize, it
# only affects the lines after that command.
# Do something only for clang
if ENV.compiler == :clang
# modify CFLAGS CXXFLAGS OBJCFLAGS OBJCXXFLAGS in one go:
ENV.append_to_cflags '-I ./missing/includes'
end
# This is in general not necessary, but to show how to find the path to
# the Mac OS X SDK:
ENV.append 'CPPFLAGS', "-I#{MacOS.sdk_path}/usr/include" unless MacOS::CLT.installed?
# Overwriting any env var:
ENV['LDFLAGS'] = '--tag CC'
system "make", "install"
# We are in a temporary directory and don't have to care about cleanup.
# Instead of `system "cp"` or something, call `install` on the Pathname
# objects as they are smarter with respect to correcting access rights.
# (`install` is a Homebrew mixin into Ruby's Pathname)
# The pathnames defined in the formula
prefix # == HOMEBREW_PREFIX+'Cellar'+name+version
bin # == prefix+'bin'
doc # == share+'doc'+name
include # == prefix+'include'
info # == share+'info'
lib # == prefix+'lib'
libexec # == prefix+'libexec'
man # share+'man'
man1 # man+'man1'
man2 # man+'man2'
man3 # man+'man3'
man4 # man+'man4'
man5 # man+'man5'
man6 # man+'man6'
man7 # man+'man7'
man8 # man+'man8'
sbin # prefix+'sbin'
share # prefix+'share'
frameworks # prefix+'Frameworks'
kext_prefix # prefix+'Library/Extensions'
# Configuration stuff that will survive formula updates
etc # HOMEBREW_PREFIX+'etc'
# Generally we don't want var stuff inside the keg
var # HOMEBREW_PREFIX+'var'
bash_completion # prefix+'etc/bash_completion.d'
zsh_completion # share+'zsh/site-functions'
# Further possibilities with the pathnames:
# http://www.ruby-doc.org/stdlib-1.8.7/libdoc/pathname/rdoc/Pathname.html
# Sometime you will see that instead of `+` we build up a path with `/`
# because it looks nicer (but you can't nest more than two `/`):
(var/'foo').mkpath
# Copy `./example_code/simple/ones` to share/demos
(share/'demos').install "example_code/simple/ones"
# Copy `./example_code/simple/ones` to share/demos/examples
(share/'demos').install "example_code/simple/ones" => 'examples'
# Additional stuff can be defined in a sub-formula (see below) and
# with a block like this, it will be extracted into its own temporary
# dir. We can install into the Cellar of the main formula easily,
# because `prefix`, `bin` and all the other pre-defined variables are
# from the main formula.
AdditionalStuff.new.brew { bin.install 'my/extra/tool' }
# `name` and `version` are accessible too, if you need them.
end
## Caveats
def caveats
"Are optional. Something the user should know?"
end
def caveats
s = <<-EOS.undent
Print some important notice to the user when `brew info <formula>` is
called or when brewing a formula.
This is optional. You can use all the vars like #{version} here.
EOS
s += "Some issue only on older systems" if MacOS.version < :mountain_lion
s
end
## Test (is optional but makes us happy)
test do
# `test do` will create, run in, and delete a temporary directory.
# We are fine if the executable does not error out, so we know linking
# and building the software was ok.
system bin/'foobar', '--version'
(testpath/'Test.file').write <<-EOS.undent
writing some test file, if you need to
EOS
# To capture the output of a command, we use backtics:
assert_equal 'OK', ` test.file`.strip
# Need complete control over stdin, stdout?
require 'open3'
Open3.popen3("#{bin}/example", "big5:utf-8") do |stdin, stdout, _|
stdin.write("\263\134\245\134\273\134")
stdin.close
assert_equal "許功蓋", stdout.read
end
# If an exception is raised (e.g. by assert), or if we return false, or if
# the command run by `system` prints to stderr, we consider the test failed.
end
## Plist handling
# Define this method to provide a plist.
# Todo: Expand this example with a little demo plist? I dunno.
# There is more to startup plists. Help, I suck a plists!
def plist; nil; end
end
class AdditionalStuff < Formula
# Often, a second formula is used to download some resource
# NOTE: This is going to change when https://github.com/Homebrew/homebrew/pull/21714 happens.
url 'https://example.com/additional-stuff.tar.gz'
sha1 'deadbeef7890123456789012345678901234567890'
end
__END__
# Room for a patch after the `__END__`
# Read in the wiki about how to get a patch in here:
# https://github.com/Homebrew/homebrew/wiki/Formula-Cookbook
# In short, `brew install --interactive --git <formula>` and make your edits.
# Then `git diff >> path/to/your/formula.rb`
# Note, that HOMEBREW_PREFIX will be replaced in the path before it is
# applied. A patch can consit of several hunks.
| 42.070388 | 103 | 0.69711 |
7abf87fced6350dbdb1a06cdcebc33199a63fc8f | 25 | module AccueilHelper
end
| 8.333333 | 20 | 0.88 |
e2652733c69b149cd6d43f9b0f2616c0ef170519 | 589 | require 'mysqlcnfparse/lines'
require 'mysqlcnfparse/generator'
module MysqlCnfParse
class Parser < IniParse::Parser
self.parse_types = self.parse_types + [ MysqlCnfParse::Lines::Include, MysqlCnfParse::Lines::IncludeDir ]
# Parses the source string and returns the resulting data structure.
#
# ==== Returns
# IniParse::Document
#
def parse
MysqlCnfParse::Generator.gen do |generator|
@source.split("\n", -1).each do |line|
generator.send(*Parser.parse_line(line))
end
end
end
end # Parser
end # MysqlCnfParse
| 24.541667 | 109 | 0.66893 |
286aee65bcaab634c85a05168ef470eff3b3aaf8 | 190 | =begin
Write your code for the 'House' exercise in this file. Make the tests in
`house_test.rb` pass.
To get started with TDD, see the `README.md` file in your
`ruby/house` directory.
=end
| 23.75 | 72 | 0.742105 |
1ca9b2cf92770c6bf7f796cd91ecad8f8682dfd7 | 7,709 | =begin
#OpenLattice API
#OpenLattice API
The version of the OpenAPI document: 0.0.1
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.0.0-SNAPSHOT
=end
require 'date'
module OpenapiClient
class DataSetColumn
attr_accessor :id
attr_accessor :data_set_id
attr_accessor :name
attr_accessor :organization_id
attr_accessor :data_type
attr_accessor :metadata
attr_accessor :acl_key
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'id' => :'id',
:'data_set_id' => :'dataSetId',
:'name' => :'name',
:'organization_id' => :'organizationId',
:'data_type' => :'dataType',
:'metadata' => :'metadata',
:'acl_key' => :'aclKey'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'id' => :'String',
:'data_set_id' => :'String',
:'name' => :'String',
:'organization_id' => :'String',
:'data_type' => :'String',
:'metadata' => :'SecurableObjectMetadataUpdate',
:'acl_key' => :'Array<String>'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::DataSetColumn` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::DataSetColumn`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'id')
self.id = attributes[:'id']
end
if attributes.key?(:'data_set_id')
self.data_set_id = attributes[:'data_set_id']
end
if attributes.key?(:'name')
self.name = attributes[:'name']
end
if attributes.key?(:'organization_id')
self.organization_id = attributes[:'organization_id']
end
if attributes.key?(:'data_type')
self.data_type = attributes[:'data_type']
end
if attributes.key?(:'metadata')
self.metadata = attributes[:'metadata']
end
if attributes.key?(:'acl_key')
if (value = attributes[:'acl_key']).is_a?(Array)
self.acl_key = value
end
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
id == o.id &&
data_set_id == o.data_set_id &&
name == o.name &&
organization_id == o.organization_id &&
data_type == o.data_type &&
metadata == o.metadata &&
acl_key == o.acl_key
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[id, data_set_id, name, organization_id, data_type, metadata, acl_key].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
elsif attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
end
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
OpenapiClient.const_get(type).build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 29.090566 | 206 | 0.60812 |
bf6bc5bf1144631826e245671b5e9bec21e4cec9 | 5,031 | require "byebug"
require_relative "../lib/circuitdata"
require_relative "./support/fixture_helpers"
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
config.include(FixtureHelpers)
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
| 47.914286 | 92 | 0.743987 |
1ac89033b13fee1875924d101d36aef6f07223c5 | 906 | #
# Cookbook:: chef-yum-docker
# Recipe:: default
#
# Copyright:: 2016-2017, Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
%w(
docker-stable
docker-edge
docker-test
).each do |repo|
yum_repository repo do
node['yum'][repo].each do |config, value|
send(config.to_sym, value) unless value.nil? || config == 'managed'
end
end if node['yum'][repo]['managed']
end
| 29.225806 | 74 | 0.717439 |
f73871b7e445c96722058adb1d3b97deb45ebf9d | 6,963 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe RateLimitedService do
let(:key) { :issues_create }
let(:scope) { [:project, :current_user] }
let(:opts) { { scope: scope, users_allowlist: -> { [User.support_bot.username] } } }
let(:rate_limiter_klass) { ::Gitlab::ApplicationRateLimiter }
let(:rate_limiter_instance) { rate_limiter_klass.new(key, **opts) }
describe 'RateLimitedError' do
subject { described_class::RateLimitedError.new(key: key, rate_limiter: rate_limiter_instance) }
describe '#headers' do
it 'returns a Hash of HTTP headers' do
# TODO: This will be fleshed out in https://gitlab.com/gitlab-org/gitlab/-/issues/342370
expected_headers = {}
expect(subject.headers).to eq(expected_headers)
end
end
describe '#log_request' do
it 'logs the request' do
request = instance_double(Grape::Request)
user = instance_double(User)
expect(rate_limiter_klass).to receive(:log_request).with(request, "#{key}_request_limit".to_sym, user)
subject.log_request(request, user)
end
end
end
describe 'RateLimiterScopedAndKeyed' do
subject { described_class::RateLimiterScopedAndKeyed.new(key: key, opts: opts, rate_limiter_klass: rate_limiter_klass) }
describe '#rate_limit!' do
let(:project_with_feature_enabled) { create(:project) }
let(:project_without_feature_enabled) { create(:project) }
let(:project) { nil }
let(:current_user) { create(:user) }
let(:service) { instance_double(Issues::CreateService, project: project, current_user: current_user) }
let(:evaluated_scope) { [project, current_user] }
let(:evaluated_opts) { { scope: evaluated_scope, users_allowlist: %w[support-bot] } }
let(:rate_limited_service_issues_create_feature_enabled) { nil }
before do
allow(rate_limiter_klass).to receive(:new).with(key, **evaluated_opts).and_return(rate_limiter_instance)
stub_feature_flags(rate_limited_service_issues_create: rate_limited_service_issues_create_feature_enabled)
end
shared_examples 'a service that does not attempt to throttle' do
it 'does not attempt to throttle' do
expect(rate_limiter_instance).not_to receive(:throttled?)
expect(subject.rate_limit!(service)).to be_nil
end
end
shared_examples 'a service that does attempt to throttle' do
before do
allow(rate_limiter_instance).to receive(:throttled?).and_return(throttled)
end
context 'when rate limiting is not in effect' do
let(:throttled) { false }
it 'does not raise an exception' do
expect(subject.rate_limit!(service)).to be_nil
end
end
context 'when rate limiting is in effect' do
let(:throttled) { true }
it 'raises a RateLimitedError exception' do
expect { subject.rate_limit!(service) }.to raise_error(described_class::RateLimitedError, 'This endpoint has been requested too many times. Try again later.')
end
end
end
context 'when :rate_limited_service_issues_create feature is globally disabled' do
let(:rate_limited_service_issues_create_feature_enabled) { false }
it_behaves_like 'a service that does not attempt to throttle'
end
context 'when :rate_limited_service_issues_create feature is globally enabled' do
let(:throttled) { nil }
let(:rate_limited_service_issues_create_feature_enabled) { true }
let(:project) { project_without_feature_enabled }
it_behaves_like 'a service that does attempt to throttle'
end
context 'when :rate_limited_service_issues_create feature is enabled for project_with_feature_enabled' do
let(:throttled) { nil }
let(:rate_limited_service_issues_create_feature_enabled) { project_with_feature_enabled }
context 'for project_without_feature_enabled' do
let(:project) { project_without_feature_enabled }
it_behaves_like 'a service that does not attempt to throttle'
end
context 'for project_with_feature_enabled' do
let(:project) { project_with_feature_enabled }
it_behaves_like 'a service that does attempt to throttle'
end
end
end
end
describe '#execute_without_rate_limiting' do
let(:rate_limiter_scoped_and_keyed) { instance_double(RateLimitedService::RateLimiterScopedAndKeyed) }
let(:subject) do
local_key = key
local_opts = opts
Class.new do
prepend RateLimitedService
rate_limit key: local_key, opts: local_opts
def execute(*args, **kwargs)
'main logic here'
end
end.new
end
before do
allow(RateLimitedService::RateLimiterScopedAndKeyed).to receive(:new).with(key: key, opts: opts, rate_limiter_klass: rate_limiter_klass).and_return(rate_limiter_scoped_and_keyed)
end
context 'bypasses rate limiting' do
it 'calls super' do
expect(rate_limiter_scoped_and_keyed).not_to receive(:rate_limit!).with(subject)
expect(subject.execute_without_rate_limiting).to eq('main logic here')
end
end
end
describe '#execute' do
context 'when rate_limit has not been called' do
let(:subject) { Class.new { prepend RateLimitedService }.new }
it 'raises an RateLimitedNotSetupError exception' do
expect { subject.execute }.to raise_error(described_class::RateLimitedNotSetupError)
end
end
context 'when rate_limit has been called' do
let(:rate_limiter_scoped_and_keyed) { instance_double(RateLimitedService::RateLimiterScopedAndKeyed) }
let(:subject) do
local_key = key
local_opts = opts
Class.new do
prepend RateLimitedService
rate_limit key: local_key, opts: local_opts
def execute(*args, **kwargs)
'main logic here'
end
end.new
end
before do
allow(RateLimitedService::RateLimiterScopedAndKeyed).to receive(:new).with(key: key, opts: opts, rate_limiter_klass: rate_limiter_klass).and_return(rate_limiter_scoped_and_keyed)
end
context 'and applies rate limiting' do
it 'raises an RateLimitedService::RateLimitedError exception' do
expect(rate_limiter_scoped_and_keyed).to receive(:rate_limit!).with(subject).and_raise(RateLimitedService::RateLimitedError.new(key: key, rate_limiter: rate_limiter_instance))
expect { subject.execute }.to raise_error(RateLimitedService::RateLimitedError)
end
end
context 'but does not apply rate limiting' do
it 'calls super' do
expect(rate_limiter_scoped_and_keyed).to receive(:rate_limit!).with(subject).and_return(nil)
expect(subject.execute).to eq('main logic here')
end
end
end
end
end
| 35.345178 | 186 | 0.691369 |
7998dd840a926fa4be4999799c7517a6aaf46f20 | 1,634 | require File.dirname(__FILE__) + '/test_helper.rb'
module Ubiquitously
class DiggTest < ActiveSupport::TestCase
=begin
context "Digg::Account" do
setup do
@user = Ubiquitously::Digg::Account.new
end
context "login" do
should "raise informative error if invalid password" do
@user.password = "bad password"
assert_raises(Ubiquitously::AuthenticationError) do
@user.login
end
end
should "login successfully if valid credentials" do
assert_equal true, @user.login
end
end
end
=end
context "Digg::Post" do
setup do
@user = Ubiquitously::User.new(
:username => "viatropos",
:cookies_path => "test/cookies.yml"
)
@title = "Viatropos"
@description = "Creativity and Emergence. A personal blog about writing code that the world can leverage."
@tags = %w(jquery html-5 css3 ajax ruby-on-rails ruby-on-rails-developer ruby-on-rails-examples rails-deployment flex actionscript flash open-source)
@post = Ubiquitously::Post.new(
:url => "./test/meta.html",
:title => @title,
:description => @description,
:tags => @tags,
:user => @user
)
end
should "find pre-existent post on digg" do
@post.url = "http://google.com"
result = @post.new_record?(:digg)
assert result
end
should "create a post" do
@post.url = "http://apple.com"
assert @post.save(:digg)
end
end
end
end
| 28.172414 | 157 | 0.574051 |
ace822d4520339dc1bfb32d1b288e4ca777968f4 | 964 | require 'rubygems'
require 'bundler'
Bundler.setup
require 'active_support'
require File.dirname(__FILE__) + '/scalr/response'
require File.dirname(__FILE__) + '/scalr/request'
require File.dirname(__FILE__) + '/scalr/core_extensions/hash'
require File.dirname(__FILE__) + '/scalr/core_extensions/http'
module Scalr
mattr_accessor :endpoint
@@endpoint = "api.scalr.net"
mattr_accessor :key_id
@@key_id = nil
mattr_accessor :access_key
@@access_key = nil
mattr_accessor :version
@@version = "2.0.0"
class << self
def method_missing(method_id, *arguments)
if matches_action? method_id
request = Scalr::Request.new(method_id, @@endpoint, @@key_id, @@access_key, @@version, arguments)
return request.process!
else
super
end
end
private
def matches_action?(method_id)
Scalr::Request::ACTIONS.keys.include? method_id.to_sym
end
end
end
| 21.422222 | 105 | 0.674274 |
2614b4635bc577abdd9593291e5d4340bab95f69 | 1,341 | require 'experian'
require 'minitest/autorun'
require 'minitest/pride'
require 'webmock/minitest'
require 'mocha/setup'
require 'timecop'
def fixture_path
File.expand_path("../fixtures", __FILE__)
end
def fixture(product, file)
File.read("#{fixture_path}/#{product}/#{file}")
end
def stub_experian_uri_lookup
Experian.user, Experian.password = 'user', 'password'
stub_request(:get, Experian.ecals_uri.to_s).to_return(body: "http://fake.experian.com", status: 200)
end
def stub_experian_request(product, file, status = 200)
stub_experian_uri_lookup
stub_request(:post, "http://user:[email protected]").to_return(body: fixture(product, file), status: status)
stub_request(:post, "https://user:[email protected]/fraudsolutions/xmlgateway/preciseid").to_return(body: fixture(product, file), status: status)
end
def stub_password_reset(status = 200)
stub_request(:post, "https://user:[email protected]/securecontrol/reset/passwordreset").
to_return(:status => status, :body => "", :headers => {})
end
Experian.configure do |config|
config.eai = "X42PB93F"
config.preamble = "FCD2"
config.op_initials = "AB"
config.subcode = "1968543"
config.user = "user"
config.password = "password"
config.vendor_number = "P55"
config.test_mode = true
config.proxy = 'http://example.com'
end
| 31.186047 | 155 | 0.740492 |
bbda44afdd317ad2d4bd2873f79bf2314847851f | 1,165 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module App
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.web_console.whitelisted_ips = '172.0.0.0/0'
end
end
| 41.607143 | 99 | 0.73133 |
79c8ce550c8d652000041b003c95c13e23a7a927 | 192 | module Byebug
#
# Common parent class for all of Byebug's states
#
class State
attr_reader :interface
def initialize(interface)
@interface = interface
end
end
end
| 14.769231 | 50 | 0.671875 |
ab2be835c0f800e9ca4b2f2bfb1a3a4515b1644a | 137 | # encoding: UTF-8
# frozen_string_literal: true
Date::DATE_FORMATS[:short] = '%m-%d'
Time::DATE_FORMATS[:default] = "%Y-%m-%d %H:%M:%S"
| 22.833333 | 50 | 0.649635 |
ed8f60604cc7cb105c8f085ead51b14c7c063e6d | 1,722 | class Moc < Formula
desc "Terminal-based music player"
homepage "http://moc.daper.net"
url "http://ftp.daper.net/pub/soft/moc/stable/moc-2.5.0.tar.bz2"
sha256 "d29ea52240af76c4aa56fa293553da9d66675823e689249cee5f8a60657a6091"
bottle do
revision 1
sha256 "3188a4355200b250e6a63c909c6ef8a7a458e25377a6a17d6f62455072b38e40" => :yosemite
sha256 "ccfd6919a5d64861ecc66f6ad01e8b4f259295dbe3772b459bb139ab0908b2e0" => :mavericks
sha256 "94cca91c117a1575aa61a10f288e95672e61bfe0c1d473b2fac70c480c0d92ab" => :mountain_lion
end
head do
url "svn://daper.net/moc/trunk"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "gettext" => :build
end
option "with-ncurses", "Build with wide character support."
depends_on "pkg-config" => :build
depends_on "libtool" => :run
depends_on "berkeley-db"
depends_on "jack"
depends_on "ffmpeg" => :recommended
depends_on "mad" => :optional
depends_on "flac" => :optional
depends_on "speex" => :optional
depends_on "musepack" => :optional
depends_on "libsndfile" => :optional
depends_on "wavpack" => :optional
depends_on "faad2" => :optional
depends_on "timidity" => :optional
depends_on "libmagic" => :optional
depends_on "homebrew/dupes/ncurses" => :optional
def install
system "autoreconf", "-fvi" if build.head?
system "./configure", "--disable-debug", "--prefix=#{prefix}"
system "make", "install"
end
def caveats
<<-EOS.undent
You must start the jack daemon prior to running mocp.
If you need wide-character support in the player, for example
with Chinese characters, you can install using
--with-ncurses
EOS
end
end
| 31.309091 | 95 | 0.708479 |
08e28dd86f3615bd74e3bae0d5aa04653841c99e | 1,421 | class Torchvision < Formula
desc "Datasets, transforms, and models for computer vision"
homepage "https://github.com/pytorch/vision"
url "https://github.com/pytorch/vision/archive/v0.9.1.tar.gz"
sha256 "79964773729880e0eee0e6af13f336041121d4cc8491a3e2c0e5f184cac8a718"
license "BSD-3-Clause"
revision 1
bottle do
sha256 cellar: :any, big_sur: "7271571ca3225e67248db0c57517149d7c7ab44f83356533daf14c6d4bcc908b"
sha256 cellar: :any, catalina: "bffc19f93cd4f9b8ac39f0297747358fd6d573755b1585f8e553791bb115a9da"
sha256 cellar: :any, mojave: "b51b1077faf60c5a9795e239a168330ef25db8852e0277a1de745cc3dbfd1a53"
end
depends_on "cmake" => :build
depends_on "jpeg"
depends_on "libpng"
depends_on "libtorch"
depends_on "[email protected]"
def install
mkdir "build" do
system "cmake", "..", *std_cmake_args
system "make"
system "make", "install"
end
pkgshare.install "examples"
end
test do
cp pkgshare/"examples/cpp/hello_world/main.cpp", testpath
libtorch = Formula["libtorch"]
system ENV.cxx, "-std=c++14", "main.cpp", "-o", "test",
"-I#{libtorch.opt_include}",
"-I#{libtorch.opt_include}/torch/csrc/api/include",
"-L#{libtorch.opt_lib}", "-ltorch", "-ltorch_cpu", "-lc10",
"-L#{lib}", "-ltorchvision"
assert_match "[1, 1000]", shell_output("./test")
end
end
| 34.658537 | 101 | 0.676988 |
18a6d30b6ef19db6d1be77a7e60ac0b0a97ad7fb | 1,447 | module HomeHelper
def render_team
content = ''
@team.each_slice(6) do |row|
content << render_team_members(row)
end
return content.html_safe
end
def render_alumni
content = ''
@alumni.each_slice(6) do |row|
content << render_alumni_rows(row)
end
return content.html_safe
end
private
def render_team_members(row)
enum = row.map #create an enumerator for the row array
content_tag('div', :id => 'team-row', :class => 'row') do
row.map do |person|
if enum.find_index(person)+1 == row.length and row.length > 1
content_tag('div', render_team_member(person), {:class => ['column', 'two', 'mobile-two'], :style=>"float:left"})
else
content_tag('div', render_team_member(person), :class => ['column', 'two', 'mobile-two'])
end
end.join.html_safe
end
end
def render_alumni_rows(row)
enum = row.map #create an enumerator for the row array
content_tag('div', :id => 'alumni-row', :class => 'row') do
row.map do |person|
if enum.find_index(person)+1 == row.length and row.length > 1
content_tag('div', render_team_member(person), {:class => ['column', 'two', 'mobile-two'], :style=>"float:left"})
else
content_tag('div', render_team_member(person), :class => ['column', 'two', 'mobile-two'])
end
end.join.html_safe
end
end
def render_team_member(person)
render(:partial => "home/team_member", :layout => false, :locals => {:person => person})
end
end | 29.530612 | 118 | 0.664133 |
38e7e249fa73344d1aeaddb7dc1492a8a6fa2627 | 274 | # This migration comes from almanac (originally 20121114043648)
class ChangeDefaultValueForBackgroundTilesInAlmanacBlogs < ActiveRecord::Migration
def self.up
change_column :almanac_blogs, :background_tile, :boolean, :default => true
end
def self.down
end
end
| 24.909091 | 82 | 0.791971 |
ab42573fdc271fbd04d0694ead6093feab7effa1 | 1,357 | #-- encoding: UTF-8
#-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2017 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See doc/COPYRIGHT.rdoc for more details.
#++
class RenameIssueStatusesToStatuses < ActiveRecord::Migration[4.2]
def change
rename_table :issue_statuses, :statuses
end
end
| 38.771429 | 91 | 0.762712 |
e8339003f4323cc0dcbf7c93fc73596ab22fe31e | 38 | module Quetcd
VERSION = "0.1.0"
end
| 9.5 | 19 | 0.657895 |
62cef603999da80ef1f7229ef853f2df9f4ac8c7 | 7,303 | require "test_helper"
class RBS::EnvironmentTest < Minitest::Test
include TestHelper
Environment = RBS::Environment
Namespace = RBS::Namespace
InvalidTypeApplicationError = RBS::InvalidTypeApplicationError
def test_entry_context
decls = RBS::Parser.parse_signature(<<EOF)
class Foo
module Bar
module Baz
end
end
end
EOF
entry = Environment::SingleEntry.new(
name: type_name("::Foo::Bar::Baz"),
decl: decls[0].members[0].members[0],
outer: [
decls[0],
decls[0].members[0],
]
)
assert_equal [
type_name("::Foo::Bar::Baz").to_namespace,
type_name("::Foo::Bar").to_namespace,
type_name("::Foo").to_namespace,
Namespace.root
],
entry.context
end
def test_insert_decl_nested_modules
env = Environment.new
decls = RBS::Parser.parse_signature(<<EOF)
class Foo
module Bar
end
module ::Baz
end
end
EOF
env << decls[0]
assert_operator env.class_decls, :key?, type_name("::Foo")
assert_operator env.class_decls, :key?, type_name("::Foo::Bar")
assert_operator env.class_decls, :key?, type_name("::Baz")
end
def test_insert_decl_open_class
env = Environment.new
decls = RBS::Parser.parse_signature(<<EOF)
class Foo
module Bar
end
end
class Foo < String
module Bar
end
end
EOF
env << decls[0]
env << decls[1]
env.class_decls[type_name("::Foo")].tap do |entry|
assert_instance_of Environment::ClassEntry, entry
assert_equal 2, entry.decls.size
assert_equal type_name("String"), entry.primary.decl.super_class.name
end
env.class_decls[type_name("::Foo::Bar")].tap do |entry|
assert_instance_of Environment::ModuleEntry, entry
assert_equal 2, entry.decls.size
end
end
def test_insert_decl_const_duplication_error
env = Environment.new
decls = RBS::Parser.parse_signature(<<EOF)
module Foo
end
Bar: ::Integer
Foo: String
class Bar
end
EOF
env << decls[0]
env << decls[1]
assert_raises RBS::DuplicatedDeclarationError do
env << decls[2]
end
assert_raises RBS::DuplicatedDeclarationError do
env << decls[3]
end
end
def test_class_module_mix
env = Environment.new
decls = RBS::Parser.parse_signature(<<EOF)
module Foo
end
class Foo
end
EOF
assert_raises RBS::DuplicatedDeclarationError do
env << decls[0]
env << decls[1]
end
end
def test_const_twice_duplication_error
env = Environment.new
decls = RBS::Parser.parse_signature(<<EOF)
Foo: String
Foo: String
EOF
assert_raises RBS::DuplicatedDeclarationError do
env << decls[0]
env << decls[1]
end
end
def test_generic_class
env = Environment.new
decls = RBS::Parser.parse_signature(<<EOF)
module Foo[A, out B]
end
module Foo[X, out Y] # ok
end
module Foo[A] # # of params mismatch
end
module Foo[X, in Y] # Variance mismatch
end
EOF
# The GenericParameterMismatchError raises on #type_params call
env << decls[0]
env << decls[1]
env << decls[2]
env << decls[3]
end
def test_generic_class_error
decls = RBS::Parser.parse_signature(<<EOF)
module Foo[A, out B]
end
module Foo[X, out Y]
end
module Foo[A]
end
module Foo[X, in Y]
end
EOF
Environment::ModuleEntry.new(name: type_name("::Foo")).tap do |entry|
entry.insert(decl: decls[0], outer: [])
entry.insert(decl: decls[1], outer: [])
assert_instance_of RBS::AST::Declarations::ModuleTypeParams, entry.type_params
end
Environment::ModuleEntry.new(name: type_name("::Foo")).tap do |entry|
entry.insert(decl: decls[0], outer: [])
entry.insert(decl: decls[2], outer: [])
assert_raises RBS::GenericParameterMismatchError do
entry.type_params
end
end
Environment::ModuleEntry.new(name: type_name("::Foo")).tap do |entry|
entry.insert(decl: decls[0], outer: [])
entry.insert(decl: decls[3], outer: [])
assert_raises RBS::GenericParameterMismatchError do
entry.type_params
end
end
end
def test_insert_global
env = Environment.new
decls = RBS::Parser.parse_signature(<<EOF)
$VERSION: String
EOF
env << decls[0]
assert_operator env.global_decls, :key?, :$VERSION
end
def test_module_self_type
decls = RBS::Parser.parse_signature(<<EOF)
interface _Animal
def bark: () -> void
end
module Foo : _Animal
def foo: () -> void
end
module Foo : Object
def bar: () -> void
end
module Bar : _Animal
end
module Bar : _Animal
end
EOF
Environment.new.tap do |env|
env << decls[0]
env << decls[1]
env << decls[2]
foo = env.class_decls[type_name("::Foo")]
assert_equal decls[1], foo.primary.decl
assert_equal [
RBS::AST::Declarations::Module::Self.new(
name: type_name("_Animal"),
args: [],
location: nil
),
RBS::AST::Declarations::Module::Self.new(
name: type_name("Object"),
args: [],
location: nil
),
], foo.self_types
end
Environment.new.tap do |env|
env << decls[0]
env << decls[3]
env << decls[4]
foo = env.class_decls[type_name("::Bar")]
assert_equal decls[3], foo.primary.decl
end
end
def test_absolute_type
env = Environment.new
decls = RBS::Parser.parse_signature(<<EOF)
# Integer is undefined and the type is left relative.
# (Will be an error afterward.)
#
class Hello < String
def hello: (String) -> Integer
end
module Foo : _Each[String]
attr_reader name: String
attr_accessor size: Integer
attr_writer email (@foo): ::String
@created_at: Time
self.@last_timestamp: Time?
@@max_size: Integer
include Enumerable[Integer]
extend _Each[untyped]
prepend Operator
VERSION: ::String
type t = ::String | String
$size: Integer
class String
end
interface _Each[A]
def each: () { (A) -> void } -> void
end
module Operator
end
end
class String end
class Time end
module Enumerable[A] end
EOF
decls.each do |decl|
env << decl
end
env_ = env.resolve_type_names
writer = RBS::Writer.new(out: StringIO.new)
writer.write(env_.declarations)
assert_equal <<RBS, writer.out.string
# Integer is undefined and the type is left relative.
# (Will be an error afterward.)
#
class ::Hello < ::String
def hello: (::String) -> Integer
end
module ::Foo : ::Foo::_Each[::Foo::String]
attr_reader name: ::Foo::String
attr_accessor size: Integer
attr_writer email(@foo): ::String
@created_at: ::Time
self.@last_timestamp: ::Time?
@@max_size: Integer
include ::Enumerable[Integer]
extend ::Foo::_Each[untyped]
prepend ::Foo::Operator
::Foo::VERSION: ::String
type ::Foo::t = ::String | ::Foo::String
$size: Integer
class ::Foo::String
end
interface ::Foo::_Each[A]
def each: () { (A) -> void } -> void
end
module ::Foo::Operator
end
end
class ::String
end
class ::Time
end
module ::Enumerable[A]
end
RBS
end
end
| 18.822165 | 84 | 0.628509 |
e940090d8a02ff2b09cf8d24a1f34b9e01c8f026 | 256 | module Rubybear
module Type
class Hash < Serializer
def initialize(value)
super(:hash, true)
end
def to_bytes
pakHash(@value)
end
def to_s
@value.to_json
end
end
end
end
| 14.222222 | 27 | 0.523438 |
28754e3d7d2e248eba1dc5c7e08ac86ba83e4391 | 469 | require 'rails_helper'
# Specs in this file have access to a helper object that includes
# the MeditationSessionsHelper. For example:
#
# describe MeditationSessionsHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# expect(helper.concat_strings("this","that")).to eq("this that")
# end
# end
# end
RSpec.describe MeditationSessionsHelper, type: :helper do
pending "add some examples to (or delete) #{__FILE__}"
end
| 29.3125 | 71 | 0.729211 |
6aada6d5a47c4898bb7a8d0ca355d97044080f99 | 250 | module Travis
module Addons
module Campfire
module Instruments
require 'travis/addons/campfire/instruments'
end
require 'travis/addons/campfire/event_handler'
class Task < ::Travis::Task; end
end
end
end
| 17.857143 | 52 | 0.668 |
1dff4ee0b9f0c56e0a8b552987e025a39b3c903b | 945 | # Run `pod lib lint' to ensure this is a valid spec.
Pod::Spec.new do |s|
s.name = 'KeyboardKit'
s.version = '4.8.0'
s.swift_versions = ['5.3']
s.summary = 'KeyboardKit helps you create keyboard extensions for iOS.'
s.description = <<-DESC
KeyboardKit is a Swift library that helps you create keyboard extensions for iOS.
DESC
s.homepage = 'https://github.com/danielsaidi/KeyboardKit'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Daniel Saidi' => '[email protected]' }
s.source = { :git => 'https://github.com/danielsaidi/KeyboardKit.git', :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/danielsaidi'
s.swift_version = '5.3'
s.ios.deployment_target = '13.0'
s.source_files = 'Sources/KeyboardKit/**/*.swift'
s.resources = "Sources/KeyboardKit/Resources/*.xcassets"
end
| 37.8 | 107 | 0.61164 |
9189a0558f8ad3e3e09518efac221f6fd904cfdf | 1,141 | # 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
Gem::Specification.new do |spec|
spec.name = 'aws-sdk-datasync'
spec.version = File.read(File.expand_path('../VERSION', __FILE__)).strip
spec.summary = 'AWS SDK for Ruby - DataSync'
spec.description = 'Official AWS Ruby gem for AWS DataSync (DataSync). This gem is part of the AWS SDK for Ruby.'
spec.author = 'Amazon Web Services'
spec.homepage = 'https://github.com/aws/aws-sdk-ruby'
spec.license = 'Apache-2.0'
spec.email = ['[email protected]']
spec.require_paths = ['lib']
spec.files = Dir['lib/**/*.rb']
spec.metadata = {
'source_code_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-datasync',
'changelog_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-datasync/CHANGELOG.md'
}
spec.add_dependency('aws-sdk-core', '~> 3', '>= 3.61.1')
spec.add_dependency('aws-sigv4', '~> 1.1')
end
| 38.033333 | 117 | 0.659947 |
035eaf88634036e35cdadde4086329498d60ef30 | 385 | When /^I run kumade$/ do
run_simple("bundle exec kumade", must_be_successful = false)
end
When /^I run kumade with "([^"]+)"$/ do |args|
run_simple("bundle exec kumade #{args}", must_be_successful = false)
end
Given /^a directory set up for kumade$/ do
create_dir('the-kumade-directory')
cd('the-kumade-directory')
add_kumade_to_gemfile
run_bundler
set_up_git_repo
end
| 24.0625 | 70 | 0.719481 |
61be661c5a9e18e8135d944a5bfb589d901285e3 | 3,404 |
#
# testing ruote
#
# Fri Jul 3 19:46:22 JST 2009
#
require File.expand_path('../base', __FILE__)
class FtConditionalTest < Test::Unit::TestCase
include FunctionalBase
def test_string_equality
pdef = Ruote.process_definition :name => 'test' do
set :f => 'd', :val => '2'
sequence do
echo '${f:d}'
echo 'a', :if => '${f:d}'
echo 'b', :if => '${f:d} == 2'
echo 'c', :if => "${f:d} == '2'"
echo 'd', :if => '${f:d} is set'
echo 'e', :if => '${f:e} is set'
end
end
assert_trace(%w[ 2 a b d ], pdef)
end
def test_string_equality_when_space
pdef = Ruote.process_definition :name => 'test' do
set :f => 'd', :val => 'some dude'
sequence do
echo '${f:d}'
echo 'a', :if => '${f:d}'
echo 'b', :if => '${f:d} == some dude'
echo 'c', :if => "${f:d} == 'some dude'"
echo 'd', :if => "${f:d} == ${'f:d}"
echo 'e', :if => '${f:d} is set'
end
end
assert_trace("some dude\na\nc\nd\ne", pdef)
end
def test_unless
pdef = Ruote.process_definition :name => 'test' do
echo '${f:f}'
echo 'u', :unless => '${f:f} == 2000'
echo 'i', :if => '${f:f} == 2000'
echo '.'
end
assert_trace(%w[ 2000 i . ], { 'f' => 2000 }, pdef)
@tracer.clear
assert_trace(%w[ 2000 i . ], { 'f' => '2000' }, pdef)
@tracer.clear
assert_trace(%w[ other u . ], { 'f' => 'other' }, pdef)
end
def test_and_or
pdef = Ruote.process_definition do
set 'f:t' => true
set 'f:f' => false
set 'f:name' => 'n'
set 'f:city' => 'c'
sequence do
echo '${f:t}/${f:f}'
echo 'a', :if => '${f:t}'
echo 'b', :if => '${f:t} or ${f:f}'
echo 'c', :if => '${f:t} and ${f:f}'
echo 'd', :if => '${f:t} and (${f:t} or ${f:f})'
echo 'e', :if => '${f:t} and (${f:t} and ${f:f})'
echo 'f', :if => '${name} == n and ${city} == c'
end
end
assert_trace(%w[ true/false a b d f ], pdef)
end
def test_if_booleans
pdef = Ruote.define do
echo 'a', :if => true
echo '.'
echo 'b', :if => 'true'
echo '.'
echo 'c', :if => false
echo '.'
echo 'd', :if => 'false'
end
wfid = @dashboard.launch(pdef)
r = @dashboard.wait_for(wfid)
assert_equal 'terminated', r['action']
assert_equal 'a.b..', @tracer.to_a.join
end
def test_unless_booleans
pdef = Ruote.define do
echo 'a', :unless => true
echo '.'
echo 'b', :unless => 'true'
echo '.'
echo 'c', :unless => false
echo '.'
echo 'd', :unless => 'false'
end
wfid = @dashboard.launch(pdef)
r = @dashboard.wait_for(wfid)
assert_equal 'terminated', r['action']
assert_equal '..c.d', @tracer.to_a.join
end
def test_with_numbers
pdef = Ruote.define do
set 'commission' => 2.310000
set 'scommission' => '2.310000'
echo 'a', :if => '${f:commission} > 0'
echo '.'
echo 'b', :unless => '${f:commission} > 0'
echo '.'
echo 'c', :if => '${f:scommission} > 0'
echo '.'
echo 'c', :unless => '${f:scommission} > 0'
end
wfid = @dashboard.launch(pdef)
r = @dashboard.wait_for(wfid)
assert_equal 'terminated', r['action']
assert_equal 'a..c.', @tracer.to_a.join
end
end
| 20.506024 | 59 | 0.485311 |
01951483f560d3d9bab603f5c1295f1cfcefc23f | 3,044 | # frozen_string_literal: true
RSpec.describe Worklog::Duration do
let(:seconds) { 16_200 }
let(:duration) do
described_class.new(seconds: seconds)
end
describe '.new' do
it 'creates an instance' do
expect(described_class.new(seconds: 30)).not_to be_nil
end
end
describe '.parse' do
context 'valid duration string' do
let(:duration_to_s) { '01h45m' }
let(:duration) do
described_class.parse(duration_to_s)
end
it 'creates an instance' do
expect(duration).not_to be_nil
end
it 'parse the duration string' do
expect(duration.seconds).to eq 6300
end
it 'represents the correct duration' do
expect(duration.to_s).to eq duration_to_s
end
end
context 'invalid duration string' do
let(:duration_to_s) { '1h10mwft lol' }
let(:duration) do
described_class.parse(duration_to_s)
end
it 'creates an instance' do
expect(duration).not_to be_nil
end
it 'parse only the valid duration parts' do
expect(duration.seconds).to eq 4200
end
end
end
describe '.valid_str?' do
context 'invalid duration string' do
let(:str) { '2g' }
it 'returns false' do
expect(described_class.valid_str?(str)).to be_falsey
end
end
context 'valid duration string' do
let(:str) { '1000h40m' }
it 'returns true' do
expect(described_class.valid_str?(str)).to be_truthy
end
end
end
describe '#+' do
context 'when the type is duration' do
let(:duration2) do
described_class.new(seconds: 800)
end
let(:new_duration) { duration + duration2 }
it 'creates a new instance' do
expect(new_duration).not_to be duration
expect(new_duration).not_to be duration2
end
it 'adds the seconds' do
expect(new_duration.seconds).to be 17_000
end
end
context 'when the type is numeric' do
let(:num2) { 50 }
let(:new_duration) { duration + num2 }
it 'creates a new instance' do
expect(new_duration).not_to be duration
end
it 'adds the seconds' do
expect(new_duration.seconds).to be 16_250
end
end
end
describe '#seconds' do
it 'returns the amount of seconds' do
expect(duration.seconds).to eq 16_200
end
end
describe '#hours' do
it 'returns the amount of hours' do
expect(duration.hours).to eq 4
end
end
describe '#minutes' do
it 'returns the amount of minutes' do
expect(duration.minutes).to eq 30
end
end
describe '#to_sap_time_str' do
it 'returns a time string (minutes to a base of 100)' do
expect(duration.to_sap_time_str).to eq '04:50'
end
end
describe '#to_time_str' do
it 'returns a time string' do
expect(duration.to_time_str).to eq '04:30'
end
end
describe '#to_s' do
it 'returns a duration string' do
expect(duration.to_s).to eq '04h30m'
end
end
end
| 22.548148 | 60 | 0.630749 |
6a086ea311e4caef2d377e577bc99538bdff42a8 | 1,307 | class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
validates :name, presence: true, length: { maximum: 20 }
has_many :posts
has_many :comments, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :friendships, dependent: :destroy
has_many :inverse_friendships, class_name: 'Friendship', foreign_key: 'friend_id', dependent: :destroy
def friends
friends_array = friendships.map { |m_friendship| m_friendship.friend if m_friendship.confirmed }
friends_array += inverse_friendships.map { |i_friendship| i_friendship.user if i_friendship.confirmed }
friends_array.compact
end
def pending_friends
friendships.map { |friendship| friendship.friend unless friendship.confirmed }.compact
end
def friend_requests
inverse_friendships.map { |friendship| friendship.user unless friendship.confirmed }.compact
end
def confirm_friend(user)
friendship = inverse_friendships.find { |c_friendship| c_friendship.user == user }
friendship.confirmed = true
friendship.save
end
def friend?(user)
friends.include?(user)
end
end
| 32.675 | 107 | 0.755164 |
f7cfe3ea278023877582a30f1582145c394d24c0 | 153 | # frozen_string_literal: true
class Deck < ActiveRecord::Base
validates :name, presence: true
belongs_to :user
has_and_belongs_to_many :cards
end
| 19.125 | 33 | 0.784314 |
2851f08c63a51a55b0269c28f208d8dfe6469bc1 | 3,491 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'User interacts with other users', js: true do
context 'As a global super administrator' do
include_context 'login_with_super_admin'
before :each do
Bullet.enable = false
@org = create :organization
@org2 = create :organization
@other_user = create :teacher_in, organization: @org
@global_guest = create :global_guest
visit '/'
click_link 'Users'
end
describe 'Add User' do
it 'creates a new user' do
visit '/users'
click_link 'Add User'
fill_in 'Email', with: '[email protected]'
click_button 'Add User'
expect(page).to have_content '[email protected]'
expect(User.last.email).to eq '[email protected]'
expect(page).to have_content 'User with email [email protected] added.'
end
end
describe 'Edit User' do
after :each do
Bullet.enable = true
end
it 'changes user\'s role, in the organization, from teacher to administrator and add an admin role in another organization' do
click_link user_name(@other_user)
form_for(@org2).find('label', text: 'Teacher').click
form_for(@org2).click_button 'Update Role'
form_for(@org).find('label', text: 'Administrator').click
form_for(@org).click_button 'Update Role'
form_for(@org).find('label.is-checked', text: 'Administrator')
form_for(@org2).find('label.is-checked', text: 'Teacher')
expect(@other_user.has_role?(:admin, @org)).to be true
expect(@other_user.has_role?(:teacher, @org2)).to be true
expect(@other_user.has_role?(:teacher, @org)).to be false
end
it 'revokes the user\'s role in the organization' do
click_link user_name(@other_user)
expect(page).to have_content "#{@org.organization_name}: Teacher"
click_button "Revoke Role in #{@org.organization_name}"
expect(@other_user.has_role?(:teacher, @org)).to be false
expect(page).not_to have_content "#{@org.organization_name}: Teacher"
end
it 'changes the user\'s global role from global guest to global admin, then removes global role' do
Bullet.enable = false
click_link user_name(@global_guest)
expect(page).to have_content Role::GLOBAL_ROLES[:global_guest]
global_form.find('label', text: 'Global Administrator').click
global_form.click_button 'Update Global Role'
expect(page).to have_content Role::GLOBAL_ROLES[:global_admin]
global_form.find('label.is-checked', text: 'Global Administrator')
expect(@global_guest.has_role?(:global_admin)).to be true
expect(@global_guest.has_role?(:global_guest)).to be false
click_button 'Revoke Global Role'
expect(@global_guest.has_role?(:global_guest)).to be false
expect(@global_guest.has_role?(:global_admin)).to be false
end
end
describe 'Delete User' do
it 'deletes an existing user' do
click_link user_name(@other_user)
click_button 'delete-dialog-button'
click_button 'confirm-delete-button'
expect(page).to have_content "User with e-mail address #{@other_user.email} deleted."
expect(User.where(id: @other_user.id)).not_to exist
end
end
end
end
def form_for(organization)
find("#user-roles-for\\[#{organization.id}\\]")
end
def global_form
find('#user-roles-global')
end
| 34.22549 | 132 | 0.665712 |
e9672a63c9bfb0fd141b35d729336416c4b177a5 | 506 | module ApplicationHelper
# Returns the full title on a per-page basis. # Documentation comment
def full_title(page_title = '') # Method def, optional arg
base_title = "Ruby on Rails Tutorial Sample App" # Variable assignment
if page_title.empty? # Boolean test
base_title # Implicit return
else
page_title + " | " + base_title # String concatenation
end
end
end
| 38.923077 | 80 | 0.55336 |
bfdd3005ecffd5162c7af480c627ffec193db74c | 6,163 | #encoding :utf-8
module ModeloQytetet
class Jugador
#Modificadores y consultores
attr_accessor :casilla_actual,:encarcelado
#Modificadores
attr_writer :carta_libertad
#Consultores
attr_reader :propiedades, :nombre
#Variables de clase:
@@factor_especulador = 1
#Métodos:
def initialize(n)
@encarcelado = false
@nombre = n
@saldo = 7500
@propiedades = Array.new
@carta_libertad = nil
@casilla_actual = nil
end
def self.especulador(jugador)
@@factor_especulador = 2
@nombre = jugador.nombre
@saldo = jugador.saldo
@propiedades = jugador.propiedades
@carta_libertad = jugador.carta_libertad
@casilla_actual = jugador.casilla_actual
end
def get_factor_especulador
return @@factor_especulador
end
def actualizar_posicion(casilla)
if(casilla.numero_casilla < @casilla_actual.numero_casilla)
modificar_saldo(Qytetet.saldo_salida)
end
tengo_propietario = false
@casilla_actual = casilla
if(casilla.soy_edificable)
if(casilla.tengo_propietario && casilla.titulo.propietario_encarcelado)
coste_alquiler = casilla.cobrar_alquiler()
modificar_saldo(-coste_alquiler)
end
end
if(casilla.tipo == TipoCasilla::IMPUESTO)
coste = casilla.coste
modificar_saldo(-coste)
end
return tengo_propietario
end
def comprar_titulo
puedo_comprar = false
coste_compra = @casilla_actual.coste
if(@casilla_actual.soy_edificable && !@casilla_actual.tengo_propietario && coste_compra<= @saldo)
@casilla_actual.asignar_propietario(self)
@propiedades << @casilla_actual.titulo
modificar_saldo(-coste_compra)
puedo_comprar = true
end
puedo_comprar
end
#guardamos la carta en una variable auxiliar y lo tenemos a null
def devolver_carta_libertad
auxiliar = @carta_libertad
@carta_libertad = nil
return auxiliar
end
def ir_a_carcel(carcel)
@casilla_actual = carcel
@encarcelado = true
end
def modificar_saldo(cantidad)
@saldo = @saldo + cantidad
end
def obtener_capital
capital = @saldo
@propiedades.each do |propied|
capital = capital + propied.coste
propied.titulo.each do |edificio|
capital = capital + (edificio.precio_edificar * cuantas_casas_hoteles_tengo())
if (propied.esta_hipotecada)
capital = capital - propied.hipoteca_base
end
end
end
return capital
end
def obtener_propiedades_hipotecadas(hipotecadas)
@propiedades.select { |propied| propied.hipotecada == hipotecadas}
end
def pagar_cobrar_por_casa_y_hotel(cantidad)
numero_total = cuantas_casas_hoteles_tengo()
modificar_saldo(cantidad * numero_total)
end
def pagar_libertad
raise "No implementado"
end
def puedo_edificar_casa(casilla)
resultado = false
if(es_de_mi_propiedad(casilla))
coste_edificar_casa = casilla.titulo.precio_edificar
if(tengo_saldo(coste_edificar_casa))
resultado = true
end
end
resultado
end
def puedo_edificar_hotel(casilla)
resultado = false
if(es_de_mi_propiedad(casilla))
coste_edificar_hotel = casilla.titulo.precio_edificar
if(tengo_saldo(coste_edificar_hotel))
resultado = true
end
end
resultado
end
def puedo_hipotecar(casilla)
es_de_mi_propiedad(casilla)
end
def puedo_pagar_hipoteca
raise "No implementado"
end
def puedo_vender_propiedad(casi)
puedo_vender = false
if (es_de_mi_propiedad(casi) && !casi.titulo.hipotecada)
puedo_vender = true
end
puedo_vender
end
def tengo_carta_libertad
return !@carta_libertad.nil?
end
def tengo_propiedades
[email protected]?
end
#Si es 0 no tiene propiedades, si es distinto de 0 si tiene propiedades
def vender_propiedad(casilla)
precio_venta = casilla.vender_titulo()
modificar_saldo(precio_venta)
eliminar_de_mis_propiedades(casilla)
end
def cuantas_casas_hoteles_tengo
@propiedades.count{|propied| propied.num_hoteles > 0 || \
propied.num_casas > 0}
end
def eliminar_de_mis_propiedades(casi)
@propiedades.delete(casi.titulo)
end
def es_de_mi_propiedad(casi)
a = @propiedades.find_index { |propied| propied==casi.titulo}
return ! a.nil?
end
def tengo_saldo(cantidad)
@saldo >= cantidad
end
def to_s
#Cambiar "Jugador" por self.class.name.
cadena = "Jugador: #{@nombre}. \n"
if(@encarcelado)
cadena = cadena + "Encarcelado: sí. \n"
else
cadena = cadena + "Encarcelado: no. \n"
end
cadena = cadena + "Saldo: #{@saldo}. \n"
cadena = cadena + "Carta libertad: " + @carta_libertad.to_s + "\n"
cadena = cadena + "Casilla actual: " + @casilla_actual.to_s
cadena = cadena + "Propiedades: \n"
for s in @propiedades
cadena = cadena + "#{s}. \n"
end
cadena = cadena + "\n"
cadena
end
def bancarrota
arruinado = false
if(@saldo <= 0)
arruinado = true
end
return arruinado
end
def pagar_impuestos(cantidad)
modificar_saldo(-cantidad)
end
def convertirme(fianza)
converso = converso.especulador(self, fianza)
return converso
end
private :es_de_mi_propiedad, :eliminar_de_mis_propiedades
end
end
| 22.741697 | 103 | 0.600357 |
012dcf77c4d77a89a3d37793156c79a0e027ab39 | 2,943 | #!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2012, Google Inc. All Rights Reserved.
#
# License:: 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.
#
# This example gets all teams that the current user belongs to.
# To create teams, run create_user_team_associations.rb.
require 'dfp_api'
API_VERSION = :v201502
def get_user_team_associations_by_statement()
# Get DfpApi instance and load configuration from ~/dfp_api.yml.
dfp = DfpApi::Api.new
# To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
# the configuration file or provide your own logger:
# dfp.logger = Logger.new('dfp_xml.log')
# Get the UserTeamAssociationService.
uta_service = dfp.service(:UserTeamAssociationService, API_VERSION)
# Get the UserService.
user_service = dfp.service(:UserService, API_VERSION)
# Get the current user.
user = user_service.get_current_user()
# Create filter text to select user team associations by the user ID.
statement = DfpApi::FilterStatement.new(
'WHERE userId = :user_id ORDER BY id',
[
{:key => 'user_id',
:value => {:value => user[:id], :xsi_type => 'NumberValue'}},
]
)
begin
# Get user team associations by statement.
page = uta_service.get_user_team_associations_by_statement(
statement.toStatement())
if page and page[:results]
page[:results].each_with_index do |association, index|
puts "%d) Team user association between team ID %d and user ID %d." %
[index + statement.offset, association[:team_id],
association[:user_id]]
end
end
statement.offset += DfpApi::SUGGESTED_PAGE_LIMIT
end while statement.offset < page[:total_result_set_size]
# Print a footer.
if page.include?(:total_result_set_size)
puts "Number of results found: %d" % page[:total_result_set_size]
end
end
if __FILE__ == $0
begin
get_user_team_associations_by_statement()
# HTTP errors.
rescue AdsCommon::Errors::HttpError => e
puts "HTTP Error: %s" % e
# API errors.
rescue DfpApi::Errors::ApiException => e
puts "Message: %s" % e.message
puts 'Errors:'
e.errors.each_with_index do |error, index|
puts "\tError [%d]:" % (index + 1)
error.each do |field, value|
puts "\t\t%s: %s" % [field, value]
end
end
end
end
| 31.308511 | 79 | 0.673462 |
ffc7b275ab2bcf3f0e66a8ee12fdeab66edf5277 | 262 | # Only works in Ruby 2.6+
RSpec.describe ValueSemantics::RangeOf do
subject { described_class.new(Integer) }
it 'matches beginless ranges' do
is_expected.to be === (1..)
end
it 'matches endless ranges' do
is_expected.to be === (..10)
end
end
| 20.153846 | 42 | 0.675573 |
bb35c0aa14a956e81b07b85900524509174c0804 | 298 | class CreateCourses < ActiveRecord::Migration
def change
create_table :courses do |t|
t.string :name
t.string :course_code
t.string :color
t.string :period
t.text :description
t.date :started_on
t.date :ended_on
t.timestamps
end
end
end
| 18.625 | 45 | 0.630872 |
18d519ff8dc9760be3e6bdbe4b2f754c1185eedc | 1,915 | module Suit # :nodoc:
module Models # :nodoc:
module Matchers
# 'newer_than' named scope which retrieves items newer than given date
# requires that the class have a factory
# Tests:
# scope :newer_than, lambda { |time| {:conditions => ["created_at < ?", time || 1.day.ago] } }
# Examples:
# it { should scope_recent }
def scope_newer_than
TimeMatcher.new(:newer_than)
end
# 'scope_older_than' named scope which retrieves items older than the given date
# requires that the class have a factory
# Tests:
# scope :newer_than, lambda { |time| {:conditions => ["created_at < ?", time || 1.day.ago] } }
# Examples:
# it { should scope_recent }
def scope_older_than
TimeMatcher.new(:older_than)
end
class TimeMatcher < SuitMatcherBase # :nodoc:
def initialize(scope, field = :created_at)
@scope = scope
@field = field
end
def matches?(subject)
@subject = subject
@subject.class.delete_all
old_item = FactoryGirl.create(factory_name, @field => 1.month.ago)
new_item = FactoryGirl.create(factory_name, @field => 1.day.ago)
items = @subject.class.send(@scope, 1.week.ago)
if @scope == :newer_than
items.include?(new_item) && !items.include?(old_item)
elsif @scope == :older_than
!items.include?(new_item) && items.include?(old_item)
else
raise "matcher not implemented for #{@scope}"
end
end
def failure_message
"Expected #{factory_name} to scope by #{@scope} on #{@field} and be successful. But the call failed"
end
def description
"items scoped #{@scope}"
end
end
end
end
end
| 31.916667 | 110 | 0.564491 |
01267a2db72d2fedc5041a0f76ab4bee3b422164 | 542 | require "simplecov"
SimpleCov.start do
add_filter "/spec/"
end
require "bundler/setup"
require "relaton_iev"
require "rspec/matchers"
require "equivalent-xml"
Dir["./spec/support/**/*.rb"].sort.each { |f| require f }
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
| 22.583333 | 66 | 0.736162 |
91d1554e6d06e6e3de270c293fc3731b546d0813 | 44 | module PassCountSim
VERSION = "0.0.1"
end
| 11 | 19 | 0.704545 |
38d19923ab615116febfede659e98265e17eee3a | 1,341 | describe :dir_delete, :shared => true do
before :all do
DirSpecs.rmdir_dirs
end
after :all do
DirSpecs.rmdir_dirs false
end
it "removes empty directories" do
Dir.send(@method, DirSpecs.mock_rmdir("empty")).should == 0
end
ruby_version_is "1.9" do
it "calls #to_path on non-String arguments" do
DirSpecs.rmdir_dirs
p = mock('path')
p.should_receive(:to_path).and_return(DirSpecs.mock_rmdir("empty"))
Dir.send(@method, p)
end
end
ruby_version_is ""..."1.9" do
it "calls #to_str on non-String arguments" do
DirSpecs.rmdir_dirs
p = mock('path')
p.should_receive(:to_str).and_return(DirSpecs.mock_rmdir("empty"))
Dir.send(@method, p)
end
end
it "raises a SystemCallError when trying to remove a nonempty directory" do
lambda do
Dir.send @method, DirSpecs.mock_rmdir("nonempty")
end.should raise_error(SystemCallError)
end
# this won't work on Windows, since chmod(0000) does not remove all permissions
platform_is_not :windows do
it "raises a SystemCallError if lacking adequate permissions to remove the directory" do
File.chmod(0000, DirSpecs.mock_rmdir("noperm"))
lambda do
Dir.send @method, DirSpecs.mock_rmdir("noperm", "child")
end.should raise_error(SystemCallError)
end
end
end
| 27.9375 | 92 | 0.686801 |
0850f98455944b7c958fcca0a4ffb32eb89fc97d | 1,226 | #
# Author:: Matt Wrock (<[email protected]>)
#
# Copyright:: (C) 2015, Matt Wrock
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'chef/role'
module Kitchen
module Provisioner
# fetches roles from kitchen roles directory
class RunListExpansionFromKitchen < ::Chef::RunList::RunListExpansion
def initialize(environment, run_list_items, source = nil, role_dir = nil)
@role_dir = role_dir
super(environment, run_list_items, source)
end
def fetch_role(name, included_by)
role_file = File.join(@role_dir, name)
::Chef::Role.from_disk(role_file)
rescue ::Chef::Exceptions::RoleNotFound
role_not_found(name, included_by)
end
end
end
end
| 32.263158 | 79 | 0.717781 |
01b85c9b571d69be0838a860bcf21c58ce373be9 | 1,638 | #
# Be sure to run `pod lib lint FluxCapacitor.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 http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'FluxCapacitor'
s.version = '0.11.0'
s.summary = 'This is what makes the Flux design pattern possible.'
# 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/marty-suzuki/FluxCapacitor'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Taiki Suzuki' => '[email protected]' }
s.source = { :git => 'https://github.com/marty-suzuki/FluxCapacitor.git', :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/marty_suzuki'
s.ios.deployment_target = '9.0'
s.source_files = 'FluxCapacitor/**/*.{swift}'
# s.resource_bundles = {
# 'FluxCapacitor' => ['FluxCapacitor/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 38.093023 | 110 | 0.642857 |
2639a93875e1f55a67f9a42118bb68140e542552 | 5,437 | class Gdal < Formula
desc "Geospatial Data Abstraction Library"
homepage "http://www.gdal.org/"
url "https://download.osgeo.org/gdal/2.3.0/gdal-2.3.0.tar.xz"
sha256 "6f75e49aa30de140525ccb58688667efe3a2d770576feb7fbc91023b7f552aa2"
bottle do
sha256 "00b28455769c3d5d6ea13dc119f213f320c247489cb2ce9d03f7791d4b53919b" => :high_sierra
sha256 "1365de6a18caeb84d6a50e466a63be9c7541b1fab21edfc3012812157464f2c0" => :sierra
sha256 "8c0fd81eda5a91c8a75a78795f96b6dd9c53e74974bd38cc004b55a44ae95932" => :el_capitan
end
head do
url "https://svn.osgeo.org/gdal/trunk/gdal"
depends_on "doxygen" => :build
end
option "with-complete", "Use additional Homebrew libraries to provide more drivers."
option "with-unsupported", "Allow configure to drag in any library it can find. Invoke this at your own risk."
deprecated_option "enable-unsupported" => "with-unsupported"
deprecated_option "complete" => "with-complete"
depends_on "freexl"
depends_on "geos"
depends_on "giflib"
depends_on "jpeg"
depends_on "json-c"
depends_on "libgeotiff"
depends_on "libpng"
depends_on "libpq"
depends_on "libspatialite"
depends_on "libtiff"
depends_on "libxml2"
depends_on "numpy"
depends_on "pcre"
depends_on "proj"
depends_on "python"
depends_on "python@2"
depends_on "sqlite" # To ensure compatibility with SpatiaLite
depends_on "mysql" => :optional
if build.with? "complete"
depends_on "cfitsio"
depends_on "epsilon"
depends_on "hdf5"
depends_on "jasper"
depends_on "json-c"
depends_on "libdap"
depends_on "libxml2"
depends_on "netcdf"
depends_on "podofo"
depends_on "poppler"
depends_on "unixodbc" # macOS version is not complete enough
depends_on "webp"
depends_on "xerces-c"
depends_on "xz" # get liblzma compression algorithm library from XZutils
end
def install
args = [
# Base configuration
"--prefix=#{prefix}",
"--mandir=#{man}",
"--disable-debug",
"--with-libtool",
"--with-local=#{prefix}",
"--with-opencl",
"--with-threads",
# GDAL native backends
"--with-bsb",
"--with-grib",
"--with-pam",
"--with-pcidsk=internal",
"--with-pcraster=internal",
# Homebrew backends
"--with-curl=/usr/bin/curl-config",
"--with-freexl=#{Formula["freexl"].opt_prefix}",
"--with-geos=#{Formula["geos"].opt_prefix}/bin/geos-config",
"--with-geotiff=#{Formula["libgeotiff"].opt_prefix}",
"--with-gif=#{Formula["giflib"].opt_prefix}",
"--with-jpeg=#{Formula["jpeg"].opt_prefix}",
"--with-libjson-c=#{Formula["json-c"].opt_prefix}",
"--with-libtiff=#{Formula["libtiff"].opt_prefix}",
"--with-pg=#{Formula["libpq"].opt_prefix}/bin/pg_config",
"--with-png=#{Formula["libpng"].opt_prefix}",
"--with-spatialite=#{Formula["libspatialite"].opt_prefix}",
"--with-sqlite3=#{Formula["sqlite"].opt_prefix}",
"--with-static-proj4=#{Formula["proj"].opt_prefix}",
# Explicitly disable some features
"--without-grass",
"--without-jpeg12",
"--without-libgrass",
"--without-perl",
"--without-php",
"--without-python",
"--without-ruby",
"--with-armadillo=no",
"--with-qhull=no",
]
if build.with?("mysql")
args << "--with-mysql=#{Formula["mysql"].opt_prefix}/bin/mysql_config"
else
args << "--without-mysql"
end
# Optional Homebrew packages supporting additional formats
supported_backends = %w[liblzma cfitsio hdf5 netcdf jasper xerces odbc
dods-root epsilon webp podofo]
if build.with? "complete"
supported_backends.delete "liblzma"
args << "--with-liblzma=yes"
args.concat supported_backends.map { |b| "--with-" + b + "=" + HOMEBREW_PREFIX }
elsif build.without? "unsupported"
args.concat supported_backends.map { |b| "--without-" + b }
end
# Unsupported backends are either proprietary or have no compatible version
# in Homebrew. Podofo is disabled because Poppler provides the same
# functionality and then some.
unsupported_backends = %w[gta ogdi fme hdf4 openjpeg fgdb ecw kakadu mrsid
jp2mrsid mrsid_lidar msg oci ingres dwgdirect
idb sde podofo rasdaman sosi]
if build.without? "unsupported"
args.concat unsupported_backends.map { |b| "--without-" + b }
end
system "./configure", *args
system "make"
system "make", "install"
if build.stable? # GDAL 2.3 handles Python differently
cd "swig/python" do
system "python3", *Language::Python.setup_install_args(prefix)
system "python2", *Language::Python.setup_install_args(prefix)
end
bin.install Dir["swig/python/scripts/*.py"]
end
system "make", "man" if build.head?
# Force man installation dir: https://trac.osgeo.org/gdal/ticket/5092
system "make", "install-man", "INST_MAN=#{man}"
# Clean up any stray doxygen files
Dir.glob("#{bin}/*.dox") { |p| rm p }
end
test do
# basic tests to see if third-party dylibs are loading OK
system "#{bin}/gdalinfo", "--formats"
system "#{bin}/ogrinfo", "--formats"
if build.stable? # GDAL 2.3 handles Python differently
system "python3", "-c", "import gdal"
system "python2", "-c", "import gdal"
end
end
end
| 33.561728 | 112 | 0.650543 |
03c590f89e5439cc4054773e8aa119027d541344 | 338 | #!/usr/bin/ruby
class Foo
def initialize (&block)
puts "inti!! #{ self } #{block}"
obj = {foo: 'bar'}
if block_given?
yield
instance_eval &block
obj.instance_eval &block
1992.instance_eval &block
['bar'].instance_eval &block
end
end
end
Foo.new do
puts "self is #{ self }"
end
| 15.363636 | 36 | 0.579882 |
4a3da1c560f18fdbfdd2ba651ae15a0965ca423d | 87 | fd = ARGV.shift.to_i
f = File.for_fd fd
f.sync = true
f.write "writing to fd: #{fd}"
| 12.428571 | 30 | 0.643678 |
f752bfc1778449138f08e1646cbe6274d9110852 | 2,213 | class UserCurrentRole < ActiveRecord::Base
include AdmRegionDelegation
belongs_to :current_role
belongs_to :nomination_source
belongs_to :region # a.k.a adm_region_id
belongs_to :uic, :inverse_of => :user_current_roles
belongs_to :user, inverse_of: :user_current_roles
validates :current_role, :nomination_source, presence: true
validates_uniqueness_of :current_role_id, :scope => [:user_id, :uic_id]
validate :validate_legitimacy
validate :validate_tic_uic
delegate :number, :to => :uic, :prefix => true, :allow_nil => true
before_save :set_region_from_user
after_save :update_uic_participants_count
after_destroy :update_uic_participants_count
scope :dislocatable, proc { joins(:current_role).merge(CurrentRole.dislocatable) }
def uic_number=(number)
self.uic = number.presence && Uic.find_by_number(number)
end
delegate :priority, :to => :current_role, :prefix => true
delegate :must_have_tic?, :must_have_uic?, :to => :current_role, :allow_nil => true
# it's better to move it to UserCurrentRole decorator
def selectable_uics
set_region_from_user
return [] unless region
uics = region.uics_with_nested_regions.order(:name)
uics = region.adm_region.uics_with_nested_regions.order(:name) if uics.blank? && region.adm_region
if must_have_tic?
uics.tics
elsif must_have_uic?
uics.uics
else
uics
end
end
private
def validate_tic_uic
return unless current_role.present?
errors.add(:uic, :blank) if must_have_tic? && !uic.try(:tic?)
errors.add(:uic, :blank) if must_have_uic? && !uic.try(:uic?)
end
def validate_legitimacy
return unless current_role.present? && nomination_source.present?
case current_role.slug
when 'journalist'
if nomination_source.variant != 'media'
errors.add(:nomination_source, :incorrect_nomination_source)
end
end
end
def update_uic_participants_count
Uic.find_by(:id => uic_id_was).try(:update_participants_count!) if uic_id_changed?
uic.try(:update_participants_count!)
end
def set_region_from_user
if user
self.region ||= (user.region || user.adm_region)
end
end
end
| 29.506667 | 102 | 0.72526 |
39ef72f2049268fa89b65e0e3710844dd147bbf8 | 810 | class Company < ApplicationRecord
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
month3 = row.field('extra').gsub("=>", ":")
data = JSON.parse month3
data3 = {}
data3["phone"] = data['phone']
data3["website"] = data['website']
data3["contact_website"] = data['contact_website']
data4 = {}
data4["name"] = row.field('name').gsub(/[^a-zA-ZÀ-ÿ ]/, "").gsub(/ +/, ' ').lstrip.rstrip
data4["city"] = row.field('city')
data4["street"] = row.field('street')
data4["country"] = row.field('country_code')
data4["extra"] = data3
puts data4["name"]
Article.create! data4.to_hash
end
end
end
| 35.217391 | 101 | 0.493827 |
622cb596906229f39f62591a3966c2ae69670e58 | 2,421 | class Textidote < Formula
desc "Spelling, grammar and style checking on LaTeX documents"
homepage "https://sylvainhalle.github.io/textidote"
url "https://github.com/sylvainhalle/textidote/archive/refs/tags/v0.8.3.tar.gz"
sha256 "8c55d6f6f35d51fb5b84e7dcc86a4041e06b3f92d6a919023dc332ba2effd584"
license "GPL-3.0-or-later"
head "https://github.com/sylvainhalle/textidote.git", branch: "master"
livecheck do
url :stable
regex(/^v?(\d+(?:\.\d+)+)$/i)
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "c43727c26715f20b4f584dc84f451892795aa2a0ea7acd126b8f60e3b75a7ea6"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "699f0bfbe3ec8667be03c956935ded5af3eca9c22ad7a6a627a29dc40224e863"
sha256 cellar: :any_skip_relocation, monterey: "306ad9dd1d5cfa96ea9976fa349ec38bd0a246f0feaf27223fff86f51bcd879d"
sha256 cellar: :any_skip_relocation, big_sur: "62cb64ee83a30dae725475d3bb5b5260ed74784ce4b7bfe071a2cf0c7bb7a917"
sha256 cellar: :any_skip_relocation, catalina: "2c307c617920b39a668b3b4d877da206912f615bf409cdafa17e4a0063393171"
sha256 cellar: :any_skip_relocation, x86_64_linux: "0571032b89ba4edb5560e4358dab877bcdd15eb8a8d76c8656405362e0da8923"
end
depends_on "ant" => :build
depends_on "openjdk"
def install
# Build the JAR
system "ant", "download-deps"
system "ant", "-Dbuild.targetjdk=#{Formula["openjdk"].version.major}"
# Install the JAR + a wrapper script
libexec.install "textidote.jar"
bin.write_jar_script libexec/"textidote.jar", "textidote"
bash_completion.install "Completions/textidote.bash"
zsh_completion.install "Completions/textidote.zsh" => "_textidote"
end
test do
output = shell_output("#{bin}/textidote --version")
assert_match "TeXtidote", output
(testpath/"test1.tex").write <<~EOF
\\documentclass{article}
\\begin{document}
This should fails.
\\end{document}
EOF
output = shell_output("#{bin}/textidote --check en #{testpath}/test1.tex", 1)
assert_match "The modal verb 'should' requires the verb's base form..", output
(testpath/"test2.tex").write <<~EOF
\\documentclass{article}
\\begin{document}
This should work.
\\end{document}
EOF
output = shell_output("#{bin}/textidote --check en #{testpath}/test2.tex")
assert_match "Everything is OK!", output
end
end
| 37.828125 | 123 | 0.731103 |
33f899168b683f44276f89927940433ea88e1ec1 | 1,026 | class Moe < Formula
desc "Console text editor for ISO-8859 and ASCII"
homepage "https://www.gnu.org/software/moe/moe.html"
url "https://ftp.gnu.org/gnu/moe/moe-1.11.tar.lz"
mirror "https://ftpmirror.gnu.org/moe/moe-1.11.tar.lz"
sha256 "0efbcbcf5a4a8d966541c6cb099ba0ab6416780366dbce82d9ff995a85a5e2f9"
license "GPL-2.0-or-later"
bottle do
sha256 arm64_big_sur: "ecf7d889fc677d4fbd201086dc195d5d072dfdbc78fc0c506104a8a1e5216365"
sha256 big_sur: "fd26036b9c0e0c72963f91b99f1a0787109af0a519df1d33d0f04d0d0cc12ebe"
sha256 catalina: "38b7920c9d82ba731f98bd1a56932b0d0ebe675d6d9006848a48e392013aad5a"
sha256 mojave: "688fc7c768e785581675079dd436c9cf3fef36094ea1aa078a8c3fc221d00fbc"
sha256 x86_64_linux: "4ab7d521862b305f5efbb6f150ba7abd9c1a69825a5421b56ed209a953be4d49" # linuxbrew-core
end
uses_from_macos "ncurses"
def install
system "./configure", "--prefix=#{prefix}"
system "make", "install"
end
test do
system "#{bin}/moe", "--version"
end
end
| 36.642857 | 109 | 0.767057 |
185c3063918d7dfdb97b05360fdbc8cc4c3020e4 | 188 | class Moneymoney < Cask
url 'http://moneymoney-app.com/download/MoneyMoney.zip'
homepage 'http://moneymoney-app.com/'
version 'latest'
sha256 :no_check
link 'MoneyMoney.app'
end
| 23.5 | 57 | 0.734043 |
ed6ed16f37469ff60cd35103a0fd7482f39326e4 | 804 | require_relative "board"
require_relative "player"
class Battleship
attr_reader :board, :player
def initialize(board_length)
@player = Player::new
@board = Board::new(board_length)
@remaining_misses = @board.size / 2
end
def start_game
@board.place_random_ships
puts "Number of ships: #{@board.num_ships}"
@board.print
end
def lose?
if @remaining_misses <= 0
puts "you lose"
return true
end
false
end
def win?
if @board.num_ships > 0
return false
end
puts "you win"
true
end
def game_over?
self.win? || self.lose?
end
def turn
move = @player.get_move
if [email protected](move)
@remaining_misses -= 1
end
@board.print
puts "Remaining misses: #{@remaining_misses}"
end
end
| 16.08 | 49 | 0.633085 |
617b2bf663c49948689f08d6a24be8474d3af93c | 1,864 | module Pallets
class Configuration
# Backend to use for handling workflows
attr_accessor :backend
# Arguments used to initialize the backend
attr_accessor :backend_args
# Number of seconds to block while waiting for jobs
attr_accessor :blocking_timeout
# Number of workers to process jobs
attr_accessor :concurrency
# Minimum number of seconds a failed job stays in the given up set. After
# this period, jobs will be permanently deleted
attr_accessor :failed_job_lifespan
# Number of seconds allowed for a job to be processed. If a job exceeds this
# period, it is considered failed, and scheduled to be processed again
attr_accessor :job_timeout
# Maximum number of failures allowed per job. Can also be configured on a
# per task basis
attr_accessor :max_failures
# Number of connections to the backend
attr_writer :pool_size
# Serializer used for jobs
attr_accessor :serializer
# Middleware used to wrap job execution with custom logic. Acts like a stack
# and accepts callable objects (lambdas, procs, objects that respond to call)
# that take three arguments: the worker handling the job, the job hash and
# the context
#
# A minimal example of a middleware is:
# ->(worker, job, context, &b) { puts 'Hello World!'; b.call }
attr_reader :middleware
def initialize
@backend = :redis
@backend_args = {}
@blocking_timeout = 5
@concurrency = 2
@failed_job_lifespan = 7_776_000 # 3 months
@job_timeout = 1_800 # 30 minutes
@max_failures = 3
@serializer = :json
@middleware = default_middleware
end
def pool_size
@pool_size || @concurrency + 1
end
def default_middleware
Middleware::Stack[
Middleware::JobLogger
]
end
end
end
| 28.676923 | 81 | 0.687768 |
e28524d5f4126981b1fa33d21f052a77d1762d98 | 146 | # @author Donovan Bray <[email protected]>
Capistrano::Configuration.instance(true).load do
after "deploy:provision", "ssmtp:install"
end | 36.5 | 49 | 0.787671 |
28f990b379274fcdcfa9a973eb92ce5c4e8ac715 | 1,632 | require File.dirname(__FILE__) + '/../../spec_helper.rb'
module Spec
module Mocks
describe "PreciseCounts" do
before(:each) do
@mock = mock("test mock")
end
it "should fail when exactly n times method is called less than n times" do
@mock.should_receive(:random_call).exactly(3).times
@mock.random_call
@mock.random_call
lambda do
@mock.rspec_verify
end.should raise_error(MockExpectationError)
end
it "should fail when exactly n times method is never called" do
@mock.should_receive(:random_call).exactly(3).times
lambda do
@mock.rspec_verify
end.should raise_error(MockExpectationError)
end
it "should pass if exactly n times method is called exactly n times" do
@mock.should_receive(:random_call).exactly(3).times
@mock.random_call
@mock.random_call
@mock.random_call
@mock.rspec_verify
end
it "should pass multiple calls with different args and counts" do
@mock.should_receive(:random_call).twice.with(1)
@mock.should_receive(:random_call).once.with(2)
@mock.random_call(1)
@mock.random_call(2)
@mock.random_call(1)
@mock.rspec_verify
end
it "should pass mutiple calls with different args" do
@mock.should_receive(:random_call).once.with(1)
@mock.should_receive(:random_call).once.with(2)
@mock.random_call(1)
@mock.random_call(2)
@mock.rspec_verify
end
end
end
end
| 30.792453 | 82 | 0.61826 |
085b9c2d502fa8c8eb6eb916dd3c4dd8e5d7bfc9 | 1,988 | gem 'minitest'
require 'minitest/autorun'
describe "ES2020 support" do
def to_js( string)
_(Ruby2JS.convert(string, eslevel: 2020, filters: []).to_s)
end
def to_js_fn(string)
_(Ruby2JS.convert(string, eslevel: 2020,
filters: [Ruby2JS::Filter::Functions]).to_s)
end
def to_js_nullish( string)
_(Ruby2JS.convert(string, eslevel: 2020, or: :nullish, filters: []).to_s)
end
describe :matchAll do
it 'should handle scan' do
to_js_fn( 'str.scan(/\d/)' ).must_equal 'str.match(/\d/g)'
to_js_fn( 'str.scan(/(\d)(\d)/)' ).
must_equal 'Array.from(str.matchAll(/(\\d)(\\d)/g), s => s.slice(1))'
to_js_fn( 'str.scan(pattern)' ).
must_equal 'Array.from(str.matchAll(new RegExp(pattern, "g")), ' +
's => s.slice(1))'
end
end
describe :regex do
it "should handle regular expression indexes" do
to_js_fn( 'a[/\d+/]' ).must_equal 'a.match(/\d+/)?.[0]'
to_js_fn( 'a[/(\d+)/, 1]' ).must_equal 'a.match(/(\d+)/)?.[1]'
end
end
describe "nullish coalescing operator" do
it "should map || operator based on :or option" do
to_js( 'a || b' ).must_equal 'a || b'
to_js_nullish( 'a || b' ).must_equal 'a ?? b'
end
end
describe :OptionalChaining do
unless (RUBY_VERSION.split('.').map(&:to_i) <=> [2, 3, 0]) == -1
it "should support conditional attribute references" do
to_js('x=a&.b').must_equal 'let x = a?.b'
end
it "should chain conditional attribute references" do
to_js('x=a&.b&.c').must_equal 'let x = a?.b?.c'
end
it "should support conditional indexing" do
to_js('x=a&.[](b)').must_equal 'let x = a?.[b]'
end
end
it "should combine conditions when it can" do
to_js('x=a && a.b').must_equal 'let x = a?.b'
end
it "should ignore unrelated ands" do
to_js('x=x && a && a.b && a.b.c && a.b.c.d && y').
must_equal 'let x = x && a?.b?.c?.d && y'
end
end
end
| 28.811594 | 77 | 0.577465 |
4acae727995e1de9d0a195886c343db8cbda3caf | 3,279 | require 'spec_helper'
shared_examples 'Card Token Mocking' do
describe 'Direct Token Creation' do
it "generates and reads a card token for create charge" do
card_token = StripeMock.generate_card_token(last4: "2244", exp_month: 33, exp_year: 2255)
charge = Stripe::Charge.create(amount: 500, card: card_token)
card = charge.card
expect(card.last4).to eq("2244")
expect(card.exp_month).to eq(33)
expect(card.exp_year).to eq(2255)
end
it "generates and reads a card token for create customer" do
card_token = StripeMock.generate_card_token(last4: "9191", exp_month: 99, exp_year: 3005)
cus = Stripe::Customer.create(card: card_token)
card = cus.cards.data.first
expect(card.last4).to eq("9191")
expect(card.exp_month).to eq(99)
expect(card.exp_year).to eq(3005)
end
it "generates and reads a card token for update customer" do
card_token = StripeMock.generate_card_token(last4: "1133", exp_month: 11, exp_year: 2099)
cus = Stripe::Customer.create()
cus.card = card_token
cus.save
card = cus.cards.data.first
expect(card.last4).to eq("1133")
expect(card.exp_month).to eq(11)
expect(card.exp_year).to eq(2099)
end
it "retrieves a created token" do
card_token = StripeMock.generate_card_token(last4: "2323", exp_month: 33, exp_year: 2222)
token = Stripe::Token.retrieve(card_token)
expect(token.id).to eq(card_token)
expect(token.card.last4).to eq("2323")
expect(token.card.exp_month).to eq(33)
expect(token.card.exp_year).to eq(2222)
end
end
describe 'Stripe::Token' do
it "generates and reads a card token for create customer" do
card_token = Stripe::Token.create({
card: {
number: "4222222222222222",
exp_month: 9,
exp_year: 2017
}
})
cus = Stripe::Customer.create(card: card_token.id)
card = cus.cards.data.first
expect(card.last4).to eq("2222")
expect(card.exp_month).to eq(9)
expect(card.exp_year).to eq(2017)
end
it "generates and reads a card token for update customer" do
card_token = Stripe::Token.create({
card: {
number: "1111222233334444",
exp_month: 11,
exp_year: 2019
}
})
cus = Stripe::Customer.create()
cus.card = card_token.id
cus.save
card = cus.cards.data.first
expect(card.last4).to eq("4444")
expect(card.exp_month).to eq(11)
expect(card.exp_year).to eq(2019)
end
it "generates a card token created from customer" do
card_token = Stripe::Token.create({
card: {
number: "1111222233334444",
exp_month: 11,
exp_year: 2019
}
})
cus = Stripe::Customer.create()
cus.card = card_token.id
cus.save
card_token = Stripe::Token.create({
customer: cus.id
})
expect(card_token.object).to eq("token")
end
it "throws an error if neither card nor customer are provided", :live => true do
expect { Stripe::Token.create }.to raise_error(
Stripe::InvalidRequestError, /must supply either a card, customer/
)
end
end
end
| 28.025641 | 95 | 0.627325 |
e2636e4b404a8cf7459b41d375d004d1ac0eeb7f | 1,620 | class Libvpx < Formula
desc "VP8/VP9 video codec"
homepage "https://www.webmproject.org/code/"
url "https://github.com/webmproject/libvpx/archive/v1.11.0.tar.gz"
sha256 "965e51c91ad9851e2337aebcc0f517440c637c506f3a03948062e3d5ea129a83"
license "BSD-3-Clause"
head "https://chromium.googlesource.com/webm/libvpx.git"
bottle do
sha256 cellar: :any, arm64_big_sur: "2edfb6a133be8947da27719975dbd19dd6233e12f21d221bea7f6008cfbc51a2"
sha256 cellar: :any, big_sur: "73d6365843bd6b8c868b3bf020152225d06304117c23c2a1e579ce347d3ab4e1"
sha256 cellar: :any, catalina: "28194ea0a917dcfecbfdcd51cb37da4ae1697238e3c2dedc769c502b435124c7"
sha256 cellar: :any, mojave: "378b9f6680ea8a99c064d8acd0cfbfbf2a1c142d8c4f27cf935dcfed3342cc61"
sha256 cellar: :any_skip_relocation, x86_64_linux: "e79ec2f50112da2b5adfc83b46604af182af8364410c9ec686c6c519c133229d"
end
depends_on "yasm" => :build
def install
args = %W[
--prefix=#{prefix}
--disable-dependency-tracking
--disable-examples
--disable-unit-tests
--enable-pic
--enable-shared
--enable-vp9-highbitdepth
]
if Hardware::CPU.intel?
ENV.runtime_cpu_detection
args << "--enable-runtime-cpu-detect"
end
# https://bugs.chromium.org/p/webm/issues/detail?id=1475
args << "--disable-avx512" if MacOS.version <= :el_capitan
mkdir "macbuild" do
system "../configure", *args
system "make", "install"
end
end
test do
system "ar", "-x", "#{lib}/libvpx.a"
end
end
| 33.75 | 122 | 0.685185 |
ab4c0af42b20ce045f980b3bd19b06099a775776 | 264 | Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :users, param: :_username
namespace :auth do
post '/login', to: 'authentication#login'
end
end
end
get '/*a', to: 'application#not_found'
end
| 16.5 | 49 | 0.628788 |
03e5d03feb4b0e63616fcffb430b156b89a51bae | 487 | module Rack
module Cache
class HashAggregator
def initialize(hash, &block)
@hash = hash
@aggregator = block || ->(v) { v }
end
def [](pattern)
aggregate(matches(pattern))
end
def *
aggregate(@hash.values)
end
private
def aggregate(values)
@aggregator.call(values)
end
def matches(pattern)
@hash.select { |k, _| pattern === k }.values
end
end
end
end
| 16.793103 | 52 | 0.521561 |
e9867894703741fe767e32373bf6e9a31561a93a | 8,268 | require 'cucumber/cucumber_expressions/ast'
require 'cucumber/cucumber_expressions/errors'
require 'cucumber/cucumber_expressions/cucumber_expression_tokenizer'
module Cucumber
module CucumberExpressions
class CucumberExpressionParser
def parse(expression)
# text := whitespace | ')' | '}' | .
parse_text = lambda do |_, tokens, current|
token = tokens[current]
case token.type
when TokenType::WHITE_SPACE, TokenType::TEXT, TokenType::END_PARAMETER, TokenType::END_OPTIONAL
return 1, [Node.new(NodeType::TEXT, nil, token.text, token.start, token.end)]
when TokenType::ALTERNATION
raise AlternationNotAllowedInOptional.new(expression, token)
when TokenType::BEGIN_PARAMETER, TokenType::START_OF_LINE, TokenType::END_OF_LINE, TokenType::BEGIN_OPTIONAL
else
# If configured correctly this will never happen
return 0, nil
end
# If configured correctly this will never happen
return 0, nil
end
# name := whitespace | .
parse_name = lambda do |_, tokens, current|
token = tokens[current]
case token.type
when TokenType::WHITE_SPACE, TokenType::TEXT
return 1, [Node.new(NodeType::TEXT, nil, token.text, token.start, token.end)]
when TokenType::BEGIN_PARAMETER, TokenType::END_PARAMETER, TokenType::BEGIN_OPTIONAL, TokenType::END_OPTIONAL, TokenType::ALTERNATION
raise InvalidParameterTypeNameInNode.new(expression, token)
when TokenType::START_OF_LINE, TokenType::END_OF_LINE
# If configured correctly this will never happen
return 0, nil
else
# If configured correctly this will never happen
return 0, nil
end
end
# parameter := '{' + name* + '}'
parse_parameter = parse_between(
NodeType::PARAMETER,
TokenType::BEGIN_PARAMETER,
TokenType::END_PARAMETER,
[parse_name]
)
# optional := '(' + option* + ')'
# option := optional | parameter | text
optional_sub_parsers = []
parse_optional = parse_between(
NodeType::OPTIONAL,
TokenType::BEGIN_OPTIONAL,
TokenType::END_OPTIONAL,
optional_sub_parsers
)
optional_sub_parsers << parse_optional << parse_parameter << parse_text
# alternation := alternative* + ( '/' + alternative* )+
parse_alternative_separator = lambda do |_, tokens, current|
unless looking_at(tokens, current, TokenType::ALTERNATION)
return 0, nil
end
token = tokens[current]
return 1, [Node.new(NodeType::ALTERNATIVE, nil, token.text, token.start, token.end)]
end
alternative_parsers = [
parse_alternative_separator,
parse_optional,
parse_parameter,
parse_text,
]
# alternation := (?<=left-boundary) + alternative* + ( '/' + alternative* )+ + (?=right-boundary)
# left-boundary := whitespace | } | ^
# right-boundary := whitespace | { | $
# alternative: = optional | parameter | text
parse_alternation = lambda do |expr, tokens, current|
previous = current - 1
unless looking_at_any(tokens, previous, [TokenType::START_OF_LINE, TokenType::WHITE_SPACE, TokenType::END_PARAMETER])
return 0, nil
end
consumed, ast = parse_tokens_until(expr, alternative_parsers, tokens, current, [TokenType::WHITE_SPACE, TokenType::END_OF_LINE, TokenType::BEGIN_PARAMETER])
sub_current = current + consumed
unless ast.map { |astNode| astNode.type }.include? NodeType::ALTERNATIVE
return 0, nil
end
start = tokens[current].start
_end = tokens[sub_current].start
# Does not consume right hand boundary token
return consumed, [Node.new(NodeType::ALTERNATION, split_alternatives(start, _end, ast), nil, start, _end)]
end
#
# cucumber-expression := ( alternation | optional | parameter | text )*
#
parse_cucumber_expression = parse_between(
NodeType::EXPRESSION,
TokenType::START_OF_LINE,
TokenType::END_OF_LINE,
[parse_alternation, parse_optional, parse_parameter, parse_text]
)
tokenizer = CucumberExpressionTokenizer.new
tokens = tokenizer.tokenize(expression)
_, ast = parse_cucumber_expression.call(expression, tokens, 0)
ast[0]
end
private
def parse_between(type, begin_token, end_token, parsers)
lambda do |expression, tokens, current|
unless looking_at(tokens, current, begin_token)
return 0, nil
end
sub_current = current + 1
consumed, ast = parse_tokens_until(expression, parsers, tokens, sub_current, [end_token, TokenType::END_OF_LINE])
sub_current += consumed
# endToken not found
unless looking_at(tokens, sub_current, end_token)
raise MissingEndToken.new(expression, begin_token, end_token, tokens[current])
end
# consumes endToken
start = tokens[current].start
_end = tokens[sub_current].end
consumed = sub_current + 1 - current
ast = [Node.new(type, ast, nil, start, _end)]
return consumed, ast
end
end
def parse_token(expression, parsers, tokens, start_at)
parsers.each do |parser|
consumed, ast = parser.call(expression, tokens, start_at)
return consumed, ast unless consumed == 0
end
# If configured correctly this will never happen
raise 'No eligible parsers for ' + tokens
end
def parse_tokens_until(expression, parsers, tokens, start_at, end_tokens)
current = start_at
size = tokens.length
ast = []
while current < size do
if looking_at_any(tokens, current, end_tokens)
break
end
consumed, sub_ast = parse_token(expression, parsers, tokens, current)
if consumed == 0
# If configured correctly this will never happen
# Keep to avoid infinite loops
raise 'No eligible parsers for ' + tokens
end
current += consumed
ast += sub_ast
end
[current - start_at, ast]
end
def looking_at_any(tokens, at, token_types)
token_types.detect { |token_type| looking_at(tokens, at, token_type) }
end
def looking_at(tokens, at, token)
if at < 0
# If configured correctly this will never happen
# Keep for completeness
return token == TokenType::START_OF_LINE
end
if at >= tokens.length
return token == TokenType::END_OF_LINE
end
tokens[at].type == token
end
def split_alternatives(start, _end, alternation)
separators = []
alternatives = []
alternative = []
alternation.each { |n|
if NodeType::ALTERNATIVE == n.type
separators.push(n)
alternatives.push(alternative)
alternative = []
else
alternative.push(n)
end
}
alternatives.push(alternative)
create_alternative_nodes(start, _end, separators, alternatives)
end
def create_alternative_nodes(start, _end, separators, alternatives)
alternatives.each_with_index.map do |n, i|
if i == 0
right_separator = separators[i]
Node.new(NodeType::ALTERNATIVE, n, nil, start, right_separator.start)
elsif i == alternatives.length - 1
left_separator = separators[i - 1]
Node.new(NodeType::ALTERNATIVE, n, nil, left_separator.end, _end)
else
left_separator = separators[i - 1]
right_separator = separators[i]
Node.new(NodeType::ALTERNATIVE, n, nil, left_separator.end, right_separator.start)
end
end
end
end
end
end
| 37.581818 | 166 | 0.606918 |
012af3be0e73c67e43cff2e2d56e1f50546996d0 | 3,500 | # frozen_string_literal: true
require 'transaction/version'
require 'securerandom'
require 'redis'
require 'json'
require 'transaction/helper'
module Transaction
STATUSES = %i[queued processing success error].freeze
DEFAULT_ATTRIBUTES = {
status: :queued
}.freeze
def self.configure
yield self
end
def self.redis=(hash = {})
@redis = if hash.instance_of?(Redis)
hash
else
Redis.new(hash)
end
end
def self.redis
# use default redis if not set
@redis ||= Redis.new
end
def self.pubsub_client=(client:, trigger:, channel_name: nil, event: 'status')
@client = client
@trigger = trigger
@event = event
@channel_name = channel_name
end
def self.pubsub_client
return if @client.nil? || @trigger.nil?
{
client: @client,
trigger: @trigger,
event: @event,
channel_name: @channel_name
}
end
class Client
attr_reader :transaction_id, :status, :attributes
def initialize(transaction_id: nil, options: {})
@transaction_id = transaction_id ||
"transact-#{SecureRandom.urlsafe_base64(16)}"
@redis_client = Transaction.redis
@pubsub_client = Transaction.pubsub_client
options = DEFAULT_ATTRIBUTES.merge(options)
@attributes = parsed_attributes || {}
update_attributes(options) if @attributes.empty?
@status = @attributes[:status].to_s
end
def update_attributes(options)
unless options.is_a? Hash
raise ArgumentError, 'Invalid type. Expected Hash'
end
@attributes = symbolize_keys!(@attributes.merge!(options))
redis_set(@transaction_id, @attributes.to_json)
@status = @attributes[:status].to_s
end
def update_status(status)
status = status.to_sym
raise 'Invalid Status' unless STATUSES.include?(status.to_sym)
update_attributes(status: status)
end
def start!
update_status(:processing)
trigger_event!(message: 'Processing')
end
def finish!(status: 'success', clear: false, data: {})
update_status(status)
trigger_event!({ message: 'Done' }.merge(data))
redis_delete if clear
end
def clear!
@attributes = @status = nil
redis_delete
end
def refresh!
@attributes = parsed_attributes
raise StandardError, 'Transaction expired' if @attributes.nil?
@status = @attributes[:status].to_s
end
def trigger_event!(data = {})
return if @pubsub_client.nil?
data[:status] = @status
channel_name = @pubsub_client[:channel_name] || @transaction_id
client = @pubsub_client[:client]
trigger = @pubsub_client[:trigger]
event = @pubsub_client[:event]
client.send(trigger, channel_name, event, data)
end
private
def parsed_attributes
data = redis_get
return nil if data.nil?
begin
response = JSON.parse(data)
raise 'Invalid type. Expected Hash' unless response.is_a? Hash
response = symbolize_keys!(response)
rescue JSON::ParserError
raise 'Invalid attempt to update the attributes'
end
response
end
# redis methods
def redis_get
@redis_client.get(@transaction_id)
end
def redis_set(key, value)
@redis_client.set(key, value)
end
def redis_delete
@redis_client.del(@transaction_id)
end
end
class Error < StandardError; end
end
| 22.727273 | 80 | 0.644 |
f878695344f4db3ffd2db262a79b61206ce1e85c | 805 | Pod::Spec.new do |s|
s.name = "CNLiveRequestKitSDK"
s.version = "1.4.2"
s.summary = "LSY-iOS 网络请求基础工具"# 项目简介
s.homepage = "https://github.com/woshiliushiyu/CNLiveRequestKitSDK"
s.source = { :git => "https://github.com/woshiliushiyu/CNLiveRequestKitSDK.git", :tag => "#{s.version}" }
s.license = "MIT" # 开源证书
s.author = { 'woshiliushiyu' => '[email protected]' }
s.platform = :ios, "9.0" #平台及支持的最低版本
s.frameworks = "UIKit", "Foundation"#支持的框架
s.ios.deployment_target = "9.0"
s.vendored_frameworks = 'CNLiveRequestBastKit.framework'
s.dependency 'AFNetworking', '~>3.2.1'
# s.subspec 'CNLiveRequestKitSDK' do |sp|
# sp.vendored_frameworks = 'CNLiveRequestKitSDK.framework'
# sp.dependency 'AFNetworking'
# end
end
| 36.590909 | 113 | 0.636025 |
f807b5eb5bd5b55283bca07131b46b0b44ac78d2 | 2,815 |
module Musikov
# This class represents a generic markov chain. It holds
# a hash of frequencies of subsequent states, for each state.
class MarkovModel
attr_reader :frequencies
###################
public
###################
# Initialize the hashes used to build the markov chain.
# Passes the initial array of values to be included in the model.
# * The "transitions" hash maps a state into another hash mapping the subsequent states to its number of subsequent occurrences
# * The "frequencies" hash maps a state into another hash mapping the subsequent states to a frequency indicating the probability of subsequent occurrences.
def initialize(value_chain = [])
@transitions = {}
@frequencies = {}
add_input(value_chain)
end
# Generate a random sequence from a markov chain
# * The initial_value is a state where the random chain must start
# * The initial_value may be nil
# * The value_number indicates the number of elements on the result random sequence
def generate(initial_value, value_number)
generated_sequence = []
selected_value = initial_value
rnd = Random.new
until generated_sequence.count == value_number do
selected_value = pick_value(rnd.rand(0.1..1.0), selected_value)
generated_sequence << selected_value
end
return generated_sequence
end
# Passes the argument array of state values to be included in the model.
def add_input(value_chain = [])
prev_value = nil
value_chain.each { |value|
add_value(prev_value, value)
prev_value = value
}
compute_frequencies
end
###################
private
###################
# Add a state on the transitions hash
def add_value(prev_value = nil, value)
@transitions[prev_value] ||= Hash.new{0}
@transitions[prev_value][value] += 1
end
# Pick a value on the frequencies hash based on a random number and the previous state
def pick_value(random_number, prev_value)
next_value = @frequencies[prev_value]
if next_value.nil? then
next_value = @frequencies[nil]
end
succ_list = next_value.sort_by{|key, value| value}
freq_counter = 0.0
succ_list.each { |succ_value, freq|
freq_counter += freq
return succ_value if freq_counter >= random_number
}
end
# Compute the frequencies hash based on the transistions hash
def compute_frequencies
@transitions.map { |value, transition_hash|
sum = 0.0
transition_hash.each { |succ_value, occurencies|
sum += occurencies
}
transition_hash.each { |succ_value, occurencies|
@frequencies[value] ||= Hash.new{0}
@frequencies[value][succ_value] = occurencies/sum
}
}
end
def to_s
return @frequencies
end
end
end
| 27.871287 | 158 | 0.676021 |
e86f807f9e4cecb012f57da108136c3ea00561f5 | 719 | # Managed by modulesync - DO NOT EDIT
# https://voxpupuli.org/docs/updating-files-managed-with-modulesync/
RSpec.configure do |c|
c.mock_with :mocha
end
# puppetlabs_spec_helper will set up coverage if the env variable is set.
# We want to do this if lib exists and it hasn't been explicitly set.
ENV['COVERAGE'] ||= 'yes' if Dir.exist?(File.expand_path('../../lib', __FILE__))
require 'voxpupuli/test/spec_helper'
if File.exist?(File.join(__dir__, 'default_module_facts.yml'))
facts = YAML.safe_load(File.read(File.join(__dir__, 'default_module_facts.yml')))
if facts
facts.each do |name, value|
add_custom_fact name.to_sym, value
end
end
end
require 'support/acceptance/supported_versions'
| 29.958333 | 83 | 0.739917 |
01d38b6d4ba474f53d43db8616b124790dd9a772 | 589 | if ENV["COVERAGE"]
require 'simplecov'
SimpleCov.start
end
require 'bundler/setup'
require 'test/unit'
require 'shoulda/context'
require 'turn'
require 'mocha/setup'
require 'webmock'
require 'vcr'
require 'pry'
require 'scrapybara'
VCR.configure do |c|
c.cassette_library_dir = File.expand_path( Pathname( File.expand_path( 'fixtures/vcr_cassettes', File.dirname(__FILE__) ) ) )
c.hook_into :webmock
end
class Test::Unit::TestCase
def fixture_file(path)
File.read File.expand_path( path, Pathname( File.expand_path( 'fixtures', File.dirname(__FILE__) ) ) )
end
end
| 19.633333 | 127 | 0.741935 |
6a2f5fef6bf0da9a42d6cea9c793e60e471ff1f8 | 441 | # frozen_string_literal: true
module Stupidedi
module TransactionSets
module TwoThousandOne
module Standards
SegmentReqs = Versions::TwoThousandOne::SegmentReqs
autoload :FA997, "stupidedi/transaction_sets/002001/standards/FA997"
autoload :PO830, "stupidedi/transaction_sets/002001/standards/PO830"
autoload :SH856, "stupidedi/transaction_sets/002001/standards/SH856"
end
end
end
end
| 29.4 | 76 | 0.739229 |
113ef54fefbbeaf7867714bca1fe959c383a21e2 | 305 | class Ahoy::Store < Ahoy::DatabaseStore
end
# set to true for JavaScript tracking
Ahoy.api = false
Ahoy.track_bots = true
Ahoy.cookie_domain = :all
Ahoy.visit_duration = 6.hours
IPS = %w[192.168.1.1]
Ahoy.exclude_method = lambda do |_controller, request|
request&.ip ? request.ip.in?(IPS) : true
end
| 20.333333 | 54 | 0.734426 |
b91da11f1956c8f137d4bfaa960c5b0983e867f3 | 2,454 | Biopartsdb::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
| 36.088235 | 104 | 0.758761 |
e94cc1a4904567c26802be047d8c882509c0399b | 6,379 | #
# Helper for generating API requests against the files API.
# When you create it, give it the Rack::Test session you want to make requests
# as. If you do a new session, you'll have to create a new helper.
#
# See Also: FilesApiTestBase. If you're changing common test setup or adding
# a utility that doesn't require access to the current Rack Test Session, you
# should consider making your change there, not here.
#
# Example:
# api = FilesApiTestHelper.new(current_session, 'sources', channel_id)
# api.get_object('myfile.txt')
# with_session(:other_guy) do
# # current_session returns a different session in this block
# other_api = FilesApiTestHelper.new(current_session, 'sources', channel_id)
# other_api.get_object('myfile.txt')
# end
#
class FilesApiTestHelper
include Rack::Test::Methods
def initialize(session, endpoint, channel_id)
@session = session
@endpoint = endpoint
@channel_id = channel_id
@random = Random.new(0)
end
def current_session
@session
end
def list_objects
get "/v3/#{@endpoint}/#{@channel_id}"
JSON.parse(last_response.body) unless last_response.body.empty?
end
def get_object(filename, body = '', headers = {})
get "/v3/#{@endpoint}/#{@channel_id}/#{filename}", body, headers
last_response.body
end
def get_root_object(filename, body = '', headers = {})
# Intended for calling files exposed at the root from codeprojects.org
get "/#{@channel_id}/#{filename}", body, headers
last_response.body
end
def put_object(filename, body = '', headers = {})
put "/v3/#{@endpoint}/#{@channel_id}/#{filename}", body, headers
last_response.body
end
def post_object(filename, body = '', headers = {})
post "/v3/#{@endpoint}/#{@channel_id}/#{filename}", body, headers
last_response.body
end
def post_file(filename, file_contents, content_type)
body = {files: [create_uploaded_file(filename, file_contents, content_type)]}
headers = {'CONTENT_TYPE' => content_type}
post_object filename, body, headers
end
def patch_abuse(abuse_score)
patch "/v3/#{@endpoint}/#{@channel_id}/?abuse_score=#{abuse_score}"
last_response.body
end
def copy_object(source_filename, dest_filename)
put "/v3/#{@endpoint}/#{@channel_id}/#{dest_filename}?src=#{CGI.escape(source_filename)}"
last_response.body
end
def rename_object(old_filename, new_filename)
put "/v3/#{@endpoint}/#{@channel_id}/#{new_filename}?delete=#{CGI.escape(old_filename)}&src=#{CGI.escape(old_filename)}"
last_response.body
end
def copy_assets(source_channel_id, source_filenames)
post("/v3/copy-assets/#{@channel_id}?src_channel=#{source_channel_id}&src_files=#{JSON.generate(source_filenames)}", '', {})
last_response.body
end
def delete_object(filename)
delete "/v3/#{@endpoint}/#{@channel_id}/#{filename}"
end
def list_object_versions(filename)
get "/v3/#{@endpoint}/#{@channel_id}/#{filename}/versions"
JSON.parse(last_response.body)
end
def get_object_version(filename, version_id, body = '', headers = {})
get "/v3/#{@endpoint}/#{@channel_id}/#{filename}?version=#{version_id}", body, headers
last_response.body
end
def put_object_version(filename, version_id, body = '', headers = {}, timestamp = nil)
params = "?version=#{version_id}"
params += "&firstSaveTimestamp=#{timestamp}" if timestamp
put "/v3/#{@endpoint}/#{@channel_id}/#{filename}#{params}", body, headers
last_response.body
end
def post_object_version(filename, version_id, body = '', headers = {})
post "/v3/#{@endpoint}/#{@channel_id}/#{filename}?version=#{version_id}", body, headers
last_response.body
end
def restore_sources_version(filename, version_id, body = '', headers = {})
put "/v3/sources/#{@channel_id}/#{filename}/restore?version=#{version_id}", body, headers
JSON.parse(last_response.body)
end
def list_files_versions
get "/v3/#{@endpoint}-version/#{@channel_id}"
JSON.parse(last_response.body)
end
def restore_files_version(version_id)
put "/v3/#{@endpoint}-version/#{@channel_id}?version=#{version_id}"
JSON.parse(last_response.body)
end
def channel_policy_violation
get "/v3/channels/#{@channel_id}/privacy-profanity"
last_response.body
end
def post_file_version(filename, version_id, file_contents, content_type)
body = {files: [create_uploaded_file(filename, file_contents, content_type)]}
headers = {'CONTENT_TYPE' => content_type}
post_object_version filename, version_id, body, headers
end
def create_uploaded_file(filename, file_contents, content_type)
Dir.mktmpdir do |dir|
file_path = "#{dir}/#{filename}"
File.open(file_path, 'w') do |file|
file.write(file_contents)
file.rewind
end
Rack::Test::UploadedFile.new(file_path, content_type)
end
end
# Like create_uploaded_file, but generates a temporary filename based on the
# provided filename and returns it along with the created file.
def create_temp_file(filename, file_contents, content_type)
temp_filename = randomize_filename(filename)
[create_uploaded_file(temp_filename, file_contents, content_type), temp_filename]
end
def randomize_filename(filename)
parts = filename.split('.')
"#{add_random_suffix(parts[0])}.#{parts[1]}"
end
def add_random_suffix(key)
key + @random.bytes(10).unpack('H*')[0]
end
def ensure_aws_credentials
list_objects
credentials_missing = !last_response.successful? &&
last_response.body.index('Aws::Errors::MissingCredentialsError')
credentials_msg = <<-TEXT.gsub(/^\s+/, '').chomp
Aws::Errors::MissingCredentialsError: if you are running these tests locally,
follow these instructions to configure your AWS credentials and try again:
http://docs.aws.amazon.com/sdkforruby/api/#Configuration
TEXT
rescue Aws::S3::Errors::InvalidAccessKeyId
credentials_missing = true
credentials_msg = <<-TEXT.gsub(/^\s+/, '').chomp
Aws::S3::Errors::InvalidAccessKeyId: Make sure your AWS credentials are set.
If you don't have AWS credentials, follow these instructions to configure your AWS credentials and try again:
http://docs.aws.amazon.com/sdkforruby/api/#Configuration
TEXT
ensure
raise credentials_msg if credentials_missing
end
end
| 34.668478 | 128 | 0.706694 |
f81344fdff5431dd1524316f93843f4b5c9ed165 | 211 | class PetSerializer < ActiveModel::Serializer
attributes :id, :name, :gender, :age, :breed, :bio, :rescues, :avatar
#has_many :rescues
def rescues
object.rescues.map{|r| {story: r.story}}
end
end
| 19.181818 | 71 | 0.682464 |
18247924fe03cf2174f20e129e21f0cdc933c14f | 447 | # typed: true
module Family
module Bart
class Character
extend T::Sig
# Ensure that lookup in a parent namespace works correctly. This should
# show up as `Family::Simpsons` in the resulting rbi.
sig {returns(T.class_of(Simpsons))}
def family
Simpsons
end
sig {void}
def catchphrase
Util::Messages.say "eat pant"
end
FamilyClass = Simpsons
end
end
end
| 16.555556 | 77 | 0.610738 |
031b89d04996fab5a498092518949d0f84d57e80 | 1,036 | require 'spec_helper'
feature 'User wants to add a .gitlab-ci.yml file', feature: true do
before do
user = create(:user)
project = create(:project)
project.team << [user, :master]
login_as user
visit namespace_project_new_blob_path(project.namespace, project, 'master', file_name: '.gitlab-ci.yml')
end
scenario 'user can see .gitlab-ci.yml dropdown' do
expect(page).to have_css('.gitlab-ci-yml-selector')
end
scenario 'user can pick a template from the dropdown', js: true do
find('.js-gitlab-ci-yml-selector').click
wait_for_requests
within '.gitlab-ci-yml-selector' do
find('.dropdown-input-field').set('Jekyll')
find('.dropdown-content li', text: 'Jekyll').click
end
wait_for_requests
expect(page).to have_css('.gitlab-ci-yml-selector .dropdown-toggle-text', text: 'Jekyll')
expect(page).to have_content('This file is a template, and might need editing before it works on your project')
expect(page).to have_content('jekyll build -d test')
end
end
| 34.533333 | 115 | 0.699807 |
03ac1d5045772e97244f9a14df0e2e0c01082498 | 584 | class Book < ApplicationRecord
has_many :book_genres
has_many :genres, through: :book_genres
scope :finished, -> { where.not(finished_on: nil)}
scope :recent, -> { where('finished_on > ?', 2.days.ago) }
scope :search, ->(keyword) { where("keywords LIKE ?", "%#{keyword.downcase}%") if keyword.present? }
scope :filter, ->(name) { where(genres: {name: name}) if name.present? }
before_save :set_keywords
def finished?
finished_on.present?
end
protected
def set_keywords
self.keywords = [title, author, description].map(&:downcase).join(" ")
end
end
| 27.809524 | 102 | 0.674658 |
87951d12257462786c86bb5d6837f61fea790f62 | 390 | require 'spec_helper'
RSpec.describe SpreeShopifyImporter::Connections::Base, type: :model do
subject { described_class }
describe '.count', vcr: { cassette_name: 'shopify_import/base/count' } do
it 'raises error ActiveResource::ResourceNotFound' do
authenticate_with_shopify
expect { subject.count }.to raise_error ActiveResource::ResourceNotFound
end
end
end
| 27.857143 | 78 | 0.751282 |
ff2b254abad6492c69e0c2c86cd9833acd561043 | 449 | require_relative '../../../../spec_helper'
describe Web::Views::Google::Lock::Destroy do
let(:exposures) { Hash[format: :html] }
let(:template) do
Hanami::View::Template.new('apps/web/templates/google/lock/destroy.html.slim')
end
let(:view) { Web::Views::Google::Lock::Destroy.new(template, exposures) }
let(:rendered) { view.render }
it 'exposes #format' do
_(view.format).must_equal exposures.fetch(:format)
end
end
| 29.933333 | 82 | 0.674833 |
386b069a0dfef90ce63cb9ccdfd05576645ca6b9 | 1,466 | require 'rspec'
require 'date'
require 'name_matcher/parser'
describe 'Parser' do
def parse_line(line)
send(:parser).parse([line]).to_a[0]
end
let (:date_source) {
# Must match date-code
NameMatcher::DateSource.new(date = Date.new(2018, 1), kingdom = "An Tir")
}
let (:date_string) {
"201801N"
}
let (:parser) {
NameMatcher::Parser.new
}
it "ignores illegal dates" do
expect(parser.parse(["Test Name|xxxxx|N||"]).to_a).to be_empty
end
it "ignores range dates" do
expect(parser.parse(["Test Name|201301K-201703K|N||(regid:300000"]).to_a).to be_empty
end
context "when parsing dates" do
def parse_date(date_str)
parse_line("Test Name|#{date_str}|N||(regid:4000)").date_source
end
it "there are at least 18 kingdoms" do
expect(NameMatcher::Parser::KINGDOM_CODES.length).to be >= 18
end
it "takes the first four digits as the year" do
expect(parse_date("201703N").date.year).to eq(2017)
end
it "takes the newt two digits as the month (starting at 1)" do
expect(parse_date("201606N").date.month).to eq(06)
end
NameMatcher::Parser::KINGDOM_CODES.each do |code, kingdom|
it "translates the last letter #{code} to #{kingdom}" do
expect(parse_date("201503#{code}").kingdom).to eq(kingdom)
end
end
it "translates an unknown letter to itself" do
expect(parse_date("201411Z").kingdom).to eq("Z")
end
end
end
| 23.269841 | 89 | 0.654843 |
1ac7110731de268233af0d6922e4bba1948ed77c | 65,939 | # 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/json_rpc.rb'
Aws::Plugins::GlobalConfiguration.add_identifier(:applicationdiscoveryservice)
module Aws::ApplicationDiscoveryService
# An API client for ApplicationDiscoveryService. To construct a client, you need to configure a `:region` and `:credentials`.
#
# client = Aws::ApplicationDiscoveryService::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 = :applicationdiscoveryservice
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::JsonRpc)
# @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] :simple_json (false)
# Disables request parameter conversion, validation, and formatting.
# Also disable response data type conversions. This option is useful
# when you want to ensure the highest level of performance by
# avoiding overhead of walking request parameters and response data
# structures.
#
# When `:simple_json` is enabled, the request parameters hash must
# be formatted exactly as the DynamoDB API expects.
#
# @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
# Associates one or more configuration items with an application.
#
# @option params [required, String] :application_configuration_id
# The configuration ID of an application with which items are to be
# associated.
#
# @option params [required, Array<String>] :configuration_ids
# The ID of each configuration item to be associated with an
# application.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.associate_configuration_items_to_application({
# application_configuration_id: "ApplicationId", # required
# configuration_ids: ["ConfigurationId"], # required
# })
#
# @overload associate_configuration_items_to_application(params = {})
# @param [Hash] params ({})
def associate_configuration_items_to_application(params = {}, options = {})
req = build_request(:associate_configuration_items_to_application, params)
req.send_request(options)
end
# Deletes one or more import tasks, each identified by their import ID.
# Each import task has a number of records that can identify servers or
# applications.
#
# AWS Application Discovery Service has built-in matching logic that
# will identify when discovered servers match existing entries that
# you've previously discovered, the information for the
# already-existing discovered server is updated. When you delete an
# import task that contains records that were used to match, the
# information in those matched records that comes from the deleted
# records will also be deleted.
#
# @option params [required, Array<String>] :import_task_ids
# The IDs for the import tasks that you want to delete.
#
# @return [Types::BatchDeleteImportDataResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::BatchDeleteImportDataResponse#errors #errors} => Array<Types::BatchDeleteImportDataError>
#
# @example Request syntax with placeholder values
#
# resp = client.batch_delete_import_data({
# import_task_ids: ["ImportTaskIdentifier"], # required
# })
#
# @example Response structure
#
# resp.errors #=> Array
# resp.errors[0].import_task_id #=> String
# resp.errors[0].error_code #=> String, one of "NOT_FOUND", "INTERNAL_SERVER_ERROR", "OVER_LIMIT"
# resp.errors[0].error_description #=> String
#
# @overload batch_delete_import_data(params = {})
# @param [Hash] params ({})
def batch_delete_import_data(params = {}, options = {})
req = build_request(:batch_delete_import_data, params)
req.send_request(options)
end
# Creates an application with the given name and description.
#
# @option params [required, String] :name
# Name of the application to be created.
#
# @option params [String] :description
# Description of the application to be created.
#
# @return [Types::CreateApplicationResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateApplicationResponse#configuration_id #configuration_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_application({
# name: "String", # required
# description: "String",
# })
#
# @example Response structure
#
# resp.configuration_id #=> String
#
# @overload create_application(params = {})
# @param [Hash] params ({})
def create_application(params = {}, options = {})
req = build_request(:create_application, params)
req.send_request(options)
end
# Creates one or more tags for configuration items. Tags are metadata
# that help you categorize IT assets. This API accepts a list of
# multiple configuration items.
#
# @option params [required, Array<String>] :configuration_ids
# A list of configuration items that you want to tag.
#
# @option params [required, Array<Types::Tag>] :tags
# Tags that you want to associate with one or more configuration items.
# Specify the tags that you want to create in a *key*-*value* format.
# For example:
#
# `\{"key": "serverType", "value": "webServer"\}`
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.create_tags({
# configuration_ids: ["ConfigurationId"], # required
# tags: [ # required
# {
# key: "TagKey", # required
# value: "TagValue", # required
# },
# ],
# })
#
# @overload create_tags(params = {})
# @param [Hash] params ({})
def create_tags(params = {}, options = {})
req = build_request(:create_tags, params)
req.send_request(options)
end
# Deletes a list of applications and their associations with
# configuration items.
#
# @option params [required, Array<String>] :configuration_ids
# Configuration ID of an application to be deleted.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_applications({
# configuration_ids: ["ApplicationId"], # required
# })
#
# @overload delete_applications(params = {})
# @param [Hash] params ({})
def delete_applications(params = {}, options = {})
req = build_request(:delete_applications, params)
req.send_request(options)
end
# Deletes the association between configuration items and one or more
# tags. This API accepts a list of multiple configuration items.
#
# @option params [required, Array<String>] :configuration_ids
# A list of configuration items with tags that you want to delete.
#
# @option params [Array<Types::Tag>] :tags
# Tags that you want to delete from one or more configuration items.
# Specify the tags that you want to delete in a *key*-*value* format.
# For example:
#
# `\{"key": "serverType", "value": "webServer"\}`
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_tags({
# configuration_ids: ["ConfigurationId"], # required
# tags: [
# {
# key: "TagKey", # required
# value: "TagValue", # required
# },
# ],
# })
#
# @overload delete_tags(params = {})
# @param [Hash] params ({})
def delete_tags(params = {}, options = {})
req = build_request(:delete_tags, params)
req.send_request(options)
end
# Lists agents or connectors as specified by ID or other filters. All
# agents/connectors associated with your user account can be listed if
# you call `DescribeAgents` as is without passing any parameters.
#
# @option params [Array<String>] :agent_ids
# The agent or the Connector IDs for which you want information. If you
# specify no IDs, the system returns information about all
# agents/Connectors associated with your AWS user account.
#
# @option params [Array<Types::Filter>] :filters
# You can filter the request using various logical operators and a
# *key*-*value* format. For example:
#
# `\{"key": "collectionStatus", "value": "STARTED"\}`
#
# @option params [Integer] :max_results
# The total number of agents/Connectors to return in a single page of
# output. The maximum value is 100.
#
# @option params [String] :next_token
# Token to retrieve the next set of results. For example, if you
# previously specified 100 IDs for `DescribeAgentsRequest$agentIds` but
# set `DescribeAgentsRequest$maxResults` to 10, you received a set of 10
# results along with a token. Use that token in this query to get the
# next set of 10.
#
# @return [Types::DescribeAgentsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DescribeAgentsResponse#agents_info #agents_info} => Array<Types::AgentInfo>
# * {Types::DescribeAgentsResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.describe_agents({
# agent_ids: ["AgentId"],
# filters: [
# {
# name: "String", # required
# values: ["FilterValue"], # required
# condition: "Condition", # required
# },
# ],
# max_results: 1,
# next_token: "NextToken",
# })
#
# @example Response structure
#
# resp.agents_info #=> Array
# resp.agents_info[0].agent_id #=> String
# resp.agents_info[0].host_name #=> String
# resp.agents_info[0].agent_network_info_list #=> Array
# resp.agents_info[0].agent_network_info_list[0].ip_address #=> String
# resp.agents_info[0].agent_network_info_list[0].mac_address #=> String
# resp.agents_info[0].connector_id #=> String
# resp.agents_info[0].version #=> String
# resp.agents_info[0].health #=> String, one of "HEALTHY", "UNHEALTHY", "RUNNING", "UNKNOWN", "BLACKLISTED", "SHUTDOWN"
# resp.agents_info[0].last_health_ping_time #=> String
# resp.agents_info[0].collection_status #=> String
# resp.agents_info[0].agent_type #=> String
# resp.agents_info[0].registered_time #=> String
# resp.next_token #=> String
#
# @overload describe_agents(params = {})
# @param [Hash] params ({})
def describe_agents(params = {}, options = {})
req = build_request(:describe_agents, params)
req.send_request(options)
end
# Retrieves attributes for a list of configuration item IDs.
#
# <note markdown="1"> All of the supplied IDs must be for the same asset type from one of
# the following:
#
# * server
#
# * application
#
# * process
#
# * connection
#
# Output fields are specific to the asset type specified. For example,
# the output for a *server* configuration item includes a list of
# attributes about the server, such as host name, operating system,
# number of network cards, etc.
#
# For a complete list of outputs for each asset type, see [Using the
# DescribeConfigurations Action][1] in the *AWS Application Discovery
# Service User Guide*.
#
# </note>
#
#
#
# [1]: https://docs.aws.amazon.com/application-discovery/latest/userguide/discovery-api-queries.html#DescribeConfigurations
#
# @option params [required, Array<String>] :configuration_ids
# One or more configuration IDs.
#
# @return [Types::DescribeConfigurationsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DescribeConfigurationsResponse#configurations #configurations} => Array<Hash<String,String>>
#
# @example Request syntax with placeholder values
#
# resp = client.describe_configurations({
# configuration_ids: ["ConfigurationId"], # required
# })
#
# @example Response structure
#
# resp.configurations #=> Array
# resp.configurations[0] #=> Hash
# resp.configurations[0]["String"] #=> String
#
# @overload describe_configurations(params = {})
# @param [Hash] params ({})
def describe_configurations(params = {}, options = {})
req = build_request(:describe_configurations, params)
req.send_request(options)
end
# Lists exports as specified by ID. All continuous exports associated
# with your user account can be listed if you call
# `DescribeContinuousExports` as is without passing any parameters.
#
# @option params [Array<String>] :export_ids
# The unique IDs assigned to the exports.
#
# @option params [Integer] :max_results
# A number between 1 and 100 specifying the maximum number of continuous
# export descriptions returned.
#
# @option params [String] :next_token
# The token from the previous call to `DescribeExportTasks`.
#
# @return [Types::DescribeContinuousExportsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DescribeContinuousExportsResponse#descriptions #descriptions} => Array<Types::ContinuousExportDescription>
# * {Types::DescribeContinuousExportsResponse#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.describe_continuous_exports({
# export_ids: ["ConfigurationsExportId"],
# max_results: 1,
# next_token: "NextToken",
# })
#
# @example Response structure
#
# resp.descriptions #=> Array
# resp.descriptions[0].export_id #=> String
# resp.descriptions[0].status #=> String, one of "START_IN_PROGRESS", "START_FAILED", "ACTIVE", "ERROR", "STOP_IN_PROGRESS", "STOP_FAILED", "INACTIVE"
# resp.descriptions[0].status_detail #=> String
# resp.descriptions[0].s3_bucket #=> String
# resp.descriptions[0].start_time #=> Time
# resp.descriptions[0].stop_time #=> Time
# resp.descriptions[0].data_source #=> String, one of "AGENT"
# resp.descriptions[0].schema_storage_config #=> Hash
# resp.descriptions[0].schema_storage_config["DatabaseName"] #=> String
# resp.next_token #=> String
#
# @overload describe_continuous_exports(params = {})
# @param [Hash] params ({})
def describe_continuous_exports(params = {}, options = {})
req = build_request(:describe_continuous_exports, params)
req.send_request(options)
end
# `DescribeExportConfigurations` is deprecated. Use
# [DescribeImportTasks][1], instead.
#
#
#
# [1]: https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_DescribeExportTasks.html
#
# @option params [Array<String>] :export_ids
# A list of continuous export IDs to search for.
#
# @option params [Integer] :max_results
# A number between 1 and 100 specifying the maximum number of continuous
# export descriptions returned.
#
# @option params [String] :next_token
# The token from the previous call to describe-export-tasks.
#
# @return [Types::DescribeExportConfigurationsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DescribeExportConfigurationsResponse#exports_info #exports_info} => Array<Types::ExportInfo>
# * {Types::DescribeExportConfigurationsResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.describe_export_configurations({
# export_ids: ["ConfigurationsExportId"],
# max_results: 1,
# next_token: "NextToken",
# })
#
# @example Response structure
#
# resp.exports_info #=> Array
# resp.exports_info[0].export_id #=> String
# resp.exports_info[0].export_status #=> String, one of "FAILED", "SUCCEEDED", "IN_PROGRESS"
# resp.exports_info[0].status_message #=> String
# resp.exports_info[0].configurations_download_url #=> String
# resp.exports_info[0].export_request_time #=> Time
# resp.exports_info[0].is_truncated #=> Boolean
# resp.exports_info[0].requested_start_time #=> Time
# resp.exports_info[0].requested_end_time #=> Time
# resp.next_token #=> String
#
# @overload describe_export_configurations(params = {})
# @param [Hash] params ({})
def describe_export_configurations(params = {}, options = {})
req = build_request(:describe_export_configurations, params)
req.send_request(options)
end
# Retrieve status of one or more export tasks. You can retrieve the
# status of up to 100 export tasks.
#
# @option params [Array<String>] :export_ids
# One or more unique identifiers used to query the status of an export
# request.
#
# @option params [Array<Types::ExportFilter>] :filters
# One or more filters.
#
# * `AgentId` - ID of the agent whose collected data will be exported
#
# ^
#
# @option params [Integer] :max_results
# The maximum number of volume results returned by `DescribeExportTasks`
# in paginated output. When this parameter is used,
# `DescribeExportTasks` only returns `maxResults` results in a single
# page along with a `nextToken` response element.
#
# @option params [String] :next_token
# The `nextToken` value returned from a previous paginated
# `DescribeExportTasks` request where `maxResults` was used and the
# results exceeded the value of that parameter. Pagination continues
# from the end of the previous results that returned the `nextToken`
# value. This value is null when there are no more results to return.
#
# @return [Types::DescribeExportTasksResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DescribeExportTasksResponse#exports_info #exports_info} => Array<Types::ExportInfo>
# * {Types::DescribeExportTasksResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.describe_export_tasks({
# export_ids: ["ConfigurationsExportId"],
# filters: [
# {
# name: "FilterName", # required
# values: ["FilterValue"], # required
# condition: "Condition", # required
# },
# ],
# max_results: 1,
# next_token: "NextToken",
# })
#
# @example Response structure
#
# resp.exports_info #=> Array
# resp.exports_info[0].export_id #=> String
# resp.exports_info[0].export_status #=> String, one of "FAILED", "SUCCEEDED", "IN_PROGRESS"
# resp.exports_info[0].status_message #=> String
# resp.exports_info[0].configurations_download_url #=> String
# resp.exports_info[0].export_request_time #=> Time
# resp.exports_info[0].is_truncated #=> Boolean
# resp.exports_info[0].requested_start_time #=> Time
# resp.exports_info[0].requested_end_time #=> Time
# resp.next_token #=> String
#
# @overload describe_export_tasks(params = {})
# @param [Hash] params ({})
def describe_export_tasks(params = {}, options = {})
req = build_request(:describe_export_tasks, params)
req.send_request(options)
end
# Returns an array of import tasks for your account, including status
# information, times, IDs, the Amazon S3 Object URL for the import file,
# and more.
#
# @option params [Array<Types::ImportTaskFilter>] :filters
# An array of name-value pairs that you provide to filter the results
# for the `DescribeImportTask` request to a specific subset of results.
# Currently, wildcard values aren't supported for filters.
#
# @option params [Integer] :max_results
# The maximum number of results that you want this request to return, up
# to 100.
#
# @option params [String] :next_token
# The token to request a specific page of results.
#
# @return [Types::DescribeImportTasksResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DescribeImportTasksResponse#next_token #next_token} => String
# * {Types::DescribeImportTasksResponse#tasks #tasks} => Array<Types::ImportTask>
#
# 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.describe_import_tasks({
# filters: [
# {
# name: "IMPORT_TASK_ID", # accepts IMPORT_TASK_ID, STATUS, NAME
# values: ["ImportTaskFilterValue"],
# },
# ],
# max_results: 1,
# next_token: "NextToken",
# })
#
# @example Response structure
#
# resp.next_token #=> String
# resp.tasks #=> Array
# resp.tasks[0].import_task_id #=> String
# resp.tasks[0].client_request_token #=> String
# resp.tasks[0].name #=> String
# resp.tasks[0].import_url #=> String
# resp.tasks[0].status #=> String, one of "IMPORT_IN_PROGRESS", "IMPORT_COMPLETE", "IMPORT_COMPLETE_WITH_ERRORS", "IMPORT_FAILED", "IMPORT_FAILED_SERVER_LIMIT_EXCEEDED", "IMPORT_FAILED_RECORD_LIMIT_EXCEEDED", "DELETE_IN_PROGRESS", "DELETE_COMPLETE", "DELETE_FAILED", "DELETE_FAILED_LIMIT_EXCEEDED", "INTERNAL_ERROR"
# resp.tasks[0].import_request_time #=> Time
# resp.tasks[0].import_completion_time #=> Time
# resp.tasks[0].import_deleted_time #=> Time
# resp.tasks[0].server_import_success #=> Integer
# resp.tasks[0].server_import_failure #=> Integer
# resp.tasks[0].application_import_success #=> Integer
# resp.tasks[0].application_import_failure #=> Integer
# resp.tasks[0].errors_and_failed_entries_zip #=> String
#
# @overload describe_import_tasks(params = {})
# @param [Hash] params ({})
def describe_import_tasks(params = {}, options = {})
req = build_request(:describe_import_tasks, params)
req.send_request(options)
end
# Retrieves a list of configuration items that have tags as specified by
# the key-value pairs, name and value, passed to the optional parameter
# `filters`.
#
# There are three valid tag filter names:
#
# * tagKey
#
# * tagValue
#
# * configurationId
#
# Also, all configuration items associated with your user account that
# have tags can be listed if you call `DescribeTags` as is without
# passing any parameters.
#
# @option params [Array<Types::TagFilter>] :filters
# You can filter the list using a *key*-*value* format. You can separate
# these items by using logical operators. Allowed filters include
# `tagKey`, `tagValue`, and `configurationId`.
#
# @option params [Integer] :max_results
# The total number of items to return in a single page of output. The
# maximum value is 100.
#
# @option params [String] :next_token
# A token to start the list. Use this token to get the next set of
# results.
#
# @return [Types::DescribeTagsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DescribeTagsResponse#tags #tags} => Array<Types::ConfigurationTag>
# * {Types::DescribeTagsResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.describe_tags({
# filters: [
# {
# name: "FilterName", # required
# values: ["FilterValue"], # required
# },
# ],
# max_results: 1,
# next_token: "NextToken",
# })
#
# @example Response structure
#
# resp.tags #=> Array
# resp.tags[0].configuration_type #=> String, one of "SERVER", "PROCESS", "CONNECTION", "APPLICATION"
# resp.tags[0].configuration_id #=> String
# resp.tags[0].key #=> String
# resp.tags[0].value #=> String
# resp.tags[0].time_of_creation #=> Time
# resp.next_token #=> String
#
# @overload describe_tags(params = {})
# @param [Hash] params ({})
def describe_tags(params = {}, options = {})
req = build_request(:describe_tags, params)
req.send_request(options)
end
# Disassociates one or more configuration items from an application.
#
# @option params [required, String] :application_configuration_id
# Configuration ID of an application from which each item is
# disassociated.
#
# @option params [required, Array<String>] :configuration_ids
# Configuration ID of each item to be disassociated from an application.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.disassociate_configuration_items_from_application({
# application_configuration_id: "ApplicationId", # required
# configuration_ids: ["ConfigurationId"], # required
# })
#
# @overload disassociate_configuration_items_from_application(params = {})
# @param [Hash] params ({})
def disassociate_configuration_items_from_application(params = {}, options = {})
req = build_request(:disassociate_configuration_items_from_application, params)
req.send_request(options)
end
# Deprecated. Use `StartExportTask` instead.
#
# Exports all discovered configuration data to an Amazon S3 bucket or an
# application that enables you to view and evaluate the data. Data
# includes tags and tag associations, processes, connections, servers,
# and system performance. This API returns an export ID that you can
# query using the *DescribeExportConfigurations* API. The system imposes
# a limit of two configuration exports in six hours.
#
# @return [Types::ExportConfigurationsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ExportConfigurationsResponse#export_id #export_id} => String
#
# @example Response structure
#
# resp.export_id #=> String
#
# @overload export_configurations(params = {})
# @param [Hash] params ({})
def export_configurations(params = {}, options = {})
req = build_request(:export_configurations, params)
req.send_request(options)
end
# Retrieves a short summary of discovered assets.
#
# This API operation takes no request parameters and is called as is at
# the command prompt as shown in the example.
#
# @return [Types::GetDiscoverySummaryResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetDiscoverySummaryResponse#servers #servers} => Integer
# * {Types::GetDiscoverySummaryResponse#applications #applications} => Integer
# * {Types::GetDiscoverySummaryResponse#servers_mapped_to_applications #servers_mapped_to_applications} => Integer
# * {Types::GetDiscoverySummaryResponse#servers_mappedto_tags #servers_mappedto_tags} => Integer
# * {Types::GetDiscoverySummaryResponse#agent_summary #agent_summary} => Types::CustomerAgentInfo
# * {Types::GetDiscoverySummaryResponse#connector_summary #connector_summary} => Types::CustomerConnectorInfo
#
# @example Response structure
#
# resp.servers #=> Integer
# resp.applications #=> Integer
# resp.servers_mapped_to_applications #=> Integer
# resp.servers_mappedto_tags #=> Integer
# resp.agent_summary.active_agents #=> Integer
# resp.agent_summary.healthy_agents #=> Integer
# resp.agent_summary.black_listed_agents #=> Integer
# resp.agent_summary.shutdown_agents #=> Integer
# resp.agent_summary.unhealthy_agents #=> Integer
# resp.agent_summary.total_agents #=> Integer
# resp.agent_summary.unknown_agents #=> Integer
# resp.connector_summary.active_connectors #=> Integer
# resp.connector_summary.healthy_connectors #=> Integer
# resp.connector_summary.black_listed_connectors #=> Integer
# resp.connector_summary.shutdown_connectors #=> Integer
# resp.connector_summary.unhealthy_connectors #=> Integer
# resp.connector_summary.total_connectors #=> Integer
# resp.connector_summary.unknown_connectors #=> Integer
#
# @overload get_discovery_summary(params = {})
# @param [Hash] params ({})
def get_discovery_summary(params = {}, options = {})
req = build_request(:get_discovery_summary, params)
req.send_request(options)
end
# Retrieves a list of configuration items as specified by the value
# passed to the required parameter `configurationType`. Optional
# filtering may be applied to refine search results.
#
# @option params [required, String] :configuration_type
# A valid configuration identified by Application Discovery Service.
#
# @option params [Array<Types::Filter>] :filters
# You can filter the request using various logical operators and a
# *key*-*value* format. For example:
#
# `\{"key": "serverType", "value": "webServer"\}`
#
# For a complete list of filter options and guidance about using them
# with this action, see [Using the ListConfigurations Action][1] in the
# *AWS Application Discovery Service User Guide*.
#
#
#
# [1]: https://docs.aws.amazon.com/application-discovery/latest/userguide/discovery-api-queries.html#ListConfigurations
#
# @option params [Integer] :max_results
# The total number of items to return. The maximum value is 100.
#
# @option params [String] :next_token
# Token to retrieve the next set of results. For example, if a previous
# call to ListConfigurations returned 100 items, but you set
# `ListConfigurationsRequest$maxResults` to 10, you received a set of 10
# results along with a token. Use that token in this query to get the
# next set of 10.
#
# @option params [Array<Types::OrderByElement>] :order_by
# Certain filter criteria return output that can be sorted in ascending
# or descending order. For a list of output characteristics for each
# filter, see [Using the ListConfigurations Action][1] in the *AWS
# Application Discovery Service User Guide*.
#
#
#
# [1]: https://docs.aws.amazon.com/application-discovery/latest/userguide/discovery-api-queries.html#ListConfigurations
#
# @return [Types::ListConfigurationsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListConfigurationsResponse#configurations #configurations} => Array<Hash<String,String>>
# * {Types::ListConfigurationsResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.list_configurations({
# configuration_type: "SERVER", # required, accepts SERVER, PROCESS, CONNECTION, APPLICATION
# filters: [
# {
# name: "String", # required
# values: ["FilterValue"], # required
# condition: "Condition", # required
# },
# ],
# max_results: 1,
# next_token: "NextToken",
# order_by: [
# {
# field_name: "String", # required
# sort_order: "ASC", # accepts ASC, DESC
# },
# ],
# })
#
# @example Response structure
#
# resp.configurations #=> Array
# resp.configurations[0] #=> Hash
# resp.configurations[0]["String"] #=> String
# resp.next_token #=> String
#
# @overload list_configurations(params = {})
# @param [Hash] params ({})
def list_configurations(params = {}, options = {})
req = build_request(:list_configurations, params)
req.send_request(options)
end
# Retrieves a list of servers that are one network hop away from a
# specified server.
#
# @option params [required, String] :configuration_id
# Configuration ID of the server for which neighbors are being listed.
#
# @option params [Boolean] :port_information_needed
# Flag to indicate if port and protocol information is needed as part of
# the response.
#
# @option params [Array<String>] :neighbor_configuration_ids
# List of configuration IDs to test for one-hop-away.
#
# @option params [Integer] :max_results
# Maximum number of results to return in a single page of output.
#
# @option params [String] :next_token
# Token to retrieve the next set of results. For example, if you
# previously specified 100 IDs for
# `ListServerNeighborsRequest$neighborConfigurationIds` but set
# `ListServerNeighborsRequest$maxResults` to 10, you received a set of
# 10 results along with a token. Use that token in this query to get the
# next set of 10.
#
# @return [Types::ListServerNeighborsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListServerNeighborsResponse#neighbors #neighbors} => Array<Types::NeighborConnectionDetail>
# * {Types::ListServerNeighborsResponse#next_token #next_token} => String
# * {Types::ListServerNeighborsResponse#known_dependency_count #known_dependency_count} => Integer
#
# @example Request syntax with placeholder values
#
# resp = client.list_server_neighbors({
# configuration_id: "ConfigurationId", # required
# port_information_needed: false,
# neighbor_configuration_ids: ["ConfigurationId"],
# max_results: 1,
# next_token: "String",
# })
#
# @example Response structure
#
# resp.neighbors #=> Array
# resp.neighbors[0].source_server_id #=> String
# resp.neighbors[0].destination_server_id #=> String
# resp.neighbors[0].destination_port #=> Integer
# resp.neighbors[0].transport_protocol #=> String
# resp.neighbors[0].connections_count #=> Integer
# resp.next_token #=> String
# resp.known_dependency_count #=> Integer
#
# @overload list_server_neighbors(params = {})
# @param [Hash] params ({})
def list_server_neighbors(params = {}, options = {})
req = build_request(:list_server_neighbors, params)
req.send_request(options)
end
# Start the continuous flow of agent's discovered data into Amazon
# Athena.
#
# @return [Types::StartContinuousExportResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::StartContinuousExportResponse#export_id #export_id} => String
# * {Types::StartContinuousExportResponse#s3_bucket #s3_bucket} => String
# * {Types::StartContinuousExportResponse#start_time #start_time} => Time
# * {Types::StartContinuousExportResponse#data_source #data_source} => String
# * {Types::StartContinuousExportResponse#schema_storage_config #schema_storage_config} => Hash<String,String>
#
# @example Response structure
#
# resp.export_id #=> String
# resp.s3_bucket #=> String
# resp.start_time #=> Time
# resp.data_source #=> String, one of "AGENT"
# resp.schema_storage_config #=> Hash
# resp.schema_storage_config["DatabaseName"] #=> String
#
# @overload start_continuous_export(params = {})
# @param [Hash] params ({})
def start_continuous_export(params = {}, options = {})
req = build_request(:start_continuous_export, params)
req.send_request(options)
end
# Instructs the specified agents or connectors to start collecting data.
#
# @option params [required, Array<String>] :agent_ids
# The IDs of the agents or connectors from which to start collecting
# data. If you send a request to an agent/connector ID that you do not
# have permission to contact, according to your AWS account, the service
# does not throw an exception. Instead, it returns the error in the
# *Description* field. If you send a request to multiple
# agents/connectors and you do not have permission to contact some of
# those agents/connectors, the system does not throw an exception.
# Instead, the system shows `Failed` in the *Description* field.
#
# @return [Types::StartDataCollectionByAgentIdsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::StartDataCollectionByAgentIdsResponse#agents_configuration_status #agents_configuration_status} => Array<Types::AgentConfigurationStatus>
#
# @example Request syntax with placeholder values
#
# resp = client.start_data_collection_by_agent_ids({
# agent_ids: ["AgentId"], # required
# })
#
# @example Response structure
#
# resp.agents_configuration_status #=> Array
# resp.agents_configuration_status[0].agent_id #=> String
# resp.agents_configuration_status[0].operation_succeeded #=> Boolean
# resp.agents_configuration_status[0].description #=> String
#
# @overload start_data_collection_by_agent_ids(params = {})
# @param [Hash] params ({})
def start_data_collection_by_agent_ids(params = {}, options = {})
req = build_request(:start_data_collection_by_agent_ids, params)
req.send_request(options)
end
# Begins the export of discovered data to an S3 bucket.
#
# If you specify `agentIds` in a filter, the task exports up to 72 hours
# of detailed data collected by the identified Application Discovery
# Agent, including network, process, and performance details. A time
# range for exported agent data may be set by using `startTime` and
# `endTime`. Export of detailed agent data is limited to five
# concurrently running exports.
#
# If you do not include an `agentIds` filter, summary data is exported
# that includes both AWS Agentless Discovery Connector data and summary
# data from AWS Discovery Agents. Export of summary data is limited to
# two exports per day.
#
# @option params [Array<String>] :export_data_format
# The file format for the returned export data. Default value is `CSV`.
# **Note:** *The* `GRAPHML` *option has been deprecated.*
#
# @option params [Array<Types::ExportFilter>] :filters
# If a filter is present, it selects the single `agentId` of the
# Application Discovery Agent for which data is exported. The `agentId`
# can be found in the results of the `DescribeAgents` API or CLI. If no
# filter is present, `startTime` and `endTime` are ignored and exported
# data includes both Agentless Discovery Connector data and summary data
# from Application Discovery agents.
#
# @option params [Time,DateTime,Date,Integer,String] :start_time
# The start timestamp for exported data from the single Application
# Discovery Agent selected in the filters. If no value is specified,
# data is exported starting from the first data collected by the agent.
#
# @option params [Time,DateTime,Date,Integer,String] :end_time
# The end timestamp for exported data from the single Application
# Discovery Agent selected in the filters. If no value is specified,
# exported data includes the most recent data collected by the agent.
#
# @return [Types::StartExportTaskResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::StartExportTaskResponse#export_id #export_id} => String
#
# @example Request syntax with placeholder values
#
# resp = client.start_export_task({
# export_data_format: ["CSV"], # accepts CSV, GRAPHML
# filters: [
# {
# name: "FilterName", # required
# values: ["FilterValue"], # required
# condition: "Condition", # required
# },
# ],
# start_time: Time.now,
# end_time: Time.now,
# })
#
# @example Response structure
#
# resp.export_id #=> String
#
# @overload start_export_task(params = {})
# @param [Hash] params ({})
def start_export_task(params = {}, options = {})
req = build_request(:start_export_task, params)
req.send_request(options)
end
# Starts an import task, which allows you to import details of your
# on-premises environment directly into AWS Migration Hub without having
# to use the Application Discovery Service (ADS) tools such as the
# Discovery Connector or Discovery Agent. This gives you the option to
# perform migration assessment and planning directly from your imported
# data, including the ability to group your devices as applications and
# track their migration status.
#
# To start an import request, do this:
#
# 1. Download the specially formatted comma separated value (CSV)
# import template, which you can find here:
# [https://s3-us-west-2.amazonaws.com/templates-7cffcf56-bd96-4b1c-b45b-a5b42f282e46/import\_template.csv][1].
#
# 2. Fill out the template with your server and application data.
#
# 3. Upload your import file to an Amazon S3 bucket, and make a note of
# it's Object URL. Your import file must be in the CSV format.
#
# 4. Use the console or the `StartImportTask` command with the AWS CLI
# or one of the AWS SDKs to import the records from your file.
#
# For more information, including step-by-step procedures, see
# [Migration Hub Import][2] in the *AWS Application Discovery Service
# User Guide*.
#
# <note markdown="1"> There are limits to the number of import tasks you can create (and
# delete) in an AWS account. For more information, see [AWS Application
# Discovery Service Limits][3] in the *AWS Application Discovery Service
# User Guide*.
#
# </note>
#
#
#
# [1]: https://s3-us-west-2.amazonaws.com/templates-7cffcf56-bd96-4b1c-b45b-a5b42f282e46/import_template.csv
# [2]: https://docs.aws.amazon.com/application-discovery/latest/userguide/discovery-import.html
# [3]: https://docs.aws.amazon.com/application-discovery/latest/userguide/ads_service_limits.html
#
# @option params [String] :client_request_token
# Optional. A unique token that you can provide to prevent the same
# import request from occurring more than once. If you don't provide a
# token, a token is automatically generated.
#
# Sending more than one `StartImportTask` request with the same client
# request token will return information about the original import task
# with that client request token.
#
# **A suitable default value is auto-generated.** You should normally
# not need to pass this option.**
#
# @option params [required, String] :name
# A descriptive name for this request. You can use this name to filter
# future requests related to this import task, such as identifying
# applications and servers that were included in this import task. We
# recommend that you use a meaningful name for each import task.
#
# @option params [required, String] :import_url
# The URL for your import file that you've uploaded to Amazon S3.
#
# <note markdown="1"> If you're using the AWS CLI, this URL is structured as follows:
# `s3://BucketName/ImportFileName.CSV`
#
# </note>
#
# @return [Types::StartImportTaskResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::StartImportTaskResponse#task #task} => Types::ImportTask
#
# @example Request syntax with placeholder values
#
# resp = client.start_import_task({
# client_request_token: "ClientRequestToken",
# name: "ImportTaskName", # required
# import_url: "ImportURL", # required
# })
#
# @example Response structure
#
# resp.task.import_task_id #=> String
# resp.task.client_request_token #=> String
# resp.task.name #=> String
# resp.task.import_url #=> String
# resp.task.status #=> String, one of "IMPORT_IN_PROGRESS", "IMPORT_COMPLETE", "IMPORT_COMPLETE_WITH_ERRORS", "IMPORT_FAILED", "IMPORT_FAILED_SERVER_LIMIT_EXCEEDED", "IMPORT_FAILED_RECORD_LIMIT_EXCEEDED", "DELETE_IN_PROGRESS", "DELETE_COMPLETE", "DELETE_FAILED", "DELETE_FAILED_LIMIT_EXCEEDED", "INTERNAL_ERROR"
# resp.task.import_request_time #=> Time
# resp.task.import_completion_time #=> Time
# resp.task.import_deleted_time #=> Time
# resp.task.server_import_success #=> Integer
# resp.task.server_import_failure #=> Integer
# resp.task.application_import_success #=> Integer
# resp.task.application_import_failure #=> Integer
# resp.task.errors_and_failed_entries_zip #=> String
#
# @overload start_import_task(params = {})
# @param [Hash] params ({})
def start_import_task(params = {}, options = {})
req = build_request(:start_import_task, params)
req.send_request(options)
end
# Stop the continuous flow of agent's discovered data into Amazon
# Athena.
#
# @option params [required, String] :export_id
# The unique ID assigned to this export.
#
# @return [Types::StopContinuousExportResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::StopContinuousExportResponse#start_time #start_time} => Time
# * {Types::StopContinuousExportResponse#stop_time #stop_time} => Time
#
# @example Request syntax with placeholder values
#
# resp = client.stop_continuous_export({
# export_id: "ConfigurationsExportId", # required
# })
#
# @example Response structure
#
# resp.start_time #=> Time
# resp.stop_time #=> Time
#
# @overload stop_continuous_export(params = {})
# @param [Hash] params ({})
def stop_continuous_export(params = {}, options = {})
req = build_request(:stop_continuous_export, params)
req.send_request(options)
end
# Instructs the specified agents or connectors to stop collecting data.
#
# @option params [required, Array<String>] :agent_ids
# The IDs of the agents or connectors from which to stop collecting
# data.
#
# @return [Types::StopDataCollectionByAgentIdsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::StopDataCollectionByAgentIdsResponse#agents_configuration_status #agents_configuration_status} => Array<Types::AgentConfigurationStatus>
#
# @example Request syntax with placeholder values
#
# resp = client.stop_data_collection_by_agent_ids({
# agent_ids: ["AgentId"], # required
# })
#
# @example Response structure
#
# resp.agents_configuration_status #=> Array
# resp.agents_configuration_status[0].agent_id #=> String
# resp.agents_configuration_status[0].operation_succeeded #=> Boolean
# resp.agents_configuration_status[0].description #=> String
#
# @overload stop_data_collection_by_agent_ids(params = {})
# @param [Hash] params ({})
def stop_data_collection_by_agent_ids(params = {}, options = {})
req = build_request(:stop_data_collection_by_agent_ids, params)
req.send_request(options)
end
# Updates metadata about an application.
#
# @option params [required, String] :configuration_id
# Configuration ID of the application to be updated.
#
# @option params [String] :name
# New name of the application to be updated.
#
# @option params [String] :description
# New description of the application to be updated.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.update_application({
# configuration_id: "ApplicationId", # required
# name: "String",
# description: "String",
# })
#
# @overload update_application(params = {})
# @param [Hash] params ({})
def update_application(params = {}, options = {})
req = build_request(:update_application, 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-applicationdiscoveryservice'
context[:gem_version] = '1.32.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
| 43.295469 | 321 | 0.666525 |
1ca8e25d257b1a94b71ba4bc435e115b78ae5e56 | 1,679 | # frozen_string_literal: true
# Copyright 2019 Steven C Hartley
# Copyright 2020 Matthew B. Gray
# Copyright 2020 Victoria Garcia
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class MembershipMailer < ApplicationMailer
include ApplicationHelper
default from: $member_services_email
def login_link(token:, email:, shortcode:)
@token = token
@shortcode = shortcode
@worldcon_public_name = worldcon_public_name
@worldcon_greeting_sentence_excited = worldcon_greeting_sentence_excited
@worldcon_homepage_url = worldcon_url_homepage
mail(
to: email,
subject: "#{worldcon_public_name} Login Link for #{email}"
)
end
def transfer(from:, to:, owner_name:, membership_number:)
@worldcon_public_name = worldcon_public_name
@worldcon_greeting_sentence_excited = worldcon_greeting_sentence_excited
@worldcon_homepage_url = worldcon_url_homepage
@from = from
@to = to
@owner_name = owner_name
@membership_number = membership_number
mail(
to: [from, to],
cc: $member_services_email,
subject: "#{worldcon_public_name}: Transferred ##{membership_number} from #{from} to #{to}"
)
end
end
| 33.58 | 97 | 0.744491 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.