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
|
---|---|---|---|---|---|
e946f4aea7232c1563e0f084263faf634b885aba | 1,939 | module GemInstaller
class GemInteractionHandler
attr_writer :dependent_gem, :noninteractive_chooser_class, :valid_platform_selector
DEPENDENCY_PROMPT = 'Install required dependency'
def initialize
check_rubygems_version
end
def handle_ask_yes_no(question)
return unless question.index(DEPENDENCY_PROMPT)
message = "Error: RubyGems is prompting to install a required dependency, and you have not " +
"specified the '--install-dependencies' option for the current gem. You must modify your " +
"geminstaller config file to either specify the '--install-depencencies' (-y) " +
"option, or explicitly add an entry for the dependency gem earlier in the file.\n"
raise GemInstaller::UnauthorizedDependencyPromptError.new(message)
end
def handle_choose_from_list(question, list, noninteractive_chooser = nil)
noninteractive_chooser ||= @noninteractive_chooser_class.new
valid_platforms = nil
if dependent_gem_with_platform_specified?(list, noninteractive_chooser) or noninteractive_chooser.uninstall_list_type?(question)
valid_platforms = [@dependent_gem.platform]
else
valid_platforms = @valid_platform_selector.select(@dependent_gem.platform)
end
noninteractive_chooser.choose(question, list, @dependent_gem.name, @dependent_gem.version, valid_platforms)
end
def dependent_gem_with_platform_specified?(list, noninteractive_chooser)
noninteractive_chooser.dependent_gem?(@dependent_gem.name, list) and @dependent_gem.platform
end
def check_rubygems_version
if GemInstaller::RubyGemsVersionChecker.matches?('>=0.9.5')
# gem_interaction_handler is not used for RubyGems >= 0.9.5
raise RuntimeError.new("Internal GemInstaller Error: GemInteractionHandler should not be used for RubyGems >= 0.9.5")
end
end
end
end
| 46.166667 | 134 | 0.734399 |
28fee95e4c2f73459b1bee422b5c5222f62bf45e | 2,224 | #
# Cookbook Name:: delivery-cluster
# Spec:: helpers_analytics_spec
#
# Author:: Salim Afiune (<[email protected]>)
#
# Copyright:: Copyright (c) 2015 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'spec_helper'
describe DeliveryCluster::Exceptions::AttributeNotFound do
subject { described_class.new("node['delivery-cluster']") }
describe '#new' do
it 'is a Runtime error that accepts an attribute' do
expect(subject).to be_a RuntimeError
expect(subject.attr).to eql("node['delivery-cluster']")
end
end
describe '#to_s' do
let(:output) { "Attribute 'node['delivery-cluster']' not found" }
it 'prints out a message pointing to the missing attribute' do
expect(subject.to_s).to eql(output)
end
end
end
describe DeliveryCluster::Exceptions::LicenseNotFound do
subject { described_class.new("node['delivery-cluster']['license']") }
describe '#new' do
it 'is a Runtime error that accepts an attribute' do
expect(subject).to be_a RuntimeError
expect(subject.attr).to eql("node['delivery-cluster']['license']")
end
end
describe '#to_s' do
let(:output) do
<<-EOM.gsub(/^ {6}/, '')
***************************************************
Chef Delivery requires a valid license to run.
To acquire a license, please contact your CHEF
account representative.
Please set `node['delivery-cluster']['license']`
in your environment file.
***************************************************
EOM
end
it 'prints out a message saying that the license is missing' do
expect(subject.to_s).to eql(output)
end
end
end
| 30.054054 | 74 | 0.663669 |
088301ac1470f02d1469e6f298280cd5fc44863a | 9,202 | require 'psych/scalar_scanner'
unless defined?(Regexp::NOENCODING)
Regexp::NOENCODING = 32
end
module Psych
module Visitors
###
# This class walks a YAML AST, converting each node to ruby
class ToRuby < Psych::Visitors::Visitor
def initialize ss = ScalarScanner.new
super()
@st = {}
@ss = ss
@domain_types = Psych.domain_types
end
def accept target
result = super
return result if @domain_types.empty? || !target.tag
key = target.tag.sub(/^[!\/]*/, '').sub(/(,\d+)\//, '\1:')
key = "tag:#{key}" unless key =~ /^(tag:|x-private)/
if @domain_types.key? key
value, block = @domain_types[key]
return block.call value, result
end
result
end
def deserialize o
if klass = Psych.load_tags[o.tag]
instance = klass.allocate
if instance.respond_to?(:init_with)
coder = Psych::Coder.new(o.tag)
coder.scalar = o.value
instance.init_with coder
end
return instance
end
return o.value if o.quoted
return @ss.tokenize(o.value) unless o.tag
case o.tag
when '!binary', 'tag:yaml.org,2002:binary'
o.value.unpack('m').first
when /^!(?:str|ruby\/string)(?::(.*))?/, 'tag:yaml.org,2002:str'
klass = resolve_class($1)
if klass
klass.allocate.replace o.value
else
o.value
end
when '!ruby/object:BigDecimal'
require 'bigdecimal'
BigDecimal._load o.value
when "!ruby/object:DateTime"
require 'date'
@ss.parse_time(o.value).to_datetime
when "!ruby/object:Complex"
Complex(o.value)
when "!ruby/object:Rational"
Rational(o.value)
when "!ruby/class", "!ruby/module"
resolve_class o.value
when "tag:yaml.org,2002:float", "!float"
Float(@ss.tokenize(o.value))
when "!ruby/regexp"
o.value =~ /^\/(.*)\/([mixn]*)$/
source = $1
options = 0
lang = nil
($2 || '').split('').each do |option|
case option
when 'x' then options |= Regexp::EXTENDED
when 'i' then options |= Regexp::IGNORECASE
when 'm' then options |= Regexp::MULTILINE
when 'n' then options |= Regexp::NOENCODING
else lang = option
end
end
Regexp.new(*[source, options, lang].compact)
when "!ruby/range"
args = o.value.split(/([.]{2,3})/, 2).map { |s|
accept Nodes::Scalar.new(s)
}
args.push(args.delete_at(1) == '...')
Range.new(*args)
when /^!ruby\/sym(bol)?:?(.*)?$/
o.value.to_sym
else
@ss.tokenize o.value
end
end
private :deserialize
def visit_Psych_Nodes_Scalar o
register o, deserialize(o)
end
def visit_Psych_Nodes_Sequence o
if klass = Psych.load_tags[o.tag]
instance = klass.allocate
if instance.respond_to?(:init_with)
coder = Psych::Coder.new(o.tag)
coder.seq = o.children.map { |c| accept c }
instance.init_with coder
end
return instance
end
case o.tag
when '!omap', 'tag:yaml.org,2002:omap'
map = register(o, Psych::Omap.new)
o.children.each { |a|
map[accept(a.children.first)] = accept a.children.last
}
map
when /^!(?:seq|ruby\/array):(.*)$/
klass = resolve_class($1)
list = register(o, klass.allocate)
o.children.each { |c| list.push accept c }
list
else
list = register(o, [])
o.children.each { |c| list.push accept c }
list
end
end
def visit_Psych_Nodes_Mapping o
return revive(Psych.load_tags[o.tag], o) if Psych.load_tags[o.tag]
return revive_hash({}, o) unless o.tag
case o.tag
when /^!(?:str|ruby\/string)(?::(.*))?/, 'tag:yaml.org,2002:str'
klass = resolve_class($1)
members = Hash[*o.children.map { |c| accept c }]
string = members.delete 'str'
if klass
string = klass.allocate.replace string
register(o, string)
end
init_with(string, members.map { |k,v| [k.to_s.sub(/^@/, ''),v] }, o)
when /^!ruby\/array:(.*)$/
klass = resolve_class($1)
list = register(o, klass.allocate)
members = Hash[o.children.map { |c| accept c }.each_slice(2).to_a]
list.replace members['internal']
members['ivars'].each do |ivar, v|
list.instance_variable_set ivar, v
end
list
when /^!ruby\/struct:?(.*)?$/
klass = resolve_class($1)
if klass
s = register(o, klass.allocate)
members = {}
struct_members = s.members.map { |x| x.to_sym }
o.children.each_slice(2) do |k,v|
member = accept(k)
value = accept(v)
if struct_members.include?(member.to_sym)
s.send("#{member}=", value)
else
members[member.to_s.sub(/^@/, '')] = value
end
end
init_with(s, members, o)
else
members = o.children.map { |c| accept c }
h = Hash[*members]
Struct.new(*h.map { |k,v| k.to_sym }).new(*h.map { |k,v| v })
end
when '!ruby/range'
h = Hash[*o.children.map { |c| accept c }]
register o, Range.new(h['begin'], h['end'], h['excl'])
when /^!ruby\/exception:?(.*)?$/
h = Hash[*o.children.map { |c| accept c }]
e = build_exception((resolve_class($1) || Exception),
h.delete('message'))
init_with(e, h, o)
when '!set', 'tag:yaml.org,2002:set'
set = Psych::Set.new
@st[o.anchor] = set if o.anchor
o.children.each_slice(2) do |k,v|
set[accept(k)] = accept(v)
end
set
when '!ruby/object:Complex'
h = Hash[*o.children.map { |c| accept c }]
register o, Complex(h['real'], h['image'])
when '!ruby/object:Rational'
h = Hash[*o.children.map { |c| accept c }]
register o, Rational(h['numerator'], h['denominator'])
when /^!ruby\/object:?(.*)?$/
name = $1 || 'Object'
obj = revive((resolve_class(name) || Object), o)
obj
when /^!map:(.*)$/, /^!ruby\/hash:(.*)$/
revive_hash resolve_class($1).new, o
when '!omap', 'tag:yaml.org,2002:omap'
map = register(o, Psych::Omap.new)
o.children.each_slice(2) do |l,r|
map[accept(l)] = accept r
end
map
else
revive_hash({}, o)
end
end
def visit_Psych_Nodes_Document o
accept o.root
end
def visit_Psych_Nodes_Stream o
o.children.map { |c| accept c }
end
def visit_Psych_Nodes_Alias o
@st.fetch(o.anchor) { raise BadAlias, "Unknown alias: #{o.anchor}" }
end
private
def register node, object
@st[node.anchor] = object if node.anchor
object
end
def revive_hash hash, o
@st[o.anchor] = hash if o.anchor
o.children.each_slice(2) { |k,v|
key = accept(k)
if key == '<<'
case v
when Nodes::Alias
hash.merge! accept(v)
when Nodes::Sequence
accept(v).reverse_each do |value|
hash.merge! value
end
else
hash[key] = accept(v)
end
else
hash[key] = accept(v)
end
}
hash
end
def revive klass, node
s = klass.allocate
@st[node.anchor] = s if node.anchor
h = Hash[*node.children.map { |c| accept c }]
init_with(s, h, node)
end
def init_with o, h, node
c = Psych::Coder.new(node.tag)
c.map = h
if o.respond_to?(:init_with)
o.init_with c
elsif o.respond_to?(:yaml_initialize)
if $VERBOSE
warn "Implementing #{o.class}#yaml_initialize is deprecated, please implement \"init_with(coder)\""
end
o.yaml_initialize c.tag, c.map
else
h.each { |k,v| o.instance_variable_set(:"@#{k}", v) }
end
o
end
# Convert +klassname+ to a Class
def resolve_class klassname
return nil unless klassname and not klassname.empty?
name = klassname
retried = false
begin
path2class(name)
rescue ArgumentError, NameError => ex
unless retried
name = "Struct::#{name}"
retried = ex
retry
end
raise retried
end
end
end
end
end
| 28.313846 | 111 | 0.501304 |
ab61895d57c89006e27311c4f2dd98acbd2f7ac8 | 1,167 | module Fog
module Compute
class Vsphere
class Real
def get_compute_resource(name, datacenter_name)
compute_resource = get_raw_compute_resource(name, datacenter_name)
raise(Fog::Compute::Vsphere::NotFound) unless compute_resource
compute_resource_attributes(compute_resource, datacenter_name)
end
protected
def get_raw_compute_resource(name, datacenter_name)
find_raw_datacenter(datacenter_name).find_compute_resource(name)
end
end
class Mock
def get_compute_resource(_name, _datacenter_name)
{
id: 'domain-s7',
name: 'fake-host',
totalCpu: 33_504,
totalMemory: 154_604_142_592,
numCpuCores: 12,
numCpuThreads: 24,
effectiveCpu: 32_247,
effectiveMemory: 135_733,
numHosts: 1,
numEffectiveHosts: 1,
overallStatus: 'gray',
overallCpuUsage: 15_682,
overallMemoryUsage: 132_755,
effective: true,
isSingleHost: true
}
end
end
end
end
end
| 27.785714 | 76 | 0.594687 |
f834f67522f3b67bf06692df298f46c819f6b628 | 164 | require_relative './directives/audio'
require_relative './directives/audio_player'
module Ralyxa
module ResponseEntities
module Directives
end
end
end
| 16.4 | 44 | 0.780488 |
e2ad6eb81cd76f12ffec7dcc1a39d1d7cd265994 | 139 | SimpleCov.profiles.define 'lib' do
add_filter '/test/'
add_filter '/config/'
add_group 'Libraries', 'lib'
end
SimpleCov.start 'lib'
| 17.375 | 34 | 0.71223 |
21ce2186776631bdc6523228da9161abdcfff5cd | 657 | class ItemsController < ApplicationController
before_action :set_item
def create
@item = current_user.items.new(item_params)
@item.project = @project
if @item.save
render json: @item, status: 201
else
render json: {errors: @comment.errors.full_messages}, status: 400
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_item
@project = Project.find(params[:project_id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def item_params
params.require(:item).permit(:content)
end
end
| 23.464286 | 88 | 0.681887 |
62fd49efdf229bebd32a9e7cc3a68facb4f2d711 | 17,480 | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
<<<<<<< HEAD
ActiveRecord::Schema.define(version: 20150701054424) do
=======
ActiveRecord::Schema.define(version: 20150703082842) do
>>>>>>> b4fe7ae84d5466694e50e724bebe182f01f461a7
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "actividad_economicas", force: true do |t|
t.string "nombre"
t.integer "mall_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "actividad_economicas", ["mall_id"], name: "index_actividad_economicas_on_mall_id", using: :btree
create_table "arrendatarios", force: true do |t|
t.string "nombre"
t.string "rif"
t.string "direccion"
t.string "telefono"
t.string "nombre_rl"
t.string "cedula_rl"
t.string "email_rl"
t.string "telefono_rl"
t.integer "mall_id"
t.datetime "created_at"
t.datetime "updated_at"
t.text "registro_mercantil"
end
add_index "arrendatarios", ["mall_id"], name: "index_arrendatarios_on_mall_id", using: :btree
create_table "bancos", force: true do |t|
t.string "nombre"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "calendario_no_laborables", force: true do |t|
t.date "fecha"
t.string "motivo"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "mall_id"
end
add_index "calendario_no_laborables", ["mall_id"], name: "index_calendario_no_laborables_on_mall_id", using: :btree
create_table "cambio_monedas", force: true do |t|
t.date "fecha"
t.decimal "cambio_ml_x_usd"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "mall_id"
end
add_index "cambio_monedas", ["mall_id"], name: "index_cambio_monedas_on_mall_id", using: :btree
create_table "canon_alquilers", force: true do |t|
t.date "fecha"
t.decimal "canon_fijo_ml"
t.decimal "canon_fijo_usd"
t.decimal "porc_canon_ventas"
t.integer "monto_minimo_ventas"
t.datetime "created_at"
t.datetime "updated_at"
end
<<<<<<< HEAD
=======
create_table "clientes", force: true do |t|
t.string "nombre"
t.string "RIF"
t.string "direccion"
t.string "telefono"
t.string "nombre_rl"
t.string "profesion_rl"
t.string "cedula_rl"
t.string "email_rl"
t.string "telefono_rl"
t.string "nombre_contacto"
t.string "profesion_contacto"
t.string "cedula_contacto"
t.string "email_contacto"
t.string "telefono_contacto"
t.integer "mall_id"
t.integer "tipo_servicio_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "clientes", ["mall_id"], name: "index_clientes_on_mall_id", using: :btree
add_index "clientes", ["tipo_servicio_id"], name: "index_clientes_on_tipo_servicio_id", using: :btree
>>>>>>> b4fe7ae84d5466694e50e724bebe182f01f461a7
create_table "cobranza_alquilers", force: true do |t|
t.string "nro_recibo"
t.date "fecha_recibo_cobro"
t.integer "anio_alquiler"
t.integer "mes_alquiler"
t.float "monto_canon_fijo", default: 0.0
t.float "monto_canon_variable", default: 0.0
t.float "monto_alquiler"
t.float "monto_alquiler_usd"
t.boolean "facturado", default: true
t.float "saldo_deudor"
t.integer "tienda_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "cobranza_alquilers", ["tienda_id"], name: "index_cobranza_alquilers_on_tienda_id", using: :btree
create_table "contrato_alquilers", force: true do |t|
t.string "nro_contrato"
t.date "fecha_inicio"
t.date "fecha_fin"
t.string "archivo_contrato"
<<<<<<< HEAD
t.decimal "canon_fijo_ml", precision: 30, scale: 2, default: 0.0
t.decimal "canon_fijo_usd", precision: 30, scale: 2, default: 0.0
t.decimal "porc_canon_ventas", precision: 30, scale: 2, default: 0.0
t.decimal "monto_minimo_ventas", precision: 30, scale: 2, default: 0.0
t.boolean "estado_contrato"
=======
t.decimal "canon_fijo_ml"
t.decimal "canon_fijo_usd"
t.decimal "porc_canon_ventas"
t.decimal "monto_minimo_ventas"
t.boolean "estado_contrato"
t.integer "tipo_canon_alquiler"
>>>>>>> b4fe7ae84d5466694e50e724bebe182f01f461a7
t.integer "tienda_id"
t.datetime "created_at"
t.datetime "updated_at"
t.boolean "requerida_venta"
t.integer "tipo_canon_alquiler_id"
end
add_index "contrato_alquilers", ["tienda_id"], name: "index_contrato_alquilers_on_tienda_id", using: :btree
create_table "cuenta_bancaria", force: true do |t|
t.string "nro_cta"
t.string "tipo_cuenta"
t.string "beneficiario"
t.string "doc_identidad"
t.integer "banco_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "mall_id"
end
add_index "cuenta_bancaria", ["banco_id"], name: "index_cuenta_bancaria_on_banco_id", using: :btree
add_index "cuenta_bancaria", ["mall_id"], name: "index_cuenta_bancaria_on_mall_id", using: :btree
create_table "detalle_pago_alquilers", force: true do |t|
t.float "monto", default: 0.0
t.integer "pago_alquiler_id"
t.integer "factura_alquiler_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "detalle_pago_alquilers", ["factura_alquiler_id"], name: "index_detalle_pago_alquilers_on_factura_alquiler_id", using: :btree
add_index "detalle_pago_alquilers", ["pago_alquiler_id"], name: "index_detalle_pago_alquilers_on_pago_alquiler_id", using: :btree
create_table "documento_ventas", force: true do |t|
t.string "titulo"
t.string "nombre"
t.integer "venta_mensual_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "documento_ventas", ["venta_mensual_id"], name: "index_documento_ventas_on_venta_mensual_id", using: :btree
create_table "factura_alquilers", force: true do |t|
t.date "fecha"
t.string "nro_factura"
t.float "monto_factura", default: 0.0
t.float "monto_abono", default: 0.0
t.float "saldo_deudor"
t.boolean "canon_fijo"
t.integer "cobranza_alquiler_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "factura_alquilers", ["cobranza_alquiler_id"], name: "index_factura_alquilers_on_cobranza_alquiler_id", using: :btree
create_table "idiomas", force: true do |t|
t.string "nombre"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "locals", force: true do |t|
t.string "foto"
t.string "nro_local"
t.string "ubicacion_pasillo"
t.integer "tipo_local_id"
t.integer "nivel_mall_id"
t.integer "mall_id"
t.datetime "created_at"
t.datetime "updated_at"
t.decimal "area_planta", default: 0.0
t.decimal "area_terraza", default: 0.0
t.decimal "area_mezanina", default: 0.0
t.integer "tipo_estado_local"
end
add_index "locals", ["mall_id"], name: "index_locals_on_mall_id", using: :btree
add_index "locals", ["nivel_mall_id"], name: "index_locals_on_nivel_mall_id", using: :btree
add_index "locals", ["tipo_local_id"], name: "index_locals_on_tipo_local_id", using: :btree
create_table "malls", force: true do |t|
t.string "nombre"
t.string "abreviado"
t.string "rif"
t.string "direccion_fiscal"
t.string "telefono"
t.integer "pai_id"
t.integer "cuenta_bancarium_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "malls", ["cuenta_bancarium_id"], name: "index_malls_on_cuenta_bancarium_id", using: :btree
add_index "malls", ["pai_id"], name: "index_malls_on_pai_id", using: :btree
create_table "malls_roles", id: false, force: true do |t|
t.integer "role_id"
t.integer "mall_id"
end
add_index "malls_roles", ["mall_id", "role_id"], name: "index_malls_roles_on_mall_id_and_role_id", using: :btree
create_table "monedas", force: true do |t|
t.string "nombre"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "nivel_malls", force: true do |t|
t.string "nombre"
t.integer "mall_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "nivel_malls", ["mall_id"], name: "index_nivel_malls_on_mall_id", using: :btree
create_table "nro_facturas", force: true do |t|
t.integer "numero"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "nro_recibos", force: true do |t|
t.integer "numero"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "nro_recibos_cobros", force: true do |t|
t.integer "numero"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "numeros_controls", force: true do |t|
t.integer "nro_contrato"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "pago_alquilers", force: true do |t|
t.string "nro_recibo"
t.date "fecha"
t.string "nro_cheque_confirmacion"
t.string "archivo_transferencia"
t.string "banco_emisor"
t.integer "tipo_pago"
<<<<<<< HEAD
t.integer "cuenta_bancarium_id"
t.datetime "created_at"
t.datetime "updated_at"
=======
t.datetime "created_at"
t.datetime "updated_at"
t.integer "cuenta_bancaria_id"
>>>>>>> b4fe7ae84d5466694e50e724bebe182f01f461a7
t.decimal "monto"
t.decimal "monto_usd"
t.boolean "conciliado", default: true
end
<<<<<<< HEAD
add_index "pago_alquilers", ["cuenta_bancarium_id"], name: "index_pago_alquilers_on_cuenta_bancarium_id", using: :btree
=======
>>>>>>> b4fe7ae84d5466694e50e724bebe182f01f461a7
create_table "pais", force: true do |t|
t.string "nombre"
t.integer "idioma_id"
t.integer "moneda_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "pais", ["idioma_id"], name: "index_pais_on_idioma_id", using: :btree
add_index "pais", ["moneda_id"], name: "index_pais_on_moneda_id", using: :btree
create_table "permissions", force: true do |t|
t.string "subject_class", limit: 60, default: ""
t.string "action", limit: 50, default: "", null: false
t.string "name", limit: 50, default: "", null: false
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "permissions_roles", id: false, force: true do |t|
t.integer "role_id"
t.integer "permission_id"
end
add_index "permissions_roles", ["permission_id", "role_id"], name: "index_permissions_roles_on_permission_id_and_role_id", using: :btree
create_table "plantilla_contrato_alquilers", force: true do |t|
t.string "nombre"
t.text "contenido"
t.integer "mall_id"
t.integer "tipo_canon_alquiler_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "plantilla_contrato_alquilers", ["mall_id"], name: "index_plantilla_contrato_alquilers_on_mall_id", using: :btree
add_index "plantilla_contrato_alquilers", ["tipo_canon_alquiler_id"], name: "index_plantilla_contrato_alquilers_on_tipo_canon_alquiler_id", using: :btree
<<<<<<< HEAD
=======
create_table "precio_servicios", force: true do |t|
t.date "fecha"
t.float "precio_usd"
t.integer "tipo_servicio_id"
t.integer "tipo_contrato_servicio_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "precio_servicios", ["tipo_contrato_servicio_id"], name: "index_precio_servicios_on_tipo_contrato_servicio_id", using: :btree
add_index "precio_servicios", ["tipo_servicio_id"], name: "index_precio_servicios_on_tipo_servicio_id", using: :btree
>>>>>>> b4fe7ae84d5466694e50e724bebe182f01f461a7
create_table "roles", force: true do |t|
t.string "name", limit: 50, default: "", null: false
t.integer "role_type", default: 0, null: false
t.datetime "created_at"
t.datetime "updated_at"
t.integer "tipo_servicio_id"
end
add_index "roles", ["tipo_servicio_id"], name: "index_roles_on_tipo_servicio_id", using: :btree
create_table "tiendas", force: true do |t|
t.string "nombre"
t.date "fecha_apertura"
t.date "fecha_cierre"
t.boolean "abierta"
t.date "fecha_fin_contrato_actual"
t.integer "local_id"
t.integer "actividad_economica_id"
t.integer "arrendatario_id"
t.datetime "created_at"
t.datetime "updated_at"
t.decimal "monto_garantia", precision: 30, scale: 2
t.decimal "monto_garantia_usd", precision: 30, scale: 2
t.string "codigo_contable"
end
add_index "tiendas", ["actividad_economica_id"], name: "index_tiendas_on_actividad_economica_id", using: :btree
add_index "tiendas", ["arrendatario_id"], name: "index_tiendas_on_arrendatario_id", using: :btree
add_index "tiendas", ["local_id"], name: "index_tiendas_on_local_id", using: :btree
create_table "tipo_canon_alquilers", force: true do |t|
t.string "tipo"
t.datetime "created_at"
t.datetime "updated_at"
end
<<<<<<< HEAD
=======
create_table "tipo_contrato_servicios", force: true do |t|
t.string "tipo"
t.datetime "created_at"
t.datetime "updated_at"
end
>>>>>>> b4fe7ae84d5466694e50e724bebe182f01f461a7
create_table "tipo_locals", force: true do |t|
t.string "tipo"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "tipo_servicios", force: true do |t|
t.string "tipo"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "user_tiendas", force: true do |t|
t.integer "user_id"
t.integer "tienda_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "user_tiendas", ["tienda_id"], name: "index_user_tiendas_on_tienda_id", using: :btree
add_index "user_tiendas", ["user_id"], name: "index_user_tiendas_on_user_id", using: :btree
create_table "users", force: true do |t|
t.string "username", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "email", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "unique_session_id", limit: 20
t.string "name"
t.string "cellphone"
t.string "avatar"
t.integer "mall_id"
t.boolean "locked", default: false
t.integer "role_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
add_index "users", ["role_id"], name: "index_users_on_role_id", using: :btree
<<<<<<< HEAD
add_index "users", ["username"], name: "index_users_on_username", unique: true, using: :btree
=======
>>>>>>> b4fe7ae84d5466694e50e724bebe182f01f461a7
create_table "venta_diaria", force: true do |t|
t.date "fecha"
t.float "monto"
t.float "monto_notas_credito", default: 0.0
t.float "monto_bruto"
t.float "monto_bruto_usd"
t.float "monto_costo_venta", default: 0.0
t.float "monto_neto", default: 0.0
t.float "monto_neto_usd", default: 0.0
t.boolean "editable", default: true
t.integer "venta_mensual_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "venta_diaria", ["venta_mensual_id"], name: "index_venta_diaria_on_venta_mensual_id", using: :btree
<<<<<<< HEAD
create_table "venta_mensuals", force: true do |t|
=======
create_table "venta_mensual", force: true do |t|
>>>>>>> b4fe7ae84d5466694e50e724bebe182f01f461a7
t.integer "anio"
t.integer "mes"
t.float "monto"
t.float "monto_notas_credito", default: 0.0
t.float "monto_bruto"
t.float "monto_bruto_USD"
t.float "monto_costo_venta", default: 0.0
t.float "monto_neto", default: 0.0
t.float "monto_neto_USD", default: 0.0
t.boolean "editable", default: true
t.integer "tienda_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "venta_mensuals", ["tienda_id"], name: "index_venta_mensuals_on_tienda_id", using: :btree
end
| 34.27451 | 155 | 0.678604 |
087c0e1434dccdef09aa0d367b351a2bdbd09dd7 | 654 | require 'json'
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
Pod::Spec.new do |s|
s.name = 'FluentUI-React-Native-Avatar'
s.version = package['version']
s.summary = package['description']
s.license = package['license']
s.authors = package['author']
s.homepage = package['homepage']
s.source = { :git => "https://github.com/microsoft/fluentui-react-native.git", :tag => "#{s.version}" }
s.swift_version = "5"
s.ios.deployment_target = "11.0"
s.ios.source_files = "ios/*.{swift,h,m}"
s.dependency 'React'
s.dependency 'MicrosoftFluentUI', '~> 0.1.16'
end | 29.727273 | 115 | 0.61315 |
b97402c4086627f8cb0178497e234eb6e618fe9e | 270 | Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root to: "static_pages#root"
namespace :api, defaults: { format: :json } do
resources :posts, except: [:new, :edit]
end
end
| 30 | 101 | 0.718519 |
4aaef0354a4ff62a6532efdf6498ab74286c3b16 | 1,400 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'paper_rock_scissors/version'
Gem::Specification.new do |spec|
spec.name = "paper_rock_scissors"
spec.version = PaperRockScissors::VERSION
spec.authors = ["Stephen Mayeux"]
spec.email = ["[email protected]"]
spec.summary = %q{Very simple game of paper, rock, scissors.}
spec.description = %q{I am an English teacher in South Korea, and the children here don't play rock, paper, scissors. They play PAPER, ROCK, SCISSORS!}
spec.homepage = "https://github.com/StephenMayeux/paper_rock_scissors"
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
# delete this section to allow pushing this gem to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "https://rubygems.org"
else
raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.11"
spec.add_development_dependency "rake", "~> 10.0"
end
| 42.424242 | 155 | 0.680714 |
ff71b39a6287a4c25edba0bf9ef96e40c718fd7e | 2,222 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::ServiceFabric::Mgmt::V2017_07_01_preview
module Models
#
# Defines a health policy used to evaluate the health of the cluster or of
# a cluster node.
#
class ClusterHealthPolicy
include MsRestAzure
# @return [Integer] The maximum allowed percentage of unhealthy nodes
# before reporting an error. For example, to allow 10% of nodes to be
# unhealthy, this value would be 10.
attr_accessor :max_percent_unhealthy_nodes
# @return [Integer] The maximum allowed percentage of unhealthy
# applications before reporting an error. For example, to allow 10% of
# applications to be unhealthy, this value would be 10.
attr_accessor :max_percent_unhealthy_applications
#
# Mapper for ClusterHealthPolicy class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ClusterHealthPolicy',
type: {
name: 'Composite',
class_name: 'ClusterHealthPolicy',
model_properties: {
max_percent_unhealthy_nodes: {
client_side_validation: true,
required: false,
serialized_name: 'maxPercentUnhealthyNodes',
constraints: {
InclusiveMaximum: 100,
InclusiveMinimum: 0
},
type: {
name: 'Number'
}
},
max_percent_unhealthy_applications: {
client_side_validation: true,
required: false,
serialized_name: 'maxPercentUnhealthyApplications',
constraints: {
InclusiveMaximum: 100,
InclusiveMinimum: 0
},
type: {
name: 'Number'
}
}
}
}
}
end
end
end
end
| 31.295775 | 78 | 0.567957 |
2166f81689078670a0ee67da0225e4b9674b0890 | 296 | class CreateRewardsTable < ActiveRecord::Migration[5.0]
def change
create_table :gamfora_rewards do |t|
t.references :action, foreign_key: true
t.references :metric, foreign_key: true
t.integer :count
t.string :text_value
t.timestamps
end
end
end
| 24.666667 | 55 | 0.672297 |
4afeaca8be8f9945e73725cf98b096e2d8b65320 | 535 | require 'rails/generators/active_record'
require "rails/generators/migration"
class ActsAsIdBankCertification::MigrationGenerator < ::Rails::Generators::Base
include Rails::Generators::Migration
source_root File.expand_path('../templates', __FILE__)
desc 'Installs ActsAsIdBankCertification migration file.'
def install
migration_template 'migration.rb', 'db/migrate/create_id_bank_documents.rb'
end
def self.next_migration_number(dirname)
ActiveRecord::Generators::Base.next_migration_number(dirname)
end
end
| 31.470588 | 79 | 0.801869 |
7983c3d49ee0dd81b8ad0e3a494fb08517f5ed00 | 2,288 | require 'features_helper'
describe 'visit home page' do
before do
UserRepository.clear
PostRepository.clear
visit '/'
end
shared_examples 'default page' do
it 'should have app title' do
expect(page).to have_content('SS Tweets')
end
it 'should have Home on Nav bar' do
expect(page).to have_content('Home')
end
it 'should have About on Nav bar' do
expect(page).to have_content('About')
end
end
context 'when login with Guest user' do
it_behaves_like 'default page'
it 'should have Login on Nav bar' do
expect(page).to have_content('Sign in')
end
end
context 'when login with user account' do
let!(:user) { UserRepository.create(User.new(email: '[email protected]', password: 'abc123', name: 'Khai')) }
before do
visit '/login'
fill_in 'Email', with: '[email protected]'
fill_in 'Password', with: 'abc123'
click_button 'Sign In'
end
it_behaves_like 'default page'
it 'should have Logout on Nav bar' do
expect(page).to have_content('Logout')
end
it 'has post textarea' do
expect(page).to have_css('form #post_content')
end
it 'has submit button' do
expect(page).to have_css('form button[type=submit]')
end
describe 'posts list' do
it 'hash element with id is posts' do
expect(page).to have_css 'div#posts'
end
context 'user has posts' do
before do
PostRepository.create(Post.new(content: Faker::Lorem.characters(100), author_id: user.id))
visit '/'
end
it 'has element with class is post-item' do
expect(page).to have_css 'div#posts div.post-item'
end
it 'has author name element' do
expect(page).to have_css 'div#posts div.post-item .author'
end
it 'has timestamp element' do
expect(page).to have_css 'div#posts div.post-item .timestamp'
end
it 'has post content element' do
expect(page).to have_css 'div#posts div.post-item .content'
end
end
context 'user has no posts' do
it 'has content of #posts element is empty' do
expect(page).not_to have_css 'div#posts div.post-item'
end
end
end
end
end
| 28.6 | 113 | 0.626311 |
e2aa97b9866555c30f6ee80a864ab36e12b496a9 | 10,562 | # frozen_string_literal: true
module Discordrb
# Mixin for the attributes members and private members should have
module MemberAttributes
# @return [Time] when this member joined the server.
attr_reader :joined_at
# @return [Time, nil] when this member boosted this server, `nil` if they haven't.
attr_reader :boosting_since
# @return [String, nil] the nickname this member has, or `nil` if it has none.
attr_reader :nick
alias_method :nickname, :nick
# @return [Array<Role>] the roles this member has.
attr_reader :roles
# @return [Server] the server this member is on.
attr_reader :server
end
# A member is a user on a server. It differs from regular users in that it has roles, voice statuses and things like
# that.
class Member < DelegateClass(User)
# @return [true, false] whether this member is muted server-wide.
def mute
voice_state_attribute(:mute)
end
# @return [true, false] whether this member is deafened server-wide.
def deaf
voice_state_attribute(:deaf)
end
# @return [true, false] whether this member has muted themselves.
def self_mute
voice_state_attribute(:self_mute)
end
# @return [true, false] whether this member has deafened themselves.
def self_deaf
voice_state_attribute(:self_deaf)
end
# @return [Channel] the voice channel this member is in.
def voice_channel
voice_state_attribute(:voice_channel)
end
alias_method :muted?, :mute
alias_method :deafened?, :deaf
alias_method :self_muted?, :self_mute
alias_method :self_deafened?, :self_deaf
include MemberAttributes
# @!visibility private
def initialize(data, server, bot)
@bot = bot
@user = bot.ensure_user(data['user'])
super @user # Initialize the delegate class
# Somehow, Discord doesn't send the server ID in the standard member format...
raise ArgumentError, 'Cannot create a member without any information about the server!' if server.nil? && data['guild_id'].nil?
@server = server || bot.server(data['guild_id'].to_i)
# Initialize the roles by getting the roles from the server one-by-one
update_roles(data['roles']) unless @server.nil?
@nick = data['nick']
@joined_at = data['joined_at'] ? Time.parse(data['joined_at']) : nil
@boosting_since = data['premium_since'] ? Time.parse(data['premium_since']) : nil
end
# @return [true, false] if this user is a Nitro Booster of this server.
def boosting?
!@boosting_since.nil?
end
# @return [true, false] whether this member is the server owner.
def owner?
@server.owner == self
end
# @param role [Role, String, Integer] the role to check or its ID.
# @return [true, false] whether this member has the specified role.
def role?(role)
role = role.resolve_id
@roles.any? { |e| e.id == role }
end
# @see Member#set_roles
def roles=(role)
set_roles(role)
end
# Bulk sets a member's roles.
# @param role [Role, Array<Role>] The role(s) to set.
# @param reason [String] The reason the user's roles are being changed.
def set_roles(role, reason = nil)
role_ids = role_id_array(role)
API::Server.update_member(@bot.token, @server.id, @user.id, roles: role_ids, reason: reason)
end
# Adds and removes roles from a member.
# @param add [Role, Array<Role>] The role(s) to add.
# @param remove [Role, Array<Role>] The role(s) to remove.
# @param reason [String] The reason the user's roles are being changed.
# @example Remove the 'Member' role from a user, and add the 'Muted' role to them.
# to_add = server.roles.find {|role| role.name == 'Muted'}
# to_remove = server.roles.find {|role| role.name == 'Member'}
# member.modify_roles(to_add, to_remove)
def modify_roles(add, remove, reason = nil)
add_role_ids = role_id_array(add)
remove_role_ids = role_id_array(remove)
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids - remove_role_ids + add_role_ids).uniq
API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids, reason: reason)
end
# Adds one or more roles to this member.
# @param role [Role, Array<Role, String, Integer>, String, Integer] The role(s), or their ID(s), to add.
# @param reason [String] The reason the user's roles are being changed.
def add_role(role, reason = nil)
role_ids = role_id_array(role)
if role_ids.count == 1
API::Server.add_member_role(@bot.token, @server.id, @user.id, role_ids[0], reason)
else
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids + role_ids).uniq
API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids, reason: reason)
end
end
# Removes one or more roles from this member.
# @param role [Role, Array<Role>] The role(s) to remove.
# @param reason [String] The reason the user's roles are being changed.
def remove_role(role, reason = nil)
role_ids = role_id_array(role)
if role_ids.count == 1
API::Server.remove_member_role(@bot.token, @server.id, @user.id, role_ids[0], reason)
else
old_role_ids = @roles.map(&:id)
new_role_ids = old_role_ids.reject { |i| role_ids.include?(i) }
API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids, reason: reason)
end
end
# @return [Role] the highest role this member has.
def highest_role
@roles.max_by(&:position)
end
# @return [Role, nil] the role this member is being hoisted with.
def hoist_role
hoisted_roles = @roles.select(&:hoist)
return nil if hoisted_roles.empty?
hoisted_roles.max_by(&:position)
end
# @return [Role, nil] the role this member is basing their colour on.
def colour_role
coloured_roles = @roles.select { |v| v.colour.combined.nonzero? }
return nil if coloured_roles.empty?
coloured_roles.max_by(&:position)
end
alias_method :color_role, :colour_role
# @return [ColourRGB, nil] the colour this member has.
def colour
return nil unless colour_role
colour_role.color
end
alias_method :color, :colour
# Server deafens this member.
def server_deafen
API::Server.update_member(@bot.token, @server.id, @user.id, deaf: true)
end
# Server undeafens this member.
def server_undeafen
API::Server.update_member(@bot.token, @server.id, @user.id, deaf: false)
end
# Server mutes this member.
def server_mute
API::Server.update_member(@bot.token, @server.id, @user.id, mute: true)
end
# Server unmutes this member.
def server_unmute
API::Server.update_member(@bot.token, @server.id, @user.id, mute: false)
end
# Bans this member from the server.
# @param message_days [Integer] How many days worth of messages sent by the member should be deleted.
# @param reason [String] The reason this member is being banned.
def ban(message_days = 0, reason: nil)
@server.ban(@user, message_days, reason: reason)
end
# Unbans this member from the server.
# @param reason [String] The reason this member is being unbanned.
def unban(reason = nil)
@server.unban(@user, reason)
end
# Kicks this member from the server.
# @param reason [String] The reason this member is being kicked.
def kick(reason = nil)
@server.kick(@user, reason)
end
# @see Member#set_nick
def nick=(nick)
set_nick(nick)
end
alias_method :nickname=, :nick=
# Sets or resets this member's nickname. Requires the Change Nickname permission for the bot itself and Manage
# Nicknames for other users.
# @param nick [String, nil] The string to set the nickname to, or nil if it should be reset.
# @param reason [String] The reason the user's nickname is being changed.
def set_nick(nick, reason = nil)
# Discord uses the empty string to signify 'no nickname' so we convert nil into that
nick ||= ''
if @user.current_bot?
API::User.change_own_nickname(@bot.token, @server.id, nick, reason)
else
API::Server.update_member(@bot.token, @server.id, @user.id, nick: nick, reason: nil)
end
end
alias_method :set_nickname, :set_nick
# @return [String] the name the user displays as (nickname if they have one, username otherwise)
def display_name
nickname || username
end
# Update this member's roles
# @note For internal use only.
# @!visibility private
def update_roles(role_ids)
@roles = [@server.role(@server.id)]
role_ids.each do |id|
# It is possible for members to have roles that do not exist
# on the server any longer. See https://github.com/shardlab/discordrb/issues/371
role = @server.role(id)
@roles << role if role
end
end
# Update this member's nick
# @note For internal use only.
# @!visibility private
def update_nick(nick)
@nick = nick
end
# Update this member's boosting timestamp
# @note For internal user only.
# @!visibility private
def update_boosting_since(time)
@boosting_since = time
end
# Update this member
# @note For internal use only.
# @!visibility private
def update_data(data)
update_roles(data['roles']) if data['roles']
update_nick(data['nick']) if data.key?('nick')
@mute = data['mute'] if data.key?('mute')
@deaf = data['deaf'] if data.key?('deaf')
@joined_at = Time.parse(data['joined_at']) if data['joined_at']
end
include PermissionCalculator
# Overwriting inspect for debug purposes
def inspect
"<Member user=#{@user.inspect} server=#{@server.inspect} joined_at=#{@joined_at} roles=#{@roles.inspect} voice_channel=#{@voice_channel.inspect} mute=#{@mute} deaf=#{@deaf} self_mute=#{@self_mute} self_deaf=#{@self_deaf}>"
end
private
# Utility method to get a list of role IDs from one role or an array of roles
def role_id_array(role)
if role.is_a? Array
role.map(&:resolve_id)
else
[role.resolve_id]
end
end
# Utility method to get data out of this member's voice state
def voice_state_attribute(name)
voice_state = @server.voice_states[@user.id]
voice_state&.send name
end
end
end
| 33.318612 | 228 | 0.660954 |
2688277e09cbe6ceb25d28b5f6c6d825a248c731 | 1,025 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'newrelic_grabby/version'
Gem::Specification.new do |spec|
spec.name = "newrelic_grabby"
spec.version = NewRelic::Grabby::VERSION
spec.authors = ["Lew Cirne"]
spec.email = ["[email protected]"]
spec.description = "Prototype for automatic custom attribute instrumentation for New Relic Insights"
spec.summary = "Prototype for automatic custom attribute instrumentation for New Relic Insights"
spec.homepage = "http://newrelic.com/insights"
spec.license = "New Relic"
spec.add_dependency "newrelic_rpm", "~> 3.9.1"
spec.files = `git ls-files`.split($/)
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.3"
spec.add_development_dependency "rake"
end
| 39.423077 | 104 | 0.68 |
1d9cbcdb959ac320e24b9ef84c73ce4f08746158 | 751 | require "rspec/expectations"
RSpec::Matchers.define :terminate do |code|
actual = nil
def supports_block_expectations?
true
end
match do |block|
begin
block.call
rescue SystemExit => e
actual = e.status
end
actual and actual == status_code
end
chain :with_code do |status_code|
@status_code = status_code
end
failure_message do |block|
"expected block to call exit(#{status_code}) but exit" +
(actual.nil? ? " not called" : "(#{actual}) was called")
end
failure_message_when_negated do |block|
"expected block not to call exit(#{status_code})"
end
description do
"expect block to call exit(#{status_code})"
end
def status_code
@status_code ||= 0
end
end
| 18.317073 | 62 | 0.663116 |
bbc5cac62bf4a7a6373172222064c18bfc4f92b7 | 293 | module SimpleAttribute
module Helpers
def simple_attribute_for(record, attribute, options = {})
options = options.merge(record: record, attribute: attribute)
SimpleAttribute::Builder.new(self, options).render
end
alias :attribute_for :simple_attribute_for
end
end
| 26.636364 | 67 | 0.740614 |
5d51362c0181a076f91d07b17a9a195f6571dfef | 1,216 | require 'uri'
require 'open-uri'
class Attachment < ApplicationRecord
belongs_to :account
belongs_to :message
mount_uploader :file, AttachmentUploader #used for images
enum file_type: [:image, :audio, :video, :file, :location, :fallback]
before_create :set_file_extension
def push_event_data
data = {
id: id,
message_id: message_id,
file_type: file_type,
account_id: account_id
}
if [:image, :file, :audio, :video].include? file_type.to_sym
data.merge!({
extension: extension,
data_url: file_url,
thumb_url: file.try(:thumb).try(:url) #will exist only for images
})
elsif :location == file_type.to_sym
data.merge!({
coordinates_lat: coordinates_lat,
coordinates_long: coordinates_long,
fallback_title: fallback_title,
data_url: external_url
})
elsif :fallback == file_type.to_sym
data.merge!({
fallback_title: fallback_title,
data_url: external_url
})
end
data
end
private
def set_file_extension
if self.external_url && !self.fallback?
self.extension = Pathname.new(URI(external_url).path).extname rescue nil
end
end
end
| 24.816327 | 78 | 0.662007 |
1a04ea869ac52435d4f00ce23426d28d60300e8e | 2,067 | module Bosh::Cli::Command
class Events < Base
usage 'events'
desc 'Show all deployment events'
option '--before-id id', Integer, 'Show all events with id less or equal to given id'
option '--before timestamp', String, 'Show all events by the given timestamp (ex: 2016-05-08 17:26:32)'
option '--after timestamp', String, 'Show all events after the given timestamp (ex: 2016-05-08 17:26:32)'
option '--deployment name', String, 'Filter all events by the Deployment Name'
option '--task id', String, 'Filter all events by the task id'
option '--instance job_name/id', String, 'Filter all events by the instance job_name/id'
def list
auth_required
show_events
end
private
def show_events
events = director.list_events(options)
if events.empty?
nl
say('No events')
nl
return
end
events_table = table do |t|
headings = ['ID', 'Time', 'User', 'Action', 'Object type', 'Object ID', 'Task', 'Dep', 'Inst', 'Context']
t.headings = headings
events.each do |event|
row = []
id = event['id']
id = "#{id} <- #{event['parent_id']}" if event['parent_id']
row << id
row << Time.at(event['timestamp']).utc.strftime('%a %b %d %H:%M:%S %Z %Y')
row << event['user']
row << event['action']
row << event['object_type']
row << event.fetch('object_name', '-')
row << event.fetch('task', '-')
row << event.fetch('deployment', '-')
row << event.fetch('instance', '-')
if !event.key?('context') || event['context'] == nil
event['context'] = {}
end
context = event['error'] ? {'error' => event['error'].to_s.truncate(80)}.merge(event['context']) : event['context']
context = context.empty? ? '-' : context.map { |k, v| "#{k}: #{v}" }.join(",\n")
row << context
t << row
end
end
nl
say(events_table)
nl
end
end
end
| 34.45 | 125 | 0.545718 |
abd5aa7822f774b3fedd6f48a394ddead5c46066 | 732 | # 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)
require 'json'
json = JSON.parse(File.read('app/assets/json/movies.json'))
movies = json['results']
movies.each do |movie_hash|
Movie.create(
title: movie_hash["title"],
release_date: movie_hash["release_date"],
synopsis: movie_hash["overview"],
poster: movie_hash["poster_path"],
movie_id: movie_hash["id"]
)
end | 36.6 | 111 | 0.68306 |
5d0e6e6a709adbaf209ea88ea5fa9b779bae63f5 | 3,753 | require 'spec_helper'
require 'vcap_request_id'
module CloudFoundry
module Middleware
RSpec.describe VcapRequestId do
let(:middleware) { described_class.new(app) }
let(:app) { FakeApp.new }
let(:app_response) { [200, {}, 'a body'] }
let(:uuid_regex) { '\w+-\w+-\w+-\w+-\w+' }
class FakeApp
attr_accessor :last_request_id, :last_env_input
def call(env)
@last_request_id = ::VCAP::Request.current_id
@last_env_input = env
[200, {}, 'a body']
end
end
describe 'handling the request' do
context 'setting the request_id in the logger' do
it 'has assigned it before passing the request' do
middleware.call('HTTP_X_VCAP_REQUEST_ID' => 'specific-request-id')
expect(app.last_request_id).to match(/^specific-request-id::#{uuid_regex}$/)
end
it 'nils it out after the request has been processed' do
middleware.call('HTTP_X_VCAP_REQUEST_ID' => 'specific-request-id')
expect(::VCAP::Request.current_id).to eq(nil)
end
end
context 'when HTTP_X_VCAP_REQUEST_ID is passed in from outside' do
it 'includes it in cf.request_id and appends a uuid to ensure uniqueness' do
middleware.call('HTTP_X_VCAP_REQUEST_ID' => 'request-id')
expect(app.last_env_input['cf.request_id']).to match(/^request-id::#{uuid_regex}$/)
end
it 'accepts only alphanumeric request ids' do
middleware.call('HTTP_X_VCAP_REQUEST_ID' => '; X-Hacked-Header: Stuff')
expect(app.last_env_input['cf.request_id']).to match(/^X-Hacked-HeaderStuff::#{uuid_regex}$/)
end
it 'accepts only 255 characters in the passed-in request id' do
middleware.call('HTTP_X_VCAP_REQUEST_ID' => 'x' * 500)
truncated_passed_id = 'x' * 255
expect(app.last_env_input['cf.request_id']).to match(/^#{truncated_passed_id}::#{uuid_regex}$/)
end
context 'when HTTP_X_REQUEST_ID is also passed in from outside' do
it 'preferes HTTP_X_VCAP_REQUEST_ID' do
middleware.call('HTTP_X_VCAP_REQUEST_ID' => 'request-id', 'HTTP_X_REQUEST_ID' => 'not-vcap-request-id')
expect(app.last_env_input['cf.request_id']).to match(/^request-id::#{uuid_regex}$/)
end
end
end
context 'when HTTP_X_VCAP_REQUEST_ID is NOT passed in from outside' do
it 'generates a uuid as the request_id' do
middleware.call({})
expect(app.last_env_input['cf.request_id']).to match(/^#{uuid_regex}$/)
end
context 'when HTTP_X_REQUEST_ID is passed in from outside' do
it 'includes it in cf.request_id and appends a uuid to ensure uniqueness' do
middleware.call('HTTP_X_REQUEST_ID' => 'not-vcap-request-id')
expect(app.last_env_input['cf.request_id']).to match(/^not-vcap-request-id::#{uuid_regex}$/)
end
end
end
end
describe 'the response' do
context 'when the request id is passed in' do
it 'is returned in the response' do
_, response_headers, _ = middleware.call('HTTP_X_VCAP_REQUEST_ID' => 'request-id')
expect(response_headers['X-VCAP-Request-ID']).to match(/^request-id::#{uuid_regex}$/)
end
end
context 'when the request id is NOT passed in' do
it 'returns a generated id in the response' do
_, response_headers, _ = middleware.call({})
expect(response_headers['X-VCAP-Request-ID']).to match(/^#{uuid_regex}$/)
end
end
end
end
end
end
| 37.909091 | 117 | 0.609646 |
187645cf12661ab252ecb89e69b0002fab088214 | 56 | module Em
module Smtp
VERSION = "0.0.1"
end
end
| 9.333333 | 21 | 0.607143 |
e91285568ce47fbb676d7681057f9eb8d814b8cd | 1,873 | #
# Author:: Salim Alam (<[email protected]>)
# Copyright:: Copyright 2015 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require "chef/win32/api/system"
require "chef/win32/error"
require "ffi"
class Chef
module ReservedNames::Win32
class System
include Chef::ReservedNames::Win32::API::System
extend Chef::ReservedNames::Win32::API::System
def self.get_system_wow64_directory
ptr = FFI::MemoryPointer.new(:char, 255, true)
succeeded = GetSystemWow64DirectoryA(ptr, 255)
if succeeded == 0
raise Win32APIError, "Failed to get Wow64 system directory"
end
ptr.read_string.strip
end
def self.wow64_disable_wow64_fs_redirection
original_redirection_state = FFI::MemoryPointer.new(:pointer)
succeeded = Wow64DisableWow64FsRedirection(original_redirection_state)
if succeeded == 0
raise Win32APIError, "Failed to disable Wow64 file redirection"
end
original_redirection_state
end
def self.wow64_revert_wow64_fs_redirection(original_redirection_state)
succeeded = Wow64RevertWow64FsRedirection(original_redirection_state)
if succeeded == 0
raise Win32APIError, "Failed to revert Wow64 file redirection"
end
end
end
end
end
| 29.730159 | 78 | 0.711692 |
113655347f761c3f5d0b087caa209e4c44822b02 | 5,020 | #--
# This file is part of the X12Parser library that provides tools to
# manipulate X12 messages using Ruby native syntax.
#
# http://x12parser.rubyforge.org
#
# Copyright (C) 2012 P&D Technical Solutions, LLC.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#++
#
require 'test_helper'
class Test271Parse < Minitest::Test
MESSAGE = <<~EDI.gsub(/\n/, '')
ISA*00* *00* *ZZ*6175910AAC21T *ZZ*54503516A *061130*1445*U*00401*309242122*0*T*:~
GS*HB*617591011C21T*545035165*20030924*21000083*309001*X*004010X092A1~
ST*271*COMP1420~
BHT*0022*11**20030924*21000083~
HL*1**20*1~
NM1*PR*2*Texas Medicaid/Healthcare Services*****PI*617591011C21T~
HL*2*1*21*1~
NM1*1P*1******XX*1234567890~
HL*3*2*22*0~
TRN*1*COMPASS 21*3617591011~
TRN*2*109834652831*9877281234*RADIOLOGY~
TRN*2*98175-012547*9877281234*RADIOLOGY~
NM1*IL*1*LASTNAME*FIRSTNAME*M**SUFFIX*MI*444115555~
REF*SY*123456789~
REF*F6*123456789012~
REF*Q4*999888777~
REF*EJ*111222333444555~
N3*123 STREET~
N4*DALLAS*TX*75024**CY*85~
DMG*D8*19850201*M~
INS*Y*18*001*25~
EB*1*IND*30**PLANABBVDE~
EB*R*IND*30*OT*CC~
REF*6P*G123456*EMPLOYERNAME~
DTP*193*D8*20000501~
DTP*194*D8*20000601~
LS*2120~
NM1*PR*2*INCOMPANYNAME~
N3*123 STREET~
N4*DALLAS*TX*75024~
PER*IC**WP*2145551212~
LE*2120~
EB*R*IND*30*OT*CC~
REF*6P*G123456*EMPLOYERNAME~
DTP*193*D8*20000501~
DTP*194*D8*20000601~
LS*2120~
NM1*IL*1*LASTNAME*FIRST*M**SUFFIX*MI*123456789~
LE*2120~
EB*R*IND*30*OT*EE~
REF*6P*G345678 *EMPLOYERNAME~
DTP*193*D8*20000701~
DTP*194*D8*20000801~
LS*2120~
NM1*IL*1*LASTNAME*THIRD*M**SUFFIX*MI*345678901~
LE*2120~
SE*45*COMP1420~
GE*1*309001~
IEA*1*309242122~
EDI
def setup
@message = MESSAGE
@parser = X12::Parser.new('271.xml')
@r = @parser.parse('271', @message)
end
def test_header
assert_equal("00", @r.ISA.AuthorizationInformationQualifier)
assert_equal(" ", @r.ISA.AuthorizationInformation)
assert_equal("00", @r.ISA.SecurityInformationQualifier)
assert_equal(" ", @r.ISA.SecurityInformation)
assert_equal("ZZ", @r.ISA.InterchangeIdQualifier1)
assert_equal("6175910AAC21T ", @r.ISA.InterchangeSenderId)
assert_equal("ZZ", @r.ISA.InterchangeIdQualifier2)
assert_equal("54503516A ", @r.ISA.InterchangeReceiverId)
assert_equal("061130", @r.ISA.InterchangeDate)
assert_equal("1445", @r.ISA.InterchangeTime)
assert_equal("U", @r.ISA.InterchangeControlStandardsIdentifier)
assert_equal("00401", @r.ISA.InterchangeControlVersionNumber)
assert_equal("309242122", @r.ISA.InterchangeControlNumber)
assert_equal("0", @r.ISA.AcknowledgmentRequested)
assert_equal("T", @r.ISA.UsageIndicator)
assert_equal(":", @r.ISA.ComponentElementSeparator)
assert_equal("HB", @r.GS.FunctionalIdentifierCode)
assert_equal("617591011C21T", @r.GS.ApplicationSendersCode)
assert_equal("545035165", @r.GS.ApplicationReceiversCode)
assert_equal("20030924", @r.GS.Date)
assert_equal("21000083", @r.GS.Time)
assert_equal("309001", @r.GS.GroupControlNumber)
assert_equal("X", @r.GS.ResponsibleAgencyCode)
assert_equal("004010X092A1", @r.GS.VersionReleaseIndustryIdentifierCode)
assert_equal("271", @r.ST.TransactionSetIdentifierCode)
assert_equal("COMP1420", @r.ST.TransactionSetControlNumber)
end
def test_trailer
assert_equal("45", @r.SE.NumberOfIncludedSegments)
assert_equal("COMP1420", @r.SE.TransactionSetControlNumber)
assert_equal("1", @r.GE.NumberOfTransactionSetsIncluded)
assert_equal("309001", @r.GE.GroupControlNumber)
assert_equal("1", @r.IEA.NumberOfIncludedFunctionalGroups)
assert_equal("309242122", @r.IEA.InterchangeControlNumber)
end
def test_each_loop
# each loop for Loops
# each loop for Segments
skip()
end
def test_various_fields
skip()
end
def test_timing
return unless ENV['BENCH']
start = Time.now
X12::TEST_REPEAT.times do
@r = @parser.parse('271', @message)
end
finish = Time.now
puts sprintf('Parses per second, 271: %.2f, elapsed: %.1f', X12::TEST_REPEAT.to_f/(finish-start), finish-start)
end
end
| 33.466667 | 115 | 0.695219 |
e2fb300d4916e5bcd7e39520baa685b039e9c668 | 142 | class UniqueIndexOnUidAndProvider < ActiveRecord::Migration
def change
add_index :identities, [:uid, :provider], unique: true
end
end
| 23.666667 | 59 | 0.760563 |
01c8f774f4813b843e11fd6ec6de02590ab5280a | 1,327 | # Licensed to Elasticsearch B.V under one or more agreements.
# Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information
module Elasticsearch
module API
module Actions
# Deletes a script.
#
# @option arguments [String] :id Script ID
# @option arguments [Time] :timeout Explicit operation timeout
# @option arguments [Time] :master_timeout Specify timeout for connection to master
#
# @see https://www.elastic.co/guide/en/elasticsearch/reference/7.5/modules-scripting.html
#
def delete_script(arguments = {})
raise ArgumentError, "Required argument 'id' missing" unless arguments[:id]
arguments = arguments.clone
_id = arguments.delete(:id)
method = Elasticsearch::API::HTTP_DELETE
path = "_scripts/#{Utils.__listify(_id)}"
params = Utils.__validate_and_extract_params arguments, ParamsRegistry.get(__method__)
body = nil
perform_request(method, path, params, body).body
end
# Register this action with its valid params when the module is loaded.
#
# @since 6.2.0
ParamsRegistry.register(:delete_script, [
:timeout,
:master_timeout
].freeze)
end
end
end
| 31.595238 | 95 | 0.666918 |
38289d4a2cbd07324c174388538d1db90ad0652c | 939 | Pod::Spec.new do |s|
s.name = "JVFloatLabeledTextField"
s.version = "1.2.2"
s.summary = "The original UITextField subclass implementing the Float Label Pattern."
s.homepage = "http://github.com/jverdi/JVFloatLabeledTextField"
s.screenshot = "https://github-camo.global.ssl.fastly.net/be57d040ec0ce5d6467fb73564c6bcb6c76d5a7b/687474703a2f2f6472696262626c652e73332e616d617a6f6e6177732e636f6d2f75736572732f363431302f73637265656e73686f74732f313235343433392f666f726d2d616e696d6174696f6e2d5f6769665f2e676966"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "Jared Verdi" => "[email protected]" }
s.source = { :git => "https://github.com/jverdi/JVFloatLabeledTextField.git", :tag => s.version.to_s }
s.platform = :ios
s.source_files = 'JVFloatLabeledTextField/JVFloatLabeledTextField/*.{h,m}'
s.frameworks = 'Foundation', 'UIKit'
s.requires_arc = true
end
| 62.6 | 280 | 0.728435 |
21e83ad028a2d5b5fb4f92bfc3c5bc2bab5ace17 | 139 | class RemoveFailedAttemptsColumnFromUsers < ActiveRecord::Migration[5.2]
def change
remove_column :users, :failed_attempts
end
end
| 23.166667 | 72 | 0.798561 |
1d465fc5a64a070e7e200c48c8444ab9ae4ceb4d | 111 | require 'xxhash'
module DeterministicHash
def deterministic_hash(string)
XXhash.xxh32(string)
end
end
| 13.875 | 32 | 0.774775 |
bbc53164b8083093f9443f792f4ee14a9fcbc172 | 114 | # -*- coding:binary -*-
module MetasploitPayloads
VERSION = '2.0.29'
def self.version
VERSION
end
end
| 11.4 | 25 | 0.649123 |
1a269145a4d85f3df36f860b6398a379ad465861 | 496 | # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
Dummy::Application.config.secret_token = '9506d7264ae3e7d3451c8522cac8ba18f2ae02818514fd2e2f1c746e0d0582f8869cef8ce0a15299f907059d43435a8b810fc1a039d035af93ea2944e5c594c0'
| 62 | 171 | 0.832661 |
e80b55332e7b04264bc682b04638225e4c8d41dc | 197 | require "rubygems"
require 'bundler/setup'
require 'bundler/gem_tasks'
require "test/unit"
require "rack"
require "rack/test"
Test::Unit::TestCase.class_eval do
include Rack::Test::Methods
end
| 16.416667 | 34 | 0.766497 |
26c3f7c3533b1e9c77e62a96ca40ff4e68e85e9e | 974 | require 'fileutils'
module Interfaces
class FtpSource < FtpSourceBase
include FtpSession
def ftp_get_files ftp, regexp
logger.debug{"#{self}: ftp nlst"}
files = ftp.nlst.select{|name| name =~ regexp}
logger.debug{"#{self}: ftp nlst: found files: #{files&&files.inspect}"}
files.each do |name|
tmp = File.join dir, "#{name}.tmp"
logger.debug{"#{self}: ftp get: #{name} => #{tmp}"}
ftp.get name, tmp
case remote_mark_done
when String
logger.debug{"#{self}: ftp move to #{remote_mark_done}: #{name}"}
ftp.rename name, "#{name}#{remote_mark_done}"
when :delete
logger.debug{"#{self}: ftp delete: #{name}"}
ftp.delete name
end
Utils.untmp_pathes tmp
end
files
rescue Net::FTPPermError => e
unless e.message == '550'
logger.error{"#{self}: ftp error: #{e.inspect}"}
raise
end
end
end
end
| 27.828571 | 77 | 0.571869 |
f7aafe2e1f30df29fa2e2b16c434bb5450b6c29d | 513 | # frozen_string_literal: true
module Ebayr #:nodoc:
# A response to an Ebayr::Request.
class Response < Record
def initialize(request, response)
ActiveSupport::XmlMini.backend = 'Nokogiri'
@request = request
@command = @request.command if @request
@response = response
@body = response.body if @response
hash = self.class.from_xml(@body) if @body
response_data = hash["#{@command}Response"] if hash
super(response_data) if response_data
end
end
end
| 27 | 57 | 0.672515 |
ed78238de483885f5845e96fd5147ea4a2de058b | 12,771 | # Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
config.secret_key = '5c72fe9ca98a9862e235c7fb8277e3f6a02d41e0f941beebaa5271a712c46da90f5e4a04fde095d7f2f219cd41ec014c72d995837424164ae7ffc0f44eaa3742'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = '[email protected]'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require "devise/orm/#{CI_ORM}"
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [:email]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [:email]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:token]` will
# enable it only for token authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# :token = Support basic authentication with token authentication key
# :token_options = Support token authentication with options as defined in
# http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# :http_auth and :token_auth by adding those symbols to the array below.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments.
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = 'db4c2356895fab849584ee71a3467a20720ff9b629f27a0da70bd4176773c5360e25d453f1801c69e2e0e61f3a9b5631cda52d7da99b4ced83ea66940db3ce0e'
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed new email is stored in
# unconfirmed email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length. Default is 8..128.
config.password_length = 8..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^@]+@[^@]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_auth_token_on_timeout = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Configuration for :token_authenticatable
# Defines name of the authentication token params key
# config.token_authentication_key = :auth_token
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
end
| 49.30888 | 152 | 0.749432 |
e28522caafc2cb871f89d68f02fd7882c4e8d97c | 695 | require 'vagrant'
set :application, 'awesomeium'
set :repository, '.'
set :scm, :none # not recommended in production
set :deploy_via, :copy
server '192.168.33.10', :web, :app, :db, :primary => true
set :user, 'vagrant'
set :password, 'vagrant' # not recommended in production
set :deploy_to, "/home/#{user}/#{application}"
set :use_sudo, false
default_run_options[:pty] = true
# Toque options
set :cookbooks_paths, %w(spec/config/cookbooks)
namespace :vagrant do
task :up do
Vagrant::Environment.new.cli 'up'
end
task :destroy do
Vagrant::Environment.new.cli 'destroy'
end
end
task :spec do
toque.run_list "recipe[awesomeium]"
end
before 'spec', 'vagrant:up'
| 19.305556 | 57 | 0.699281 |
7a964e5b37b4812e4a4cb44312ceeecd5ed46c7a | 1,375 | require 'rails_helper'
RSpec.describe ConsumptionTaxRate, type: :model do
describe ".calc" do
it "returns nil when arg is nil" do
expect(ConsumptionTaxRate.calc_current(nil)).to be_nil
end
it "returns 8% of argument with floored" do
expect(ConsumptionTaxRate.calc_current(10)).to eq 0
expect(ConsumptionTaxRate.calc_current(11)).to eq 0
expect(ConsumptionTaxRate.calc_current(12)).to eq 0
expect(ConsumptionTaxRate.calc_current(13)).to eq 1
expect(ConsumptionTaxRate.calc_current(14)).to eq 1
expect(ConsumptionTaxRate.calc_current(15)).to eq 1
expect(ConsumptionTaxRate.calc_current(16)).to eq 1
expect(ConsumptionTaxRate.calc_current(17)).to eq 1
expect(ConsumptionTaxRate.calc_current(18)).to eq 1
expect(ConsumptionTaxRate.calc_current(19)).to eq 1
expect(ConsumptionTaxRate.calc_current(20)).to eq 1
expect(ConsumptionTaxRate.calc_current(21)).to eq 1
expect(ConsumptionTaxRate.calc_current(22)).to eq 1
expect(ConsumptionTaxRate.calc_current(23)).to eq 1
expect(ConsumptionTaxRate.calc_current(24)).to eq 1
expect(ConsumptionTaxRate.calc_current(25)).to eq 2
expect(ConsumptionTaxRate.calc_current(26)).to eq 2
expect(ConsumptionTaxRate.calc_current(99)).to eq 7
expect(ConsumptionTaxRate.calc_current(100)).to eq 8
end
end
end
| 44.354839 | 60 | 0.735273 |
6a7f8910cb89b1cc598a059a26cf004e9507fb22 | 43 | class AverageGrade < ApplicationRecord
end
| 14.333333 | 38 | 0.860465 |
bbd0b5ac8a924986b046cac6c40ebf60489d0e1a | 4,107 | # frozen_string_literal: true
# This file should only be used by sub-classes, not directly by any clients of the sub-classes
# please require all dependencies below:
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/module/delegation'
module Gitlab
module Redis
class Wrapper
DEFAULT_REDIS_URL = 'redis://localhost:6379'
REDIS_CONFIG_ENV_VAR_NAME = 'GITLAB_REDIS_CONFIG_FILE'
class << self
delegate :params, :url, to: :new
def with
pool.with { |redis| yield redis }
end
def pool
@pool ||= ConnectionPool.new(size: pool_size) { ::Redis.new(params) }
end
def pool_size
# heuristic constant 5 should be a config setting somewhere -- related to CPU count?
size = 5
if Gitlab::Runtime.multi_threaded?
size += Gitlab::Runtime.max_threads
end
size
end
def _raw_config
return @_raw_config if defined?(@_raw_config)
@_raw_config =
begin
if filename = config_file_name
ERB.new(File.read(filename)).result.freeze
else
false
end
rescue Errno::ENOENT
false
end
end
def default_url
DEFAULT_REDIS_URL
end
# Return the absolute path to a Rails configuration file
#
# We use this instead of `Rails.root` because for certain tasks
# utilizing these classes, `Rails` might not be available.
def config_file_path(filename)
File.expand_path("../../../config/#{filename}", __dir__)
end
def config_file_name
# if ENV set for wrapper class, use it even if it points to a file does not exist
file_name = ENV[REDIS_CONFIG_ENV_VAR_NAME]
return file_name unless file_name.nil?
# otherwise, if config files exists for wrapper class, use it
file_name = config_file_path('resque.yml')
return file_name if File.file?(file_name)
# nil will force use of DEFAULT_REDIS_URL when config file is absent
nil
end
end
def initialize(rails_env = nil)
@rails_env = rails_env || ::Rails.env
end
def params
redis_store_options
end
def url
raw_config_hash[:url]
end
def sentinels
raw_config_hash[:sentinels]
end
def sentinels?
sentinels && !sentinels.empty?
end
private
def redis_store_options
config = raw_config_hash
redis_url = config.delete(:url)
redis_uri = URI.parse(redis_url)
config[:driver] ||= ::Gitlab::Instrumentation::RedisDriver
if redis_uri.scheme == 'unix'
# Redis::Store does not handle Unix sockets well, so let's do it for them
config[:path] = redis_uri.path
query = redis_uri.query
unless query.nil?
queries = CGI.parse(redis_uri.query)
db_numbers = queries["db"] if queries.key?("db")
config[:db] = db_numbers[0].to_i if db_numbers.any?
end
config
else
redis_hash = ::Redis::Store::Factory.extract_host_options_from_uri(redis_url)
# order is important here, sentinels must be after the connection keys.
# {url: ..., port: ..., sentinels: [...]}
redis_hash.merge(config)
end
end
def raw_config_hash
config_data = fetch_config
if config_data
config_data.is_a?(String) ? { url: config_data } : config_data.deep_symbolize_keys
else
{ url: self.class.default_url }
end
end
def fetch_config
return false unless self.class._raw_config
yaml = YAML.load(self.class._raw_config)
# If the file has content but it's invalid YAML, `load` returns false
if yaml
yaml.fetch(@rails_env, false)
else
false
end
end
end
end
end
| 27.563758 | 94 | 0.590942 |
014dc572f646d0a41d29d2842e7724c5b5c44e5c | 766 | Gem::Specification.new do |s|
s.name = 'yaml_zlib_blowfish'
s.version = '2.0.210127'
s.homepage = 'https://github.com/carlosjhr64/yaml_zlib_blowfish'
s.author = 'carlosjhr64'
s.email = '[email protected]'
s.date = '2021-01-27'
s.licenses = ['MIT']
s.description = <<DESCRIPTION
Have you ever wanted to YAML dump, Zlib compress, and Blowfish encrypt your data structures?
YOU HAVE!? Well...
DESCRIPTION
s.summary = <<SUMMARY
Have you ever wanted to YAML dump, Zlib compress, and Blowfish encrypt your data structures?
YOU HAVE!? Well...
SUMMARY
s.require_paths = ['lib']
s.files = %w(
README.md
lib/yaml_zlib_blowfish.rb
)
s.requirements << 'ruby: ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-linux]'
end
| 23.212121 | 92 | 0.691906 |
b962eae74a93d28c738c32ed48c3749c59e14d1c | 1,942 | require 'spec_helper'
describe "dating agency" do
before(:each) do
class Love
include Asp::Element
asp_schema :name
end
class Person
include Asp::Element
def self.match?(string)
nil
end
def initialize(name, sex, status)
@name = name || "_"
@sex = sex || "_"
@status = status || "_"
end
def asp_representation
"person(\"#{@name}\", #{@sex}, #{@status})"
end
asp_schema :name, :sex, :relationship_status
end
end
after(:all) do
Asp::Memory.instance.forget!
end
context "online dating site" do
subject (:problem) {
Asp::Problem.new().tap do |p|
p.add(Person.new("Alice", :female, :single))
p.add(Person.new("Bob", :male, :single))
p.add(Person.new("Carla", :female, :married))
p.add("{ love(NAME) } 1 :- person(NAME,_,_)")
end
}
before(:each) do
problem.never { less_than(1) { Love.asp } }
problem.never { more_than(1) { Love.asp } }
end
let(:solo_constraint) do
problem.never { conjunct{ [Love.asp(:name => "NAME"), Person.asp(:name => "NAME", :relationship_status => "married")] } }
end
let(:female_constraint) do
problem.never { conjunct{[ Love.asp(:name => "NAME"), Person.asp(:name => "NAME", :sex => "male")] } }
end
its(:solutions) { are_expected.to correspond_with [['love("Alice")'], ['love("Bob")'], ['love("Carla")']] }
it "only females" do
female_constraint
expect(problem.solutions).to correspond_with [['love("Alice")'], ['love("Carla")']]
end
it "only singles" do
solo_constraint
expect(problem.solutions).to correspond_with [['love("Alice")'], ['love("Bob")']]
end
it "only female singles" do
solo_constraint; female_constraint
expect(problem.solutions).to correspond_with [['love("Alice")']]
end
end
end
| 26.243243 | 127 | 0.57312 |
1d00c3603de49596c8ce82c1f985f052c11c6c65 | 189 | class Post < ActiveRecord::Base
translatable :title, :content, :published, :published_at
validates_presence_of :title
scope :with_some_title, -> { where(:title => 'some_title') }
end
| 31.5 | 62 | 0.73545 |
d5bd44b9db53840fe7a357ff1cab100b24419bb9 | 651 | require 'generators/generators_test_helper'
require 'rails/generators/rails/task/task_generator'
class TaskGeneratorTest < Rails::Generators::TestCase
include GeneratorsTestHelper
arguments %w(feeds foo bar)
def test_task_is_created
run_generator
assert_file "lib/tasks/feeds.rake" do |content|
assert_match(/namespace :feeds/, content)
assert_match(/task foo:/, content)
assert_match(/task bar:/, content)
end
end
def test_task_on_revoke
task_path = 'lib/tasks/feeds.rake'
run_generator
assert_file task_path
run_generator ['feeds'], behavior: :revoke
assert_no_file task_path
end
end
| 26.04 | 53 | 0.741935 |
6228415971cbf0119fe544876a60d5fe467dcf69 | 1,522 | {
matrix_id: '2578',
name: 'AS365',
group: 'DIMACS10',
description: 'DIMACS10 numerical/AS365 : A 2-D Tri-Element mesh around a chopper',
author: 'C. S. Yin, J. T. Zhang',
editor: 'H. Meyerhenke',
date: '2011',
kind: 'undirected graph',
problem_2D_or_3D: '0',
num_rows: '3799275',
num_cols: '3799275',
nonzeros: '22736152',
num_explicit_zeros: '0',
num_strongly_connected_components: '1',
pattern_symmetry: '1.000',
numeric_symmetry: '1.000',
rb_type: 'binary',
structure: 'symmetric',
cholesky_candidate: 'no',
positive_definite: 'no',
notes: 'DIMACS10 set: numerical/AS365
source: http://www.cc.gatech.edu/dimacs10/archive/numerical.shtml
The instances NACA0015, M6, 333SP, AS365, and NLR are 2-dimensional FE
triangular meshes with coordinate information. 333SP and AS365 are
actually converted from existing 3-dimensional models to 2D places,
while the rest are created from geometry. The corresponding coordinate
files have been assembled in one archive. They have been created and
contributed by Chan Siew Yin with the help of Jian Tao Zhang,
Department of Mechanical Engineering, University of New Brunswick,
Fredericton, Canada.
',
aux_fields: 'coord: full 3799275-by-2
', image_files: 'AS365.png,AS365_gplot.png,AS365_graph.gif,',
}
| 41.135135 | 86 | 0.626807 |
3377fd79e075968a520262a248a92f1d884590de | 5,488 | RSpec.describe Pcloud::Client do
before(:each) do
Pcloud::Client.remove_class_variable(:@@data_region) if Pcloud::Client.class_variable_defined?(:@@data_region)
Pcloud::Client.remove_class_variable(:@@access_token) if Pcloud::Client.class_variable_defined?(:@@access_token)
Pcloud::Client.remove_class_variable(:@@closest_server) if Pcloud::Client.class_variable_defined?(:@@closest_server)
end
describe ".execute" do
let(:httparty_response) { double(HTTParty::Response) }
before do
Pcloud::Client.configure(access_token: "test-token", data_region: "US")
allow(httparty_response).to receive(:body).and_return({ fileid: 100100 }.to_json)
allow(HTTParty).to receive(:public_send).and_return(httparty_response)
end
context "when method is 'uploadfile'" do
it "makes a post request to the pCloud api" do
expect(HTTParty)
.to receive(:public_send)
.with(
:post,
"https://api.pcloud.com/uploadfile",
{
headers: { "Authorization" => "Bearer test-token" },
timeout: 8,
body: { filename: "cats.jpg" }
}
).and_return(httparty_response)
Pcloud::Client.execute("uploadfile", body: { filename: "cats.jpg" })
end
it "returns the JSON response" do
response = Pcloud::Client.execute("uploadfile", body: { filename: "cats.jpg" })
expect(response).to eq({ "fileid" => 100100 })
end
end
context "for all other methods" do
it "makes a get request to the pCloud api" do
expect(HTTParty)
.to receive(:public_send)
.with(
:get,
"https://api.pcloud.com/stat",
{
headers: { "Authorization" => "Bearer test-token" },
timeout: 8,
query: { fileid: 100100 }
}
).and_return(httparty_response)
Pcloud::Client.execute("stat", query: { fileid: 100100 })
end
it "returns the JSON response" do
response = Pcloud::Client.execute("stat", query: { fileid: 100100 })
expect(response).to eq({ "fileid" => 100100 })
end
end
context "when pCloud returns an error in the JSON" do
before do
allow(httparty_response).to receive(:body).and_return({ error: "Don't do it David" }.to_json)
end
it "raises an ErrorResponse" do
allow(HTTParty).to receive(:public_send).and_return(httparty_response)
expect {
Pcloud::Client.execute("stat", query: { fileid: 100100 })
}.to raise_error(Pcloud::Client::ErrorResponse, "Don't do it David")
end
end
end
describe ".region" do
it "reads from module configuration" do
Pcloud::Client.configure(access_token: "test-token", data_region: "EU")
expect(Pcloud::Client.send(:data_region)).to eq("EU")
end
it "reads from environment variable" do
allow(ENV).to receive(:[]).with("PCLOUD_API_DATA_REGION").and_return("EU")
expect(Pcloud::Client.send(:data_region)).to eq("EU")
end
it "raises ConfigurationError when not configured" do
expect {
Pcloud::Client.send(:data_region)
}.to raise_error(Pcloud::Client::ConfigurationError, "Missing pCloud data region")
end
it "raises ConfigurationError when set to an invalid value" do
allow(ENV).to receive(:[]).with("PCLOUD_API_DATA_REGION").and_return("SPACE")
expect {
Pcloud::Client.send(:data_region)
}.to raise_error(Pcloud::Client::ConfigurationError, 'Invalid pCloud data region, must be one of ["EU", "US"]')
end
end
describe ".access_token" do
it "reads from module configuration" do
Pcloud::Client.configure(access_token: "test-token", data_region: "EU")
expect(Pcloud::Client.send(:access_token)).to eq("test-token")
end
it "reads from environment variable" do
allow(ENV).to receive(:[]).with("PCLOUD_API_ACCESS_TOKEN").and_return("test-token")
expect(Pcloud::Client.send(:access_token)).to eq("test-token")
end
it "raises ConfigurationError when not configured" do
expect {
Pcloud::Client.send(:access_token)
}.to raise_error(Pcloud::Client::ConfigurationError, "Missing pCloud API access token")
end
end
describe ".closest_server" do
before do
allow(ENV).to receive(:[]).and_call_original
end
it "returns the correct server for the US" do
allow(ENV).to receive(:[]).with("PCLOUD_API_DATA_REGION").and_return("US")
expect(Pcloud::Client.send(:closest_server)).to eq("api.pcloud.com")
end
it "returns the correct server for the EU" do
allow(ENV).to receive(:[]).with("PCLOUD_API_DATA_REGION").and_return("EU")
expect(Pcloud::Client.send(:closest_server)).to eq("eapi.pcloud.com")
end
it "allows manual override with PCLOUD_API_BASE_URI environment variable" do
allow(ENV).to receive(:[]).with("PCLOUD_API_BASE_URI").and_return("spacecats.pcloud.com")
expect(Pcloud::Client.send(:closest_server)).to eq("spacecats.pcloud.com")
end
it "raises ConfigurationError when retion is set to an invalid value" do
allow(ENV).to receive(:[]).with("PCLOUD_API_DATA_REGION").and_return("SPACE")
expect {
Pcloud::Client.send(:closest_server)
}.to raise_error(Pcloud::Client::ConfigurationError, 'Invalid pCloud data region, must be one of ["EU", "US"]')
end
end
end
| 37.589041 | 120 | 0.646684 |
7abb3bda2fc5527865af9e5bc172f21f7001b14c | 404 | cask "font-averia-gruesa-libre" do
version :latest
sha256 :no_check
# github.com/google/fonts/ was verified as official when first introduced to the cask
url "https://github.com/google/fonts/raw/master/ofl/averiagruesalibre/AveriaGruesaLibre-Regular.ttf"
name "Averia Gruesa Libre"
homepage "https://fonts.google.com/specimen/Averia+Gruesa+Libre"
font "AveriaGruesaLibre-Regular.ttf"
end
| 33.666667 | 102 | 0.777228 |
ac007bed86c0e5fc82d391c45b8323f35a98b17e | 534 | module Stupidedi
module Versions
module FunctionalGroups
module ThirtyForty
module SegmentDefs
s = Schema
e = ElementDefs
r = ElementReqs
ST = s::SegmentDef.build(:ST, "Transaction Set Header",
"To indicate the start of a transaction set and assign a control number",
e::E143 .simple_use(r::Mandatory, s::RepeatCount.bounded(1)),
e::E329 .simple_use(r::Mandatory, s::RepeatCount.bounded(1)))
end
end
end
end
end
| 25.428571 | 85 | 0.597378 |
3881ca38fcd9fa8c9ab2093797b1f3b71e77a4a7 | 3,341 | require 'csv'
class SeedController < ApplicationController
"""
Access at /visitors/seed
This method is to seed the words from the corpus.
"""
def dictionary
"""
Dictionary.delete_all
array_global = []
count = 0
"""
#filename = "/home/prashant/cs76proj/master_master_corpus.txt"
#CSV.foreach filename,{:col_sep => "\t", encoding: "ISO8859-1"} do |row|
"""
count = count+1
#if count>20
#break
#end
array = row[2].split(/ -/)
array.each do |each_string|
each_string.split(' ').each do |a|
a.gsub!('\.\?\(\)\:\"\'\!\@\#\$\%\^\&\*','')
a.delete('?')
array_global.push a.downcase
end
end
end
array_global.each do |string|
@dict = Dictionary.find_by_word(string)
if @dict
@dict.count = @dict.count+1
@dict.save
else
@dictionary = Dictionary.create!(:word=>string,:count=>1)
@dictionary.save
end
end
"""
end
"""
"""
def bigrams
#filename = "/home/prashant/cs76proj/master_corpus.txt"
"""
Bigram.delete_all
count = 0
"""
#CSV.foreach filename,{:col_sep => "\t", encoding: "ISO8859-1"} do |row|
"""
count = count+1
#if count>20
#break
#end
array = row[2]
tokenizer = Nanogram::Tokenizer.new
array = array.downcase.gsub(/[\.\?\,\:\-\(\)\'\!0-9\/]/,'')
global_array = tokenizer.ngrams(2,array)
global_array.each do |string|
string = string.split(' ')
@bigram = Bigram.find_by_word1_and_word2(string[0],string[1])
if @bigram
@bigram.count = @bigram.count+1
@bigram.save
else
@bigrams = Bigram.create!(:word1=> string[0],:word2 => string[1])
@bigrams.save
end
end
end
"""
end
"""
"""
def trigrams
#filename = "/home/prashant/cs76proj/master_corpus.txt"
"""
Trigram.delete_all
count = 0
"""
#CSV.foreach filename,{:col_sep => "\t", encoding: "ISO8859-1"} do |row|
"""
count = count+1
#if count>20
#break
#end
array = row[2]
tokenizer = Nanogram::Tokenizer.new
array = array.downcase.gsub(/[\.\?\,\:\-\(\)\'\!0-9\/]/,'')
global_array = tokenizer.ngrams(3,array)
global_array.each do |string|
string = string.split(' ')
@trigram = Trigram.find_by_word1_and_word2_and_word3(string[0],string[1],string[2])
if @trigram
@trigram.count = @trigram.count+1
@trigram.save
else
@trigrams = Trigram.create!(:word1=> string[0],:word2 => string[1],:word3 => string[2])
@trigrams.save
end
end
end
"""
end
end
| 30.372727 | 107 | 0.444777 |
bf77fdb45a303b6fb0547350828e04baf2b0fc02 | 616 | class Polaris::TextField::ComponentPreview < ViewComponent::Preview
def default
end
def number
end
def email
end
def multiline
end
def with_hidden_label
end
def with_label_action
end
def with_right_aligned_text
end
def with_placeholder_text
end
def with_help_text
end
def with_prefix_or_suffix
end
def with_connected_fields
end
def with_validation_error
end
def with_separate_validation_error
end
def disabled
end
def with_character_count
end
def with_clear_button
end
def with_monospaced_font
end
def with_form_helper
end
end
| 11 | 67 | 0.748377 |
87d002326ffca881e97f079f87cb490081d983fb | 142 | class ApplicationRecord < ActiveRecord::Base
# NOTE : Added for loading slug module
include Slugifiable
self.abstract_class = true
end
| 20.285714 | 44 | 0.774648 |
6afd30b3700bd0bef4a1df67ebc1235822d270a0 | 6,108 | # frozen_string_literal: true
#
# == SwimmerUserStrategy
#
# Strategy Pattern implementation for Swimmer-User relations and action-enable
# policy.
#
# @author Steve A.
# @version 4.00.285
#
class SwimmerUserStrategy
def initialize(swimmer)
@swimmer = swimmer
end
#-- --------------------------------------------------------------------------
#++
# Returns true if this swimmer instance can support the "social/confirm"
# action links or buttons. False otherwise.
#
def is_confirmable_by(another_user)
!!(
is_associated_to_somebody_else_than(another_user) &&
another_user.find_any_confirmation_given_to(@swimmer.associated_user).nil?
)
end
# Returns true if this swimmer instance can support the "social/unconfirm"
# action links or buttons. False otherwise.
#
def is_unconfirmable_by(another_user)
!!(
is_associated_to_somebody_else_than(another_user) &&
!another_user.find_any_confirmation_given_to(@swimmer.associated_user).nil?
)
end
#-- --------------------------------------------------------------------------
#++
# Returns true if this swimmer instance can support the "social/invite friend"
# action links or buttons. False otherwise.
#
# @see #is_pending_for()
# @see #is_approvable_by()
#
def is_invitable_by(another_user)
!!(
is_associated_to_somebody_else_than(another_user) &&
@swimmer.associated_user.find_any_friendship_with(another_user).nil?
)
end
# Returns true if this swimmer instance cannot "invite socially" another friend
# because the invite has already been sent and it is pending for acceptance.
# False otherwise.
#
# "Pending" friendships are the only "approvable" ones in the sense that they can be
# both active and passive subjects. But from an "active" (meaning "user-clickable")
# point of view, an "approvable" friendship is the only one having as friend the
# same user browsing the page. A "Pending" friendship matches the friendable instead.
#
# Simply put:
# - A pending friendship, waiting for approval from the friend:
# => it is "pending" for the friendable,
# => it is "approvable" by the friend.
#
# @see #is_approvable_by()
#
def is_pending_for(another_user)
return false unless is_associated_to_somebody_else_than(another_user)
existing_friendship = @swimmer.associated_user.find_any_friendship_with(another_user)
!!(
existing_friendship &&
existing_friendship.pending? &&
(existing_friendship.friendable_id == another_user.id) # Another user is the one *sending* the invite
)
end
# Returns true if this swimmer instance can "approve socially" another friend request
# because the invite has already been sent and it is pending for acceptance.
# False otherwise.
#
# "Pending" friendships are the only "approvable" ones in the sense that they can be
# both active and passive subjects. But from an "active" (meaning "user-clickable")
# point of view, an "approvable" friendship is the only one having as friend the
# same user browsing the page. A "Pending" friendship matches the friendable instead.
#
# Simply put:
# - A pending friendship, waiting for approval from the friend:
# => it is "pending" for the friendable,
# => it is "approvable" by the friend.
#
# @see #is_pending_for()
#
def is_approvable_by(another_user)
return false unless is_associated_to_somebody_else_than(another_user)
existing_friendship = @swimmer.associated_user.find_any_friendship_with(another_user)
!!(
existing_friendship &&
existing_friendship.pending? &&
(existing_friendship.friend_id == another_user.id) # Another user is the one *receiving* the invite
)
end
#-- --------------------------------------------------------------------------
#++
# Returns true if this swimmer instance can support the "social/block friendship"
# action links or buttons. False otherwise.
#
def is_blockable_by(another_user)
return false unless is_associated_to_somebody_else_than(another_user)
existing_friendship = @swimmer.associated_user.find_any_friendship_with(another_user)
!!(
existing_friendship &&
existing_friendship.can_block?(another_user)
)
end
# Returns true if this swimmer instance can support the "social/unblock friendship"
# action links or buttons. False otherwise.
#
def is_unblockable_by(another_user)
return false unless is_associated_to_somebody_else_than(another_user)
existing_friendship = @swimmer.associated_user.find_any_friendship_with(another_user)
!!(
existing_friendship &&
existing_friendship.can_unblock?(another_user)
)
end
# Returns true if this swimmer instance can support the "social/edit (or remove) friendship"
# action links or buttons. False otherwise.
#
def is_editable_by(another_user)
!!(
is_associated_to_somebody_else_than(another_user) &&
[email protected]_user.find_any_friendship_with(another_user).nil?
)
end
#-- --------------------------------------------------------------------------
#++
# Check if this Swimmer object is correctly associated to a user and if it's a
# different user from the one specified, plus they both have different swimmers
# associated with their accounts.
#
# Returns true if the associated user is different from +another_user+.
# False otherwise.
#
def is_associated_to_somebody_else_than(another_user)
!!(
another_user && # User exists...
another_user.swimmer && # It has a swimmer associated...
@swimmer && # Ditto for this strategy's object...
@swimmer.associated_user && # ...And their are different gogglers:
(@swimmer.associated_user_id != another_user.id) &&
(@swimmer.id != another_user.swimmer_id) # (additional and redundant integrity check)
)
end
#-- --------------------------------------------------------------------------
#++
end
| 35.929412 | 107 | 0.666503 |
394aef6ccafaa3d609aa085a124ba99532be4be7 | 2,159 |
if respond_to?(:require_relative, true)
require_relative 'common'
else
require File.dirname(__FILE__) + '/common'
end
describe RestGraph do
after do
WebMock.reset!
Muack.verify
end
should 'return true in authorized? if there is an access_token' do
RestGraph.new(:access_token => '1').authorized?.should == true
RestGraph.new(:access_token => nil).authorized?.should == false
end
should 'treat oauth_token as access_token as well' do
rg = RestGraph.new
hate_facebook = 'why the hell two different name?'
rg.data['oauth_token'] = hate_facebook
rg.authorized?.should == true
rg.access_token == hate_facebook
end
should 'build correct headers' do
rg = RestGraph.new(:accept => 'text/html',
:lang => 'zh-tw')
rg.send(:build_headers).should == {'Accept' => 'text/html',
'Accept-Language' => 'zh-tw'}
end
should 'build empty query string' do
RestGraph.new.send(:build_query_string).should == ''
end
should 'create access_token in query string' do
RestGraph.new(:access_token => 'token').send(:build_query_string).
should == '?access_token=token'
end
should 'build correct query string' do
TestHelper.normalize_query(
RestGraph.new(:access_token => 'token').send(:build_query_string,
:message => 'hi!!')).
should == '?access_token=token&message=hi%21%21'
TestHelper.normalize_query(
RestGraph.new.send(:build_query_string, :message => 'hi!!',
:subject => '(&oh&)')).
should == '?message=hi%21%21&subject=%28%26oh%26%29'
end
should 'auto decode json' do
RestGraph.new(:auto_decode => true).
send(:post_request, {}, '', '[]').should == []
end
should 'not auto decode json' do
RestGraph.new(:auto_decode => false).
send(:post_request, {}, '', '[]').should == '[]'
end
should 'give attributes' do
RestGraph.new(:auto_decode => false).attributes.keys.map(&:to_s).sort.
should == RestGraphStruct.members.map(&:to_s).sort
end
end
| 30.842857 | 74 | 0.613247 |
f744b087bf631f5753488d32d7090d1ac0f4b0a9 | 4,958 | # 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
| 49.58 | 96 | 0.712586 |
ac369121bce64fa476bf0e66b870b721b48252b7 | 187 | class Helper
def self.current_user(session_hash)
User.find(session_hash[:user_id])
end
def self.logged_in?(session_hash)
!!session_hash[:user_id]
end
end | 20.777778 | 40 | 0.668449 |
1c458a098625f4d381f5cd821d9ac9fcb9458799 | 4,355 | RSpec.describe PowerApi::GeneratorHelper::RoutesHelper, type: :generator do
describe "#routes_path" do
let(:expected_path) { "config/routes.rb" }
def perform
generators_helper.routes_path
end
it { expect(perform).to eq(expected_path) }
end
describe "#api_version_routes_line_regex" do
let(:expected_regex) { /Api::V1[^\n]*/ }
def perform
generators_helper.api_version_routes_line_regex
end
it { expect(perform).to eq(expected_regex) }
end
describe "#parent_resource_routes_line_regex" do
def perform
generators_helper.parent_resource_routes_line_regex
end
it { expect { perform }.to raise_error("missing parent_resource") }
context "with parent_resource" do
let(:expected_regex) { /resources :users[^\n]*/ }
let(:parent_resource_name) { "user" }
it { expect(perform).to eq(expected_regex) }
end
end
describe "#resource_route_tpl" do
let(:actions) { [] }
let(:expected_tpl) { "resources :blogs" }
let(:parent_resource_name) { "user" }
let(:is_parent) { false }
def perform
generators_helper.resource_route_tpl(actions: actions, is_parent: is_parent)
end
it { expect(perform).to eq(expected_tpl) }
context "with specific actions" do
let(:actions) { ["index", "create"] }
let(:expected_tpl) { "resources :blogs, only: [:index, :create]" }
it { expect(perform).to eq(expected_tpl) }
end
context "with is_parent option actions" do
let(:is_parent) { true }
let(:expected_tpl) { "resources :users" }
it { expect(perform).to eq(expected_tpl) }
end
end
describe "routes_line_to_inject_new_version" do
let(:expected_line) do
"routes.draw do\n"
end
def perform
generators_helper.routes_line_to_inject_new_version
end
it { expect(perform).to eq(expected_line) }
context "when is not the first version" do
let(:version_number) { "2" }
let(:expected_line) do
"'/api' do\n"
end
it { expect(perform).to eq(expected_line) }
end
end
describe "#version_route_tpl" do
let(:expected_tpl) do
<<~ROUTE
scope path: '/api' do
api_version(module: 'Api::V1', path: { value: 'v1' }, defaults: { format: 'json' }) do
end
end
ROUTE
end
def perform
generators_helper.version_route_tpl
end
it { expect(perform).to eq(expected_tpl) }
context "when is not the first version" do
let(:version_number) { "2" }
let(:expected_tpl) do
<<~ROUTE
api_version(module: 'Api::V2', path: { value: 'v2' }, defaults: { format: 'json' }) do
end
ROUTE
end
it { expect(perform).to eq(expected_tpl.delete_suffix("\n")) }
end
end
describe "#parent_route_exist?" do
let(:parent_resource_name) { "user" }
let(:line) { nil }
def perform
generators_helper.parent_route_exist?
end
before { mock_file_content("config/routes.rb", [line]) }
context "with file line not matching regex" do
let(:line) { "X" }
it { expect(perform).to eq(false) }
end
context "with no parent_resource" do
let(:parent_resource_name) { nil }
it { expect { perform }.to raise_error("missing parent_resource") }
end
context "with file line matching regex" do
let(:line) { "resources :users" }
it { expect(perform).to eq(true) }
end
end
describe "#parent_route_already_have_children?" do
let(:parent_resource_name) { "user" }
let(:line) { nil }
def perform
generators_helper.parent_route_already_have_children?
end
before { mock_file_content("config/routes.rb", [line]) }
context "with file line not matching regex" do
let(:line) { "X" }
it { expect(perform).to eq(false) }
end
context "with no parent_resource" do
let(:parent_resource_name) { nil }
it { expect { perform }.to raise_error("missing parent_resource") }
end
context "with parent line found but with no children" do
let(:line) { "resources :users" }
it { expect(perform).to eq(false) }
end
context "with parent line found with children" do
let(:line) { "resources :users do" }
it { expect(perform).to eq(true) }
end
end
end
| 24.194444 | 96 | 0.632147 |
ff7b58414ff3dd6085e4934a551f3c81ae282e0c | 1,588 | platform_is_not :windows do
require File.expand_path('../../../spec_helper', __FILE__)
require 'syslog'
describe "Syslog.log" do
platform_is_not [:windows, :darwin] do
before :each do
Syslog.opened?.should be_false
end
after :each do
Syslog.opened?.should be_false
end
it "receives a priority as first argument" do
lambda {
Syslog.open("rubyspec", Syslog::LOG_PERROR) do |s|
s.log(Syslog::LOG_ALERT, "Hello")
s.log(Syslog::LOG_CRIT, "World")
end
}.should output_to_fd("rubyspec: Hello\nrubyspec: World\n", $stderr)
end
it "accepts undefined priorites" do
lambda {
Syslog.open("rubyspec", Syslog::LOG_PERROR) do |s|
s.log(1337, "Hello")
end
# use a regex since it'll output unknown facility/priority messages
}.should output_to_fd(/rubyspec: Hello/, $stderr)
end
it "fails with TypeError on nil log messages" do
Syslog.open do |s|
lambda { s.log(1, nil) }.should raise_error(TypeError)
end
end
it "fails if the log is closed" do
lambda {
Syslog.log(Syslog::LOG_ALERT, "test")
}.should raise_error(RuntimeError)
end
it "accepts printf parameters" do
lambda {
Syslog.open("rubyspec", Syslog::LOG_PERROR) do |s|
s.log(Syslog::LOG_ALERT, "%s x %d", "chunky bacon", 2)
end
}.should output_to_fd("rubyspec: chunky bacon x 2\n", $stderr)
end
end
end
end
| 28.357143 | 77 | 0.584383 |
f7951b8d3a7c13e1aae535d80f493c5abfba5290 | 750 | require 'artemis_api/client'
require 'artemis_api/model'
require 'artemis_api/facility'
require 'artemis_api/user'
require 'artemis_api/version'
require 'artemis_api/zone'
require 'artemis_api/organization'
require 'artemis_api/batch'
require 'artemis_api/completion'
require 'artemis_api/discard'
require 'artemis_api/harvest'
require 'artemis_api/seeding_unit'
require 'artemis_api/harvest_unit'
require 'artemis_api/resource_unit'
require 'artemis_api/crop_variety'
require 'artemis_api/item'
require 'artemis_api/subscription'
require 'artemis_api/stage'
require 'artemis_api/sub_stage'
require 'artemis_api/crop_batch_state'
require 'artemis_api/custom_fields'
require 'artemis_api/custom_data'
module ArtemisApi
# Your code goes here...
end
| 27.777778 | 38 | 0.833333 |
1c8df0a6a85ff12b76e27842d7afdbced208236f | 409 | require 'formula'
class Jags < Formula
homepage 'http://mcmc-jags.sourceforge.net'
url 'http://downloads.sourceforge.net/project/mcmc-jags/JAGS/3.x/Source/JAGS-3.3.0.tar.gz'
sha1 '79a50baaf1e2b2e7673d477e830963b49aad2a6c'
depends_on :fortran
def install
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make install"
end
end
| 25.5625 | 92 | 0.682152 |
1cef6fb776cc1c104c8a0178f7b4cb5994c38545 | 299 | module Slh
extend ActiveSupport::Autoload
autoload :ClassMethods
extend Slh::ClassMethods
autoload :Cli
module Models
extend ActiveSupport::Autoload
autoload :Base
autoload :Strategy
autoload :Host
autoload :Site
autoload :SitePath
autoload :Version
end
end
| 17.588235 | 34 | 0.722408 |
6219c2994b7a3896e35cc86a65ea43a52bc398f9 | 85 | json.extract! @project, :id, :name, :description, :user_id, :created_at, :updated_at
| 42.5 | 84 | 0.729412 |
e8163d9d99dc3d0850ea32e03304fec639e6afcb | 729 | module TwentyfourSevenOffice
module Services
class Invoice < Service
wsdl "https://api.24sevenoffice.com/Economy/InvoiceOrder/V001/InvoiceService.asmx?WSDL"
api_operation :save_invoices,
input_data_types: { invoices: Array[InvoiceOrder] }
def save(invoice)
if invoice.is_a?(Hash)
invoice = TwentyfourSevenOffice::DataTypes::InvoiceOrder.new(invoice)
end
saved = save_invoices(invoices: [invoice])
if saved
if saved.api_exception
raise TwentyfourSevenOffice::Errors::APIError.new(saved.api_exception.message)
end
saved.order_id
else
nil
end
end
end
end
end
| 23.516129 | 93 | 0.62963 |
ac9f5251ee74e5663c8a991f9fba17d168b26d5f | 693 | module Extent
def extent_label
sanitized_format || "Physical extent"
end
def extent
[physical_string, characteristics_string].compact.join(' ')
end
private
def physical_string
return nil unless self[:physical].present?
Array[self[:physical]].flatten.join(', ')
end
def characteristics_string
return nil unless self.marc_characteristics.present?
self.marc_characteristics.map do |characteristic|
"#{characteristic.label}: #{characteristic.values.join(' ')}"
end.join(' ')
end
def sanitized_format
if self[format_key].present?
self[format_key].reject do |format|
format == 'Database'
end.first
end
end
end
| 21.65625 | 67 | 0.689755 |
1a1911555c437058aa9a6b39447c0709435b3f7e | 1,214 | class Libmp3splt < Formula
desc "Utility library to split mp3, ogg, and FLAC files"
homepage "https://mp3splt.sourceforge.io"
url "https://downloads.sourceforge.net/project/mp3splt/libmp3splt/0.9.2/libmp3splt-0.9.2.tar.gz"
sha256 "30eed64fce58cb379b7cc6a0d8e545579cb99d0f0f31eb00b9acc8aaa1b035dc"
revision 1
bottle do
sha256 "8070118d4ad4175f51c60081fcc01193b494c8f5e96ed7cf82364f73d68754e3" => :catalina
sha256 "d929bb92be95a49b808d087be5e88100bc23c423100da1afd86422cf0ed3d6cb" => :mojave
sha256 "71eb2ec5137acc03b95dbfdfadbb88c6bade2cb1548cce2655876971e346707a" => :high_sierra
sha256 "805407189fbd468b036493996832e387395380a2fbda743cafac78876632abf9" => :sierra
sha256 "df0fe08763144831bf9544e2ccda4746623cd3c6730021a363138b89b203fe72" => :x86_64_linux
end
depends_on "pkg-config" => :build
depends_on "flac"
depends_on "gettext"
depends_on "libid3tag"
depends_on "libogg"
depends_on "libtool"
depends_on "libvorbis"
depends_on "mad"
depends_on "pcre"
def install
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
end
| 36.787879 | 98 | 0.747117 |
032d09ff46dc8cc8affe2c24a79df4b1ee225e36 | 1,116 | class LoosePassengerValidator < ActiveModel::Validator
def validate record
if record.trip_id != nil
unless Trip.find(record.trip_id)
record.errors[:name] << 'Picked up Passenger must have valid Trip ID'
end
end
end
end
class Passenger < ApplicationRecord
include ActiveModel::Validations
validates :address, presence: true
validates_with LoosePassengerValidator
belongs_to :user, foreign_key: :passenger_id
validates :user, presence: true
def self.load_example! count: 1
trip = Trip.load_example!
hitchers = User.load_example! count: count, skip: 1
passengers = Array.new
count.times do |i|
passengers.push(Passenger.create! passenger_id: hitchers[0].id,
address: 'Some random address')
end
return { trip: trip, passengers: passengers }
end
def assign_trip trip, pickup_time:
self.trip_id = trip.id
self.driver_id = trip.user_id
self.pickup_time = pickup_time
self.save!
end
def is_assigned_to_trip?
return (self.trip_id != nil and self.driver_id != nil)
end
end
| 24.8 | 77 | 0.68638 |
1c9e9142fadcd154d732fd2c37d6bf225b01a561 | 72 | class Object
delegate :decorate, to: Rails::Decorators::Decorator
end
| 18 | 54 | 0.777778 |
1c2dafe6f0d627f61ea7c861cbbf24b704c07d7a | 38 | module Surfio
VERSION = "0.1.0"
end
| 9.5 | 19 | 0.657895 |
e9fc05b3c28228b18888d2259905a08735446a93 | 495 | # alexggordon.rb
require 'sinatra'
require 'sinatra/assetpack'
class AlexGGordon < Sinatra::Base
set :root, File.dirname(__FILE__) # You must set app root
register Sinatra::AssetPack
end
assets do
serve '/images', :from => 'app/images'
serve '/css', :from => 'app/css'
css :application, [
]
css :skeleton, [
'/css/skeleton.css'
]
css :normalize, [
'/css/normalize.css'
]
css :custom, [
'/css/custom.css'
]
end
get '/' do
render "html.erb", :index
end
| 15.46875 | 59 | 0.632323 |
d5e060bdbe818ed9328745d5a8176079ff89244f | 8,503 | class Spinach::Features::ProjectMergeRequests < Spinach::FeatureSteps
include SharedAuthentication
include SharedIssuable
include SharedProject
include SharedNote
include SharedPaths
include SharedMarkdown
include SharedDiffNote
step 'I click link "New Merge Request"' do
click_link "New Merge Request"
end
step 'I click link "Bug NS-04"' do
click_link "Bug NS-04"
end
step 'I click link "All"' do
click_link "All"
end
step 'I click link "Closed"' do
click_link "Closed"
end
step 'I should see merge request "Wiki Feature"' do
within '.merge-request' do
page.should have_content "Wiki Feature"
end
end
step 'I should see closed merge request "Bug NS-04"' do
merge_request = MergeRequest.find_by!(title: "Bug NS-04")
merge_request.closed?.should be_true
page.should have_content "Closed by"
end
step 'I should see merge request "Bug NS-04"' do
page.should have_content "Bug NS-04"
end
step 'I should see "Bug NS-04" in merge requests' do
page.should have_content "Bug NS-04"
end
step 'I should see "Feature NS-03" in merge requests' do
page.should have_content "Feature NS-03"
end
step 'I should not see "Feature NS-03" in merge requests' do
page.should_not have_content "Feature NS-03"
end
step 'I should not see "Bug NS-04" in merge requests' do
page.should_not have_content "Bug NS-04"
end
step 'I click link "Close"' do
within '.page-title' do
click_link "Close"
end
end
step 'I submit new merge request "Wiki Feature"' do
select "fix", from: "merge_request_source_branch"
select "feature", from: "merge_request_target_branch"
click_button "Compare branches"
fill_in "merge_request_title", with: "Wiki Feature"
click_button "Submit merge request"
end
step 'project "Shop" have "Bug NS-04" open merge request' do
create(:merge_request,
title: "Bug NS-04",
source_project: project,
target_project: project,
source_branch: 'fix',
target_branch: 'master',
author: project.users.first,
description: "# Description header"
)
end
step 'project "Shop" have "Bug NS-05" open merge request with diffs inside' do
create(:merge_request_with_diffs,
title: "Bug NS-05",
source_project: project,
target_project: project,
author: project.users.first)
end
step 'project "Shop" have "Feature NS-03" closed merge request' do
create(:closed_merge_request,
title: "Feature NS-03",
source_project: project,
target_project: project,
author: project.users.first)
end
step 'project "Shop" has "MR-task-open" open MR with task markdown' do
create_taskable(:merge_request, 'MR-task-open')
end
step 'I switch to the diff tab' do
visit diffs_project_merge_request_path(project, merge_request)
end
step 'I switch to the merge request\'s comments tab' do
visit project_merge_request_path(project, merge_request)
end
step 'I click on the commit in the merge request' do
within '.mr-commits' do
click_link Commit.truncate_sha(sample_commit.id)
end
end
step 'I leave a comment on the diff page' do
init_diff_note
leave_comment "One comment to rule them all"
end
step 'I leave a comment on the diff page in commit' do
click_diff_line(sample_commit.line_code)
leave_comment "One comment to rule them all"
end
step 'I leave a comment like "Line is wrong" on diff' do
init_diff_note
leave_comment "Line is wrong"
end
step 'I leave a comment like "Line is wrong" on diff in commit' do
click_diff_line(sample_commit.line_code)
leave_comment "Line is wrong"
end
step 'I should see a discussion has started on diff' do
page.should have_content "#{current_user.name} started a discussion"
page.should have_content sample_commit.line_code_path
page.should have_content "Line is wrong"
end
step 'I should see a discussion has started on commit diff' do
page.should have_content "#{current_user.name} started a discussion on commit"
page.should have_content sample_commit.line_code_path
page.should have_content "Line is wrong"
end
step 'I should see a discussion has started on commit' do
page.should have_content "#{current_user.name} started a discussion on commit"
page.should have_content "One comment to rule them all"
end
step 'merge request is mergeable' do
page.should have_content 'You can accept this request automatically'
end
step 'I modify merge commit message' do
find('.modify-merge-commit-link').click
fill_in 'commit_message', with: 'wow such merge'
end
step 'merge request "Bug NS-05" is mergeable' do
merge_request.mark_as_mergeable
end
step 'I accept this merge request' do
Gitlab::Satellite::MergeAction.any_instance.stub(
merge!: true,
)
click_button "Accept Merge Request"
end
step 'I should see merged request' do
within '.issue-box' do
page.should have_content "Merged"
end
end
step 'I click link "Reopen"' do
within '.page-title' do
click_link "Reopen"
end
end
step 'I should see reopened merge request "Bug NS-04"' do
within '.state-label' do
page.should have_content "Open"
end
end
step 'I click link "Hide inline discussion" of the second file' do
within '.files [id^=diff]:nth-child(2)' do
click_link "Diff comments"
end
end
step 'I click link "Show inline discussion" of the second file' do
within '.files [id^=diff]:nth-child(2)' do
click_link "Diff comments"
end
end
step 'I should not see a comment like "Line is wrong" in the second file' do
within '.files [id^=diff]:nth-child(2)' do
page.should_not have_visible_content "Line is wrong"
end
end
step 'I should see a comment like "Line is wrong" in the second file' do
within '.files [id^=diff]:nth-child(2) .note-text' do
page.should have_visible_content "Line is wrong"
end
end
step 'I should not see a comment like "Line is wrong here" in the second file' do
within '.files [id^=diff]:nth-child(2)' do
page.should_not have_visible_content "Line is wrong here"
end
end
step 'I should see a comment like "Line is wrong here" in the second file' do
within '.files [id^=diff]:nth-child(2) .note-text' do
page.should have_visible_content "Line is wrong here"
end
end
step 'I leave a comment like "Line is correct" on line 12 of the first file' do
init_diff_note_first_file
within(".js-discussion-note-form") do
fill_in "note_note", with: "Line is correct"
click_button "Add Comment"
end
within ".files [id^=diff]:nth-child(1) .note-text" do
page.should have_content "Line is correct"
end
end
step 'I leave a comment like "Line is wrong" on line 39 of the second file' do
init_diff_note_second_file
within(".js-discussion-note-form") do
fill_in "note_note", with: "Line is wrong on here"
click_button "Add Comment"
end
end
step 'I should still see a comment like "Line is correct" in the first file' do
within '.files [id^=diff]:nth-child(1) .note-text' do
page.should have_visible_content "Line is correct"
end
end
step 'I unfold diff' do
first('.js-unfold').click
end
step 'I should see additional file lines' do
expect(first('.text-file')).to have_content('.bundle')
end
step 'I click Side-by-side Diff tab' do
click_link 'Side-by-side Diff'
end
step 'I should see comments on the side-by-side diff page' do
within '.files [id^=diff]:nth-child(1) .note-text' do
page.should have_visible_content "Line is correct"
end
end
def merge_request
@merge_request ||= MergeRequest.find_by!(title: "Bug NS-05")
end
def init_diff_note
click_diff_line(sample_commit.line_code)
end
def leave_comment(message)
within(".js-discussion-note-form") do
fill_in "note_note", with: message
click_button "Add Comment"
end
page.should have_content message
end
def init_diff_note_first_file
click_diff_line(sample_compare.changes[0][:line_code])
end
def init_diff_note_second_file
click_diff_line(sample_compare.changes[1][:line_code])
end
def have_visible_content (text)
have_css("*", text: text, visible: true)
end
end
| 27.787582 | 83 | 0.689874 |
d5f31bf519ea043373e6ed391d394ce1f565fbb8 | 3,633 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Compute::Mgmt::V2019_03_01
module Models
#
# Identity for the virtual machine.
#
class VirtualMachineIdentity
include MsRestAzure
# @return [String] The principal id of virtual machine identity. This
# property will only be provided for a system assigned identity.
attr_accessor :principal_id
# @return [String] The tenant id associated with the virtual machine.
# This property will only be provided for a system assigned identity.
attr_accessor :tenant_id
# @return [ResourceIdentityType] The type of identity used for the
# virtual machine. The type 'SystemAssigned, UserAssigned' includes both
# an implicitly created identity and a set of user assigned identities.
# The type 'None' will remove any identities from the virtual machine.
# Possible values include: 'SystemAssigned', 'UserAssigned',
# 'SystemAssigned, UserAssigned', 'None'
attr_accessor :type
# @return [Hash{String =>
# VirtualMachineIdentityUserAssignedIdentitiesValue}] The list of user
# identities associated with the Virtual Machine. The user identity
# dictionary key references will be ARM resource ids in the form:
# '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
attr_accessor :user_assigned_identities
#
# Mapper for VirtualMachineIdentity class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'VirtualMachineIdentity',
type: {
name: 'Composite',
class_name: 'VirtualMachineIdentity',
model_properties: {
principal_id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'principalId',
type: {
name: 'String'
}
},
tenant_id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'tenantId',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
serialized_name: 'type',
type: {
name: 'Enum',
module: 'ResourceIdentityType'
}
},
user_assigned_identities: {
client_side_validation: true,
required: false,
serialized_name: 'userAssignedIdentities',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'VirtualMachineIdentityUserAssignedIdentitiesValueElementType',
type: {
name: 'Composite',
class_name: 'VirtualMachineIdentityUserAssignedIdentitiesValue'
}
}
}
}
}
}
}
end
end
end
end
| 35.271845 | 151 | 0.562896 |
383fa5de5cdeb3811ed83ab94e71db59f0de310a | 286 | class Auth::ConfirmationsController < Devise::ConfirmationsController
# most often it's needed to customize url of location to redirect user to after confirmation
# protected
# def after_confirmation_path_for(resource_name, user)
# edit_user_registration_path
# end
end
| 23.833333 | 94 | 0.786713 |
e2fa76522bccdb6a7d8749d2ed16f081efa863dd | 1,481 | require 'spec_helper'
describe Gitlab::Template::GitlabCiYmlTemplate do
subject { described_class }
describe '.all' do
it 'strips the gitlab-ci suffix' do
expect(subject.all.first.name).not_to end_with('.gitlab-ci.yml')
end
it 'combines the globals and rest' do
all = subject.all.map(&:name)
expect(all).to include('Elixir')
expect(all).to include('Docker')
expect(all).to include('Ruby')
end
end
describe '.find' do
it 'returns nil if the file does not exist' do
expect(subject.find('mepmep-yadida')).to be nil
end
it 'returns the GitlabCiYml object of a valid file' do
ruby = subject.find('Ruby')
expect(ruby).to be_a described_class
expect(ruby.name).to eq('Ruby')
end
end
describe '.by_category' do
it 'returns sorted results' do
result = described_class.by_category('General')
expect(result).to eq(result.sort)
end
end
describe '#content' do
it 'loads the full file' do
gitignore = subject.new(Rails.root.join('vendor/gitlab-ci-yml/Ruby.gitlab-ci.yml'))
expect(gitignore.name).to eq 'Ruby'
expect(gitignore.content).to start_with('#')
end
end
describe '#<=>' do
it 'sorts lexicographically' do
one = described_class.new('a.gitlab-ci.yml')
other = described_class.new('z.gitlab-ci.yml')
expect(one.<=>(other)).to be(-1)
expect([other, one].sort).to eq([one, other])
end
end
end
| 24.683333 | 89 | 0.64551 |
39447499d774a2277e1c6980c4687e59b8af0ff9 | 71 | # frozen_string_literal: true
Fabricator(:ignored_user) do
user
end
| 11.833333 | 29 | 0.788732 |
b98d3948ca8445d6f8eb864d0350f02feb508d6e | 159 | require 'settingslogic'
module EpiCas
class Settings < Settingslogic
source "#{Rails.root}/config/epi_cas_settings.yml"
namespace Rails.env
end
end | 22.714286 | 54 | 0.761006 |
91d809e8a46c4e12c9f510bbcb10f38b4ab67051 | 201 | class CreateKriteria < ActiveRecord::Migration[5.0]
def change
create_table :kriteria do |t|
t.string :nama
t.integer :tipe
t.float :bobot
t.timestamps
end
end
end
| 16.75 | 51 | 0.636816 |
f84590b3df06cad852faf20681a81d2786961265 | 2,313 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :test
host = 'example.com' # Don't use this literally; use your local dev host instead
# Use this on the cloud IDE.
config.action_mailer.default_url_options = { host: host, protocol: 'https' }
# Use this if developing on localhost.
# config.action_mailer.default_url_options = { host: host, protocol: 'http' }
end
| 36.140625 | 85 | 0.758755 |
794679a0b5f3a3f6c790b185fa2b1523c57d0925 | 138 | class AddRelevanceToAlerts < ActiveRecord::Migration[6.0]
def change
add_column :alerts, :relevance, :integer, default: 0
end
end
| 23 | 57 | 0.746377 |
62d74d83c28dcb82d63f97e88f5ffc67e698b30f | 5,552 | # frozen_string_literal: true
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
# Require this file early so that the version constant gets defined before
# requiring "google/cloud". This is because google-cloud-core will load the
# entrypoint (gem name) file, which in turn re-requires this file (hence
# causing a require cycle) unless the version constant is already defined.
require "google/cloud/workflows/executions/version"
require "googleauth"
gem "google-cloud-core"
require "google/cloud" unless defined? ::Google::Cloud.new
require "google/cloud/config"
# Set the default configuration
::Google::Cloud.configure.add_config! :workflows_executions do |config|
config.add_field! :endpoint, "workflowexecutions.googleapis.com", match: ::String
config.add_field! :credentials, nil, match: [::String, ::Hash, ::Google::Auth::Credentials]
config.add_field! :scope, nil, match: [::Array, ::String]
config.add_field! :lib_name, nil, match: ::String
config.add_field! :lib_version, nil, match: ::String
config.add_field! :interceptors, nil, match: ::Array
config.add_field! :timeout, nil, match: ::Numeric
config.add_field! :metadata, nil, match: ::Hash
config.add_field! :retry_policy, nil, match: [::Hash, ::Proc]
config.add_field! :quota_project, nil, match: ::String
end
module Google
module Cloud
module Workflows
module Executions
##
# Create a new client object for Executions.
#
# By default, this returns an instance of
# [Google::Cloud::Workflows::Executions::V1beta::Executions::Client](https://googleapis.dev/ruby/google-cloud-workflows-executions-v1beta/latest/Google/Cloud/Workflows/Executions/V1beta/Executions/Client.html)
# for version V1beta of the API.
# However, you can specify specify a different API version by passing it in the
# `version` parameter. If the Executions service is
# supported by that API version, and the corresponding gem is available, the
# appropriate versioned client will be returned.
#
# ## About Executions
#
# Executions is used to start and manage running instances of
# [Workflows][google.cloud.workflows.v1beta.Workflow] called executions.
#
# @param version [::String, ::Symbol] The API version to connect to. Optional.
# Defaults to `:v1beta`.
# @return [Executions::Client] A client object for the specified version.
#
def self.executions version: :v1beta, &block
require "google/cloud/workflows/executions/#{version.to_s.downcase}"
package_name = Google::Cloud::Workflows::Executions
.constants
.select { |sym| sym.to_s.downcase == version.to_s.downcase.tr("_", "") }
.first
package_module = Google::Cloud::Workflows::Executions.const_get package_name
package_module.const_get(:Executions).const_get(:Client).new(&block)
end
##
# Configure the google-cloud-workflows-executions library.
#
# The following configuration parameters are supported:
#
# * `credentials` (*type:* `String, Hash, Google::Auth::Credentials`) -
# The path to the keyfile as a String, the contents of the keyfile as a
# Hash, or a Google::Auth::Credentials object.
# * `lib_name` (*type:* `String`) -
# The library name as recorded in instrumentation and logging.
# * `lib_version` (*type:* `String`) -
# The library version as recorded in instrumentation and logging.
# * `interceptors` (*type:* `Array<GRPC::ClientInterceptor>`) -
# An array of interceptors that are run before calls are executed.
# * `timeout` (*type:* `Numeric`) -
# Default timeout in seconds.
# * `metadata` (*type:* `Hash{Symbol=>String}`) -
# Additional gRPC headers to be sent with the call.
# * `retry_policy` (*type:* `Hash`) -
# The retry policy. The value is a hash with the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) -
# The error codes that should trigger a retry.
#
# @return [::Google::Cloud::Config] The default configuration used by this library
#
def self.configure
yield ::Google::Cloud.configure.workflows_executions if block_given?
::Google::Cloud.configure.workflows_executions
end
end
end
end
end
helper_path = ::File.join __dir__, "executions", "helpers.rb"
require "google/cloud/workflows/executions/helpers" if ::File.file? helper_path
| 46.655462 | 217 | 0.659402 |
1c606199a78a9e203996df621feef9280158d00f | 881 | # frozen_string_literal: true
module MLP
class Layer
attr_accessor :level, :neurons
def initialize(params)
@level = params[:level]
@neurons = params[:neurons]
end
def each(&block)
neurons.each do |n|
block.call(n)
end
end
def last_output
neurons.map(&:last_output)
end
def each_with_index(&block)
neurons.each_with_index do |n, i|
block.call(n, i)
end
end
def inject(val, &block)
neurons.inject(val) do |value, n|
block.call(value, n)
end
end
def first
neurons.first
end
def last
neurons.last
end
def initial?
level.zero?
end
def delta
neurons.map(&:delta)
end
def update_weights(inputs, training_rate)
neurons.each { |n| n.update_weight(inputs, training_rate) }
end
end
end | 16.314815 | 65 | 0.586833 |
7a5636e39d38a4e431b8b1112bc8d93b5c8f59cd | 100 | # This is a single ruby file that doesn't do anything for testing Zeus
# load tracking during boot.
| 33.333333 | 70 | 0.77 |
ff6e8b033d162be1512494ac93a62f2ec0a81834 | 272 | ##
# Main application class inherited from {https://www.rubydoc.info/gems/anoubis/Anoubis/ApplicationController Anoubis::ApplicationController}
class AnoubisSsoClient::ApplicationController < Anoubis::ApplicationController
include AnoubisSsoClient::ApplicationCommon
end | 54.4 | 140 | 0.852941 |
1ce81b6029e973725cd679bda5071d9ca498342d | 15,321 | #--
# Copyright 2013 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#++
require_relative '../test_helper'
require 'pathname'
# Deploy cannot be testing in this manner. SELinux requires a valid UID or the tests fail.
# See cucumber test application_repository.feature
class ApplicationRepositoryFuncTest < OpenShift::NodeTestCase
GEAR_BASE_DIR = '/var/lib/openshift'
def before_setup
super
@uid = 5997
@config = mock('OpenShift::Config')
@config.stubs(:get).returns(nil)
@config.stubs(:get).with("GEAR_BASE_DIR").returns(GEAR_BASE_DIR)
@config.stubs(:get).with("GEAR_GECOS").returns('Functional Test')
@config.stubs(:get).with("CREATE_APP_SYMLINKS").returns('0')
@config.stubs(:get).with("GEAR_SKEL_DIR").returns(nil)
@config.stubs(:get).with("GEAR_SHELL").returns(nil)
@config.stubs(:get).with("CLOUD_DOMAIN").returns('example.com')
@config.stubs(:get).with("OPENSHIFT_HTTP_CONF_DIR").returns('/etc/httpd/conf.d/openshift')
@config.stubs(:get).with("PORT_BEGIN").returns(nil)
@config.stubs(:get).with("PORT_END").returns(nil)
@config.stubs(:get).with("PORTS_PER_USER").returns(5)
@config.stubs(:get).with("UID_BEGIN").returns(@uid)
@config.stubs(:get).with("BROKER_HOST").returns('localhost')
@config.stubs(:get).with("CARTRIDGE_BASE_PATH").returns('.')
OpenShift::Config.stubs(:new).returns(@config)
@uuid = `uuidgen -r |sed -e s/-//g`.chomp
begin
%x(userdel -f #{Etc.getpwuid(@uid).name})
rescue ArgumentError
end
@user = OpenShift::UnixUser.new(@uuid, @uuid,
@uid,
'AppRepoFuncTest',
'AppRepoFuncTest',
'functional-test')
@user.create
OpenShift::CartridgeRepository.instance.clear
OpenShift::CartridgeRepository.instance.load
@state = mock('OpenShift::Utils::ApplicationState')
@state.stubs(:value=).with('started').returns('started')
@hourglass = mock()
@hourglass.stubs(:remaining).returns(3600)
@model = OpenShift::V2CartridgeModel.new(@config, @user, @state, @hourglass)
@cartridge_name = 'mock-0.1'
@cartridge_directory = 'mock'
@cartridge_home = File.join(@user.homedir, @cartridge_directory)
@model.configure(@cartridge_name)
teardown
end
def after_teardown
@user.destroy
end
def teardown
FileUtils.rm_rf(File.join(@user.homedir, @cartridge_directory, 'template'))
FileUtils.rm_rf(File.join(@user.homedir, @cartridge_directory, 'template.git'))
FileUtils.rm_rf(File.join(@user.homedir, @cartridge_directory, 'usr', 'template'))
FileUtils.rm_rf(File.join(@user.homedir, @cartridge_directory, 'usr', 'template.git'))
end
def assert_bare_repository(repo)
assert_path_exist repo.path
assert_path_exist File.join(repo.path, 'description')
assert_path_exist File.join(@user.homedir, '.gitconfig')
assert_path_exist File.join(repo.path, 'hooks', 'pre-receive')
assert_path_exist File.join(repo.path, 'hooks', 'post-receive')
files = Dir[repo.path + '/objects/**/*']
assert files.count > 0, 'Error: Git repository missing objects'
files.each { |f|
stat = File.stat(f)
assert_equal @user.uid, stat.uid, 'Error: Git object wrong ownership'
}
stat = File.stat(File.join(repo.path, 'hooks'))
assert_equal 0, stat.uid, 'Error: Git hook directory not owned by root'
stat = File.stat(File.join(repo.path, 'hooks', 'post-receive'))
assert_equal 0, stat.uid, 'Error: Git hook post-receive not owned by root'
end
def test_new
repo = OpenShift::ApplicationRepository.new(@user)
refute_nil repo
end
def test_no_template
template = File.join(@user.homedir, @cartridge_directory, 'template')
FileUtils.rm_rf template
repo = OpenShift::ApplicationRepository.new(@user)
refute_path_exist template
repo.archive
end
def test_bare_repository_usr
create_template(File.join(@cartridge_home, 'usr', 'template', 'perl'))
create_bare(File.join(@cartridge_home, 'usr', 'template'))
cartridge_template_git = File.join(@cartridge_home, 'usr', 'template.git')
assert_path_exist cartridge_template_git
refute_path_exist File.join(@cartridge_home, 'usr', 'template')
expected_path = File.join(@user.homedir, 'git', @user.app_name + '.git')
repo = OpenShift::ApplicationRepository.new(@user)
repo.destroy
repo.populate_from_cartridge(@cartridge_directory)
assert_equal expected_path, repo.path
assert_bare_repository(repo)
assert repo.exist?, "Application Repository (#{repo.path}) not found"
assert repo.exists?, "Application Repository (#{repo.path}) not found"
end
def test_bare_repository
create_template(File.join(@cartridge_home, 'template', 'perl'))
create_bare(File.join(@cartridge_home, 'template'))
cartridge_template_git = File.join(@cartridge_home, 'template.git')
assert_path_exist cartridge_template_git
refute_path_exist File.join(@cartridge_home, 'template')
expected_path = File.join(@user.homedir, 'git', @user.app_name + '.git')
repo = OpenShift::ApplicationRepository.new(@user)
repo.destroy
begin
repo.populate_from_cartridge(@cartridge_directory)
rescue OpenShift::Utils::ShellExecutionException => e
puts %Q{
Failed to create git repo from cartridge template: rc(#{e.rc})
stdout ==> #{e.stdout}
stderr ==> #{e.stderr}
#{e.backtrace.join("\n")}}
raise
end
assert_equal expected_path, repo.path
assert_bare_repository(repo)
assert repo.exist?, "Application Repository (#{repo.path}) not found"
assert repo.exists?, "Application Repository (#{repo.path}) not found"
end
def test_from_url
create_template(File.join(@cartridge_home, 'template', 'perl'))
create_bare(File.join(@cartridge_home, 'template'))
cartridge_template_git = File.join(@cartridge_home, 'template.git')
assert_path_exist cartridge_template_git
refute_path_exist File.join(@cartridge_home, 'template')
cartridge_template_url = "file://#{cartridge_template_git}"
expected_path = File.join(@user.homedir, 'git', @user.app_name + '.git')
repo = OpenShift::ApplicationRepository.new(@user)
repo.destroy
begin
repo.populate_from_url(@cartridge_name, cartridge_template_url)
rescue OpenShift::Utils::ShellExecutionException => e
puts %Q{
Failed to create git repo from cartridge template: rc(#{e.rc})
stdout ==> #{e.stdout}
stderr ==> #{e.stderr}
#{e.backtrace.join("\n")}}
raise
end
assert_equal expected_path, repo.path
assert_bare_repository(repo)
end
def test_from_ssh_url
e = assert_raise(OpenShift::Utils::ShellExecutionException) do
repo = OpenShift::ApplicationRepository.new(@user)
repo.destroy
repo.populate_from_url(@cartridge_name, '[email protected]:jwhonce/origin-server.git')
end
assert_equal 130, e.rc
assert e.message.start_with?('CLIENT_ERROR:')
end
def test_source_usr
refute_path_exist File.join(@cartridge_home, 'template.git')
create_template(File.join(@cartridge_home, 'usr', 'template', 'perl'))
expected_path = File.join(@user.homedir, 'git', @user.app_name + '.git')
repo = OpenShift::ApplicationRepository.new(@user)
repo.destroy
refute_path_exist(expected_path)
begin
repo.populate_from_cartridge(@cartridge_directory)
assert_equal expected_path, repo.path
assert_bare_repository(repo)
runtime_repo = "#{@user.homedir}/app-root/runtime/repo"
FileUtils.mkpath(runtime_repo)
repo.archive
assert_path_exist File.join(runtime_repo, 'perl', 'health_check.pl')
rescue OpenShift::Utils::ShellExecutionException => e
puts %Q{
Failed to create git repo from cartridge template: rc(#{e.rc})
stdout ==> #{e.stdout}
stderr ==> #{e.stderr}
#{e.backtrace.join("\n")}}
raise
end
end
def test_source
create_template(File.join(@cartridge_home, 'template', 'perl'))
expected_path = File.join(@user.homedir, 'git', @user.app_name + '.git')
refute_path_exist File.join(@cartridge_home, 'template.git')
repo = OpenShift::ApplicationRepository.new(@user)
repo.destroy
refute_path_exist(expected_path)
begin
repo.populate_from_cartridge(@cartridge_directory)
assert_equal expected_path, repo.path
assert_bare_repository(repo)
runtime_repo = "#{@user.homedir}/app-root/runtime/repo"
FileUtils.mkpath(runtime_repo)
repo.archive
assert_path_exist File.join(runtime_repo, 'perl', 'health_check.pl')
rescue OpenShift::Utils::ShellExecutionException => e
puts %Q{
Failed to create git repo from cartridge template: rc(#{e.rc})
stdout ==> #{e.stdout}
stderr ==> #{e.stderr}
#{e.backtrace.join("\n")}}
raise
end
end
def test_bare_submodule
create_template(File.join(@cartridge_home, 'template', 'perl'))
create_bare_submodule
expected_path = File.join(@user.homedir, 'git', @user.app_name + '.git')
repo = OpenShift::ApplicationRepository.new(@user)
repo.destroy
refute_path_exist(expected_path)
begin
repo.populate_from_cartridge(@cartridge_directory)
assert_equal expected_path, repo.path
assert_bare_repository(repo)
runtime_repo = "#{@user.homedir}/app-root/runtime/repo"
FileUtils.mkpath(runtime_repo)
repo.archive
assert_path_exist File.join(runtime_repo, 'perl', 'health_check.pl')
assert_path_exist File.join(runtime_repo, 'module001', 'README.md')
rescue OpenShift::Utils::ShellExecutionException => e
puts %Q{
Failed to create git repo from cartridge template: rc(#{e.rc})
stdout ==> #{e.stdout}
stderr ==> #{e.stderr}
#{e.backtrace.join("\n")}}
raise
end
end
def test_bare_nested_submodule
create_template(File.join(@cartridge_home, 'template', 'perl'))
create_bare_nested_submodule
expected_path = File.join(@user.homedir, 'git', @user.app_name + '.git')
repo = OpenShift::ApplicationRepository.new(@user)
repo.destroy
refute_path_exist(expected_path)
begin
repo.populate_from_cartridge(@cartridge_directory)
assert_equal expected_path, repo.path
assert_bare_repository(repo)
runtime_repo = "#{@user.homedir}/app-root/runtime/repo"
FileUtils.mkpath(runtime_repo)
repo.archive
assert_path_exist File.join(runtime_repo, 'perl', 'health_check.pl')
assert_path_exist File.join(runtime_repo, 'lib', 'module001', 'README.md')
assert_path_exist File.join(runtime_repo, 'lib', 'module001', 'module002', 'README.md')
rescue OpenShift::Utils::ShellExecutionException => e
puts %Q{
Failed to create git repo from cartridge template: rc(#{e.rc})
stdout ==> #{e.stdout}
stderr ==> #{e.stderr}
#{e.backtrace.join("\n")}}
raise
end
end
def create_template(path)
# Cartridge Author tasks...
#perl = File.join(@cartridge_home, 'template', 'perl')
FileUtils.mkpath(path)
File.open(File.join(path, 'health_check.pl'), 'w', 0664) { |f|
f.write(%q{\
#!/usr/bin/perl
print "Content-type: text/plain\r\n\r\n";
print "1";
})
}
File.open(File.join(path, 'index.pl'), 'w', 0664) { |f|
f.write(%q{\
#!/usr/bin/perl
print "Content-type: text/html\r\n\r\n";
print <<EOF
<html>
<head>
<title>Welcome to OpenShift</title>
</head>
<body>
<p>Welcome to OpenShift
</body>
</html>
EOF
})
FileUtils.chown_R(@user.uid, @user.uid, path)
}
end
def create_bare(template)
Dir.chdir(@cartridge_home) do
output = %x{set -xe;
pushd #{template};
git init;
git config user.email "[email protected]";
git config user.name "Mock Template builder";
git add -f .;
git </dev/null commit -a -m "Creating mocking template" 2>&1;
cd ..;
git </dev/null clone --bare --no-hardlinks template template.git 2>&1;
chown -R #{@user.uid}:#{@user.uid} template template.git;
popd;
}
#puts "\ncreate_bare: #{output}"
FileUtils.rm_r(template)
end
end
def create_bare_submodule
template = File.join(@cartridge_home, 'template')
submodule = File.join(@cartridge_home, 'module001')
Dir.chdir(@cartridge_home) do
output = %x{set -xe;
mkdir module001;
pushd module001;
git init;
git config user.email "[email protected]";
git config user.name "Mock Module builder";
touch README.md;
git add -f .;
git </dev/null commit -a -m "Creating module" 2>&1;
popd
pushd #{template}
git init;
git config user.email "[email protected]";
git config user.name "Mock Template builder";
git add -f .;
git </dev/null commit -a -m "Creating mocking template" 2>&1;
git submodule add #{submodule} module001
git submodule update --init
git </dev/null commit -m 'Added submodule module001'
popd;
git </dev/null clone --bare --no-hardlinks template template.git 2>&1;
chown -R #{@user.uid}:#{@user.uid} template template.git
}
FileUtils.chown_R(@user.uid, @user.uid, template)
#puts "\ncreate_bare_submodule: #{output}"
FileUtils.rm_r(template)
end
end
def create_bare_nested_submodule
template = File.join(@cartridge_home, 'template')
submodule = File.join(@cartridge_home, 'module001')
nested_submodule = File.join(@cartridge_home, 'module002')
Dir.chdir(@cartridge_home) do
output = %x{\
set -xe;
mkdir module002;
pushd module002;
git init;
git config user.email "[email protected]";
git config user.name "Mock Module builder";
touch README.md;
git add -f .;
git </dev/null commit -a -m "Creating module002" 2>&1;
popd;
mkdir module001;
pushd module001;
git init;
git config user.email "[email protected]";
git config user.name "Mock Module builder";
touch README.md;
git add -f .;
git submodule add #{nested_submodule} module002
git submodule update --init
git </dev/null commit -a -m "Creating module001" 2>&1;
popd;
pushd #{template}
git init;
git config user.email "[email protected]";
git config user.name "Mock Template builder";
touch README.md;
mkdir lib;
git add -f .;
git </dev/null commit -a -m "Creating mocking template" 2>&1;
git submodule add #{submodule} lib/module001
git submodule update --init
git </dev/null commit -m 'Added submodule module001'
popd;
git </dev/null clone --bare --no-hardlinks template template.git 2>&1;
chown -R #{@user.uid}:#{@user.uid} template template.git
}
FileUtils.chown_R(@user.uid, @user.uid, template)
#puts "\ncreate_bare_submodule: #{output}"
FileUtils.rm_r(template)
end
end
end
| 32.322785 | 94 | 0.684094 |
ed4b5f8a14807711bc99a292e33d5667b6e9ec32 | 786 | require File.dirname(__FILE__) + '/../../../../spec_helper'
require 'net/http'
require File.dirname(__FILE__) + "/fixtures/classes"
describe "Net::HTTPHeader#delete when passed key" do
before(:each) do
@headers = NetHTTPHeaderSpecs::Example.new
end
it "removes the header entry with the passed key" do
@headers["My-Header"] = "test"
@headers.delete("My-Header")
@headers["My-Header"].should be_nil
@headers.size.should eql(0)
end
it "returns the removed values" do
@headers["My-Header"] = "test"
@headers.delete("My-Header").should == ["test"]
end
it "is case-insensitive" do
@headers["My-Header"] = "test"
@headers.delete("my-header")
@headers["My-Header"].should be_nil
@headers.size.should eql(0)
end
end
| 25.354839 | 59 | 0.650127 |
08062b3f2e644d71b6b0382b6253f6ab1f558204 | 426 | # frozen_string_literal: true
require 'bundler'
Bundler.setup(:test, :development)
require 'simplecov'
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.421053 | 66 | 0.755869 |
185d4e77f23fb5c78327e0217645b41540c9963b | 1,039 | # frozen_string_literal: true
module MSR
# Represents a single track from a magnetic stripe card.
class Track
# Whether or not the track contains any data.
# @return [Boolean] `true` if empty, `false` otherwise
def empty?
data.empty?
end
# Reverse the direction of the track, in place.
# @return [MSR::Tracks] the current instance
def reverse!
@data = reverse.data
self # return ourself, just for convenience
end
# Return a string representation of the track's data.
# @note May or may not be human readable.
# @return [String] a string representation of track data
def to_s
data.map(&:chr).join
end
# Compare two tracks for equality. Two tracks are said to be equal if they
# contain the same data, in the same order.
# @param other [Track] the track to compare to
# @return [Boolean] `true` if the two are equal, `false` otherwise
def ==(other)
return unless other.is_a?(self.class)
data == other.data
end
end
end
| 28.081081 | 78 | 0.659288 |
87647791a810ee73270400e579fd6ec69c3cbe25 | 1,354 | Pod::Spec.new do |s|
s.name = "DesktopADView"
s.version = "2.3.3"
s.summary = "仿滴滴/Uber 的启动之后再控制器上面弹出多个广告,带删除按钮的动画绘制"
s.homepage = "https://github.com/tpctt/DesktopADView"
s.social_media_url = "https://github.com/tpctt/DesktopADView"
s.platform = :ios,'6.0'
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { " tim" => "[email protected]" }
s.source = { :git => "https://github.com/tpctt/DesktopADView.git",:tag => s.version.to_s }
s.ios.deployment_target = "6.0"
s.requires_arc = true
s.framework = "CoreFoundation","Foundation","CoreGraphics","Security","UIKit"
s.library = "z.1.1.3","stdc++","sqlite3"
s.source_files = 'DesktopADView/**/*.{h,m,mm}'
#s.resources = 'SIDADView/*.{bundle}'
# s.subspec 'YMCitySelect' do |sp|
# sp.source_files = 'YMCitySelect/*.{h,m,mm}'
# sp.resources = "Extend/**/*.{png}"
# sp.requires_arc = true
# sp.xcconfig = { 'HEADER_SEARCH_PATHS' => '$(SDKROOT)/usr/include/libz, $(SDKROOT)/usr/include/libxml2', 'CLANG_CXX_LANGUAGE_STANDARD' => 'gnu++0x', 'CLANG_CXX_LIBRARY' => 'libstdc++', 'CLANG_WARN_DIRECT_OBJC_ISA_USAGE' => 'YES'}
# sp.dependency 'FontIcon'
# sp.prefix_header_contents = '#import "EasyIOS.h"'
# end
end
| 46.689655 | 232 | 0.587888 |
ff4f0c4fa71ebc422a7e1ccccb09c73d941af6e7 | 984 | #
# Created by teambition-ios on 2020/7/27.
# Copyright © 2020 teambition. All rights reserved.
#
Pod::Spec.new do |s|
s.name = 'ManagedObjectAdapter'
s.version = '0.0.7'
s.summary = 'ManagedObjectAdapter is a lightweight adapter for the converts between Model instances and Core Data managed objects.'
s.description = <<-DESC
ManagedObjectAdapter is a lightweight adapter for the converts between Model instances and Core Data managed objects.
DESC
s.homepage = 'https://github.com/teambition/ManagedObjectAdapter'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'teambition mobile' => '[email protected]' }
s.source = { :git => 'https://github.com/teambition/ManagedObjectAdapter.git', :tag => s.version.to_s }
s.swift_version = '5.0'
s.ios.deployment_target = '8.0'
s.source_files = 'ManagedObjectAdapter/*.swift'
end
| 39.36 | 142 | 0.643293 |
26e86be96b2b9b501a3457d8cfd1d12e267c2ebc | 131 | class Random
def next_move game
game.board.get_available_positions.sample
end
def name
"Frederick Random"
end
end
| 13.1 | 45 | 0.732824 |
21ff1d87d46ac3993ba6b70186c3540627980f02 | 513 | Given(/^the username is "(.*?)"$/) do |arg1|
@username = arg1
end
When(/^the password is "(.*?)"$/) do |arg1|
@password = arg1
end
Then(/^the result should be "(.*?)"$/) do |arg1|
@result = arg1
uuid = SecureRandom.uuid
user = "login_user_#{@username}_#{uuid}@jemurai.com"
register_as_user(user, "password")
logout(user)
login_as_user(user, @password)
if @result == "fail"
expect(page).to have_content 'Sign in'
else
expect(page).to have_content 'Dashboard'
end
end | 20.52 | 54 | 0.623782 |
39f2458c4ab86956e6df8c8497aa3e841988f2fe | 1,610 | require 'time'
def silence_warnings
old_verbose, $VERBOSE = $VERBOSE, nil
yield
ensure
$VERBOSE = old_verbose
end
class Object
def blank?
respond_to?(:empty?) ? empty? : !self
end
def present?
!blank?
end
def try(m, *args)
send(m, *args) if respond_to?(m)
end
end
class NilClass
def try(*args)
end
end
class String
def underscore
word = self.dup
word.gsub!('::', '/')
word.gsub!(/(?:([A-Za-z\d])|^)((?=a)b)(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" }
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2')
word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
word.tr!('-', '_')
word.downcase!
word
end
end
class Array
def extract_options!
self[-1].is_a?(Hash) ? self.pop : {}
end
end
class Numeric
def percents
self
end
alias_method :percent, :percents
def seconds
self
end
alias_method :second, :seconds
def minutes
self * 60
end
alias_method :minute, :minutes
def hours
self * 3600
end
alias_method :hour, :hours
def days
self * 86_400
end
alias_method :day, :days
def weeks
self * 86_400 * 7
end
alias_method :week, :weeks
def ago
::Time.now - self
end
def bytes
self
end
alias_method :byte, :bytes
def kilobytes
self * 1024
end
alias_method :kilobyte, :kilobytes
def megabytes
self * 1024 * 1024
end
alias_method :megabyte, :megabytes
def gigabytes
self * 1024 * 1024 * 1024
end
alias_method :gigabyte, :gigabytes
def terabytes
self * 1024 * 1024 * 1024 * 1024
end
alias_method :terabyte, :terabytes
end
| 14.907407 | 95 | 0.601242 |
910709cf57d4f980d2c0afafd47cb0169fc8ad86 | 119 | module MoneyS3
module Parsers
class FaktPrij < FakturaType
include ParserCore::BaseParser
end
end
end | 17 | 36 | 0.722689 |
d5008b369691de2beef2cbbb99197555e42a77b9 | 444 | # MODULE templates/en-us/html/extensions/MAB_Clubs_read_shop.rb
# VIEW views/Clubs_read_shop.rb
# SASS ~/megauni/templates/en-us/css/Clubs_read_shop.sass
# NAME Clubs_read_shop
club_nav_bar(__FILE__)
pretension!
div.substance! {
messages! {
everybody {
messages_or_guide
}
}
publish! {
everybody { about }
insider_or_owner {
post_message
}
} # === publish!
} # === div.substance!
| 15.310345 | 63 | 0.650901 |
393745bc0db43dd727f648ab8f0a5750fbd071f7 | 1,321 | require 'rails_helper'
RSpec.describe 'Siging Up', type: :feature do
let(:user) { User.new(username: 'tarly', fullname: 'truly') }
scenario 'Sign up with valid inputs' do
visit login_path
click_on 'Sign up'
find(:css, '#new_fullname', visible: false).set user.fullname
find(:css, '#new_username', visible: false).set user.username
click_on 'Sign up'
sleep(3)
visit home_path
expect(page).to have_content('truly')
end
scenario 'Sign up with invalid inputs' do
visit login_path
click_on 'Sign up'
find(:css, '#new_fullname', visible: false).set ' '
find(:css, '#new_username', visible: false).set user.username
click_on 'Sign up'
expect(page).to have_content('Fullname can\'t be blank')
end
end
RSpec.describe 'Loggin In', type: :feature do
let(:user) { User.create(username: 'mrigorir') }
scenario 'Log in with invalid inputs' do
visit login_path
find(:css, '#login_username', visible: false).set user.username
click_on 'Login'
sleep(3)
expect(page).to_not have_content('Tweets')
end
scenario 'Log in with invalid inputs' do
visit login_path
find(:css, '#login_username', visible: false).set ' '
click_on 'Login'
sleep(3)
expect(page).to have_content('Username does not exist in our database')
end
end
| 30.022727 | 75 | 0.680545 |
26c99f48efda6684203ac23fd27fe262cdad4e56 | 350 | cask 'mediathekview' do
version '13.5.0'
sha256 'ac634ab0383270e61ed1fe91905c0f5c8dfa8a15408d1471ed1b2669974d07bd'
url "https://download.mediathekview.de/stabil/MediathekView-#{version}-mac.dmg"
appcast 'https://mediathekview.de/changelog/index.xml'
name 'MediathekView'
homepage 'https://mediathekview.de/'
suite 'MediathekView'
end
| 29.166667 | 81 | 0.78 |
87d887b0cb4933896e169564a5d3e98fb153fcf5 | 301 | require "walmart_open/product_request"
module WalmartOpen
module Requests
class Taxonomy < ProductRequest
def initialize
self.path = "taxonomy"
end
private
def parse_response(response)
response.parsed_response["categories"]
end
end
end
end
| 16.722222 | 46 | 0.667774 |
f8088efc8ade3b51cfa2d63ee9b3af8de929f77e | 1,776 | require 'logger'
module Rack
class ContentLengthChecker
# @param app []
# @param logger [] logger
# @param options [Hash] opts チェックするオプション
# @option opts [Symbol] :warn lenght と 例外を排出するかの
# @option opts [Symbol] :fatal lenght と 例外を排出するかの
# @return Object
def initialize(app, warn: {}, fatal: {}, logger: ::Logger.new(STDOUT))
@app = app
@logger = logger
@warn = warn
@fatal = fatal
@warn_length = @warn[:length].to_i
@fatal_length = @fatal[:length] ? @fatal[:length].to_i : Float::INFINITY
raise ArgumentError, 'warn length is greater than 0' if @warn_length < 0
raise ArgumentError, 'fatal length is greater than 1' if @fatal_length < 1
raise ArgumentError, 'Warn length is smaller than fatal one.' if (([email protected]?) && (@warn[:length].to_i > @fatal[:length].to_i))
end
def call(env)
request_length = env['CONTENT_LENGTH'].to_i
error_status = 413
error_headers = {'Content-Type' => 'text/plain'}
error_body = "Request Entity Too Large : #{request_length} bytes"
error_message = "remote_addr:#{env['HTTP_X_FORWARDED_FOR']}\tmethod:#{env['REQUEST_METHOD']}\turi:#{env['REQUEST_URI']}\tmsg:#{error_body}"
case request_length
when @warn_length..@fatal_length-1
unless @warn.empty?
@logger.warn(error_message)
return [error_status, error_headers, [error_body]] if @warn[:is_error]
end
when @fatal_length..Float::INFINITY
unless @fatal.empty?
@logger.fatal(error_message)
return [error_status, error_headers, [error_body]] if @fatal[:is_error]
end
end
status, headers, body = @app.call(env)
[status, headers, body]
end
end
end
| 37 | 145 | 0.634009 |
abb1613023b8f2d8675829339f8e1744f1419968 | 1,077 | require 'formula'
class Nmap < Formula
homepage "http://nmap.org/"
head "https://guest:@svn.nmap.org/nmap/", :using => :svn
url "http://nmap.org/dist/nmap-6.47.tar.bz2"
sha1 "0c917453a91a5e85c2a217d27c3853b0f3e0e6ac"
bottle do
revision 1
sha1 "f866508268e57a381a1c2456456c5580f83e5bc4" => :mavericks
sha1 "c80f12d6d1a52bca5ff152404a84a5c4436ba7b3" => :mountain_lion
sha1 "28da4ac4b94c636b1acd02ca1b17cbb799f86f3f" => :lion
end
depends_on "openssl"
conflicts_with 'ndiff', :because => 'both install `ndiff` binaries'
fails_with :llvm do
build 2334
end
def install
ENV.deparallelize
args = %W[
--prefix=#{prefix}
--with-libpcre=included
--with-liblua=included
--with-openssl=#{Formula["openssl"].opt_prefix}
--without-nmap-update
--without-zenmap
--disable-universal
]
system "./configure", *args
system "make" # separate steps required otherwise the build fails
system "make install"
end
test do
system "#{bin}/nmap", '-p80,443', 'google.com'
end
end
| 23.413043 | 69 | 0.674095 |
3830e4ad404c8673b826670de96468ad38a37154 | 118 | # frozen_string_literal: true
module BenefitSponsors
module Organizations
class Organization
end
end
end
| 13.111111 | 29 | 0.771186 |
acb3bee5426ff6e4ddbf629a4b82739c138b98be | 5,254 | #
# Author:: Derek Groh (<[email protected]>)
# Copyright:: 2018, Derek Groh
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require_relative "../resource"
require "chef-utils/dist" unless defined?(ChefUtils::Dist)
class Chef
class Resource
class WindowsWorkgroup < Chef::Resource
unified_mode true
provides :windows_workgroup
description "Use the **windows_workgroup** resource to join or change the workgroup of a Windows host."
introduced "14.5"
examples <<~DOC
**Join a workgroup**:
```ruby
windows_workgroup 'myworkgroup'
```
**Join a workgroup using a specific user**:
```ruby
windows_workgroup 'myworkgroup' do
user 'Administrator'
password 'passw0rd'
end
```
DOC
property :workgroup_name, String,
description: "An optional property to set the workgroup name if it differs from the resource block's name.",
validation_message: "The 'workgroup_name' property must not contain spaces.",
regex: /^\S*$/, # no spaces
name_property: true
property :user, String,
description: "The local administrator user to use to change the workgroup. Required if using the `password` property.",
desired_state: false
property :password, String,
description: "The password for the local administrator user. Required if using the `user` property.",
sensitive: true,
desired_state: false
property :reboot, Symbol,
equal_to: %i{never request_reboot reboot_now},
validation_message: "The reboot property accepts :immediate (reboot as soon as the resource completes), :delayed (reboot once the #{ChefUtils::Dist::Infra::PRODUCT} run completes), and :never (Don't reboot)",
description: "Controls the system reboot behavior post workgroup joining. Reboot immediately, after the #{ChefUtils::Dist::Infra::PRODUCT} run completes, or never. Note that a reboot is necessary for changes to take effect.",
coerce: proc { |x| clarify_reboot(x) },
default: :immediate, desired_state: false
# This resource historically took `:immediate` and `:delayed` as arguments to the reboot property but then
# tried to shove that straight to the `reboot` resource which objected strenuously. We need to convert these
# legacy actions into actual reboot actions
#
# @return [Symbol] chef reboot resource action
def clarify_reboot(reboot_action)
case reboot_action
when :immediate
:reboot_now
when :delayed
:request_reboot
else
reboot_action
end
end
# define this again so we can default it to true. Otherwise failures print the password
# FIXME: this should now be unnecessary with the password property itself marked sensitive?
property :sensitive, [TrueClass, FalseClass],
default: true, desired_state: false
action :join, description: "Update the workgroup." do
unless workgroup_member?
converge_by("join workstation workgroup #{new_resource.workgroup_name}") do
ps_run = powershell_exec(join_command)
raise "Failed to join the workgroup #{new_resource.workgroup_name}: #{ps_run.errors}}" if ps_run.error?
unless new_resource.reboot == :never
reboot "Reboot to join workgroup #{new_resource.workgroup_name}" do
action new_resource.reboot
reason "Reboot to join workgroup #{new_resource.workgroup_name}"
end
end
end
end
end
action_class do
# return [String] the appropriate PS command to joint the workgroup
def join_command
cmd = ""
cmd << "$pswd = ConvertTo-SecureString \'#{new_resource.password}\' -AsPlainText -Force;" if new_resource.password
cmd << "$credential = New-Object System.Management.Automation.PSCredential (\"#{new_resource.user}\",$pswd);" if new_resource.password
cmd << "Add-Computer -WorkgroupName #{new_resource.workgroup_name}"
cmd << " -Credential $credential" if new_resource.password
cmd << " -Force"
cmd
end
# @return [Boolean] is the node a member of the workgroup specified in the resource
def workgroup_member?
node_workgroup = powershell_exec!("(Get-WmiObject -Class Win32_ComputerSystem).Workgroup")
raise "Failed to determine if system already a member of workgroup #{new_resource.workgroup_name}" if node_workgroup.error?
String(node_workgroup.result).downcase.strip == new_resource.workgroup_name.downcase
end
end
end
end
end
| 40.415385 | 233 | 0.674343 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.