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
|
---|---|---|---|---|---|
792df7ffa8783735377c96b957cb5489753a4490 | 403 | require "coveralls"
Coveralls.wear!
require "bundler/setup"
require "nutrientes"
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.388889 | 66 | 0.756824 |
e26086c36d4c24962978b7a8db0028f16eebb63a | 92 | ActionController::Dispatcher.to_prepare do
BaseController.renders_in_context :section
end
| 23 | 44 | 0.869565 |
38a3f3f504357b159f387f3a27bc16c721b8436e | 371 | # This migration shouldn't change these column types, but we need it to stick around
# so just comment out column changes
class IntsToBigint < ActiveRecord::Migration[5.1]
def up
remove_foreign_key :users, :roles
# change_column :users, :role_id, :bigint
end
def down
# change_column :users, :role_id, :int
add_foreign_key :users, :roles
end
end
| 26.5 | 84 | 0.725067 |
bf17f91a5cf86cd953ac74a0584c65c4e9ad3668 | 7,114 | # Copyright (c) 2015 Vault12, Inc.
# MIT License https://opensource.org/licenses/MIT
class SessionController < ApplicationController
include TransactionHelper
before_action :preamble
# POST /start_session - start handshake
def start_session_token
reportCommonErrors("start_session_token error ") do
# ready only the number of bytes we expect
@body = request.body.read SESSION_START_BODY
# we expect 1 line to be start session
lines = _check_body_lines @body, 1, 'start session'
# check that the client token is valid
@client_token = _check_client_token lines[0]
# lets make the relay token to initiate handshake
@relay_token = make_relay_token
# save both tokens to redis
cache_tokens
diff = get_diff(false)
# Send back our token in a base64 response body
render plain: "#{@relay_token.to_b64}\r\n#{diff}"
adjust_difficulty
end
end
# POST /verify_session - verify started handshake
def verify_session_token
reportCommonErrors("verify_session_token error ") do
# read only the bytes we expect for verification
@body = request.body.read SESSION_VERIFY_BODY
# original token and signature in 2 lines
lines = _check_body_lines @body, 2, 'verify session'
# check that client token line is valid
_check_client_token lines[0]
# decode and check both lines
decode = decode_lines lines
# check handshake or throw error
# returns client_token and its h2() from cache
ct, h2_ct = verify_handshake(decode)
# signature is valid, lets make temp keys
session_key = make_session_key h2_ct
# resond with relay temp key for this session
# masked by client token
render plain: "#{session_key.public_key.to_bytes.to_b64}"
adjust_difficulty
end
end
# Missing routes, mostly triggered by spammers
def missing_route
logger.warn "#{SPAM} Spammers scan for: #{request.path}"
head :service_unavailable # Let's pretend we are dead
end
# === Private helper functions ===
private
def preamble # runs before every response
expires_now # never cache
end
# Use NaCl service to generate random 32 bytes token
def make_relay_token
relay_token = RbNaCl::Random.random_bytes TOKEN_LEN
# Sanity check server-side RNG
if !relay_token || relay_token.length != TOKEN_LEN
fail SevereRandomError.new
end
relay_token
end
# Save to cache @client_token and @relay_token
# This pair will identify unique handshake until the session is ready
def cache_tokens
h2_client_token = h2 @client_token
Rails.cache.write "client_token_#{h2_client_token}",
@client_token,
expires_in: Rails.configuration.x.relay.token_timeout
Rails.cache.write "relay_token_#{h2_client_token}",
@relay_token,
expires_in: Rails.configuration.x.relay.token_timeout
end
# decode body lines from base64 and return the decoded array
def decode_lines(lines)
lines.map do |l|
if l.length == TOKEN_B64
l.from_b64
else
fail ReportError.new self,
msg:"verify_session lines wrong size, expecting #{TOKEN_B64}"
end
end
end
# h₂(client_token) becomes the handhshake storage tag in redis
# if we dont find client_token itself at that storage key
# it means there was no handshake or it is expired
def load_cached_tokens(h2_ct)
ct = Rails.cache.read "client_token_#{h2_ct}"
if ct.nil? || ct.length != TOKEN_LEN
fail ClientTokenError.new self,
client_token: dumpHex(ct),
msg: "session controller: client token not registered/wrong size, expecting #{TOKEN_LEN}b"
end
rt = Rails.cache.read "relay_token_#{h2_ct}"
if rt.nil? || rt.length != TOKEN_LEN
fail RelayTokenError.new self,
rt: dumpHex(rt),
msg: "session controller: relay token not registered/wrong size, expecting #{TOKEN_LEN}b"
end
[ct,rt]
end
# For simple 0 diffculty handshake simply verifies
# that the client sent h₂(client_token,relay_token).
# For higher difficulty, verify that the nonce sent by
# client makes h₂(client_token, relay_token, nonce)
# to have difficulty num of leading zero bits.
def verify_handshake(lines)
h2_client_token, h2_client_sign = lines
ct, rt = load_cached_tokens(h2_client_token)
unless h2_client_token.eql? h2(ct)
fail ClientTokenError.new self,
client_token: dumpHex(ct),
msg: 'handshake mismatch: wrong client token'
end
# With difficulty throttling we keep a short window for
# older nonces to validate using older diff setting
# Window closes when ZAX_TEMP_DIFF expires in redis
diff = get_diff
unless static_diff?
diff2 = get_diff(true) # Old value if present
if diff != diff2 # There was a recent change
if diff == 0 or diff2 == 0 # Special case of changing to/from 0 diff
correct_sign = h2(ct + rt) # Check if client uses 0 diff algorithm
diff = 0 if h2_client_sign.eql? correct_sign
else
# Use easier one to confirm
diff = [diff,diff2].min
end
end
end
if diff == 0
correct_sign = h2(ct + rt)
unless h2_client_sign.eql? correct_sign
fail ClientTokenError.new self,
client_token: dumpHex(ct),
msg: 'handshake: wrong hash for 0 difficulty'
end
else
nonce = h2_client_sign
hash = h2(ct + rt + nonce).bytes
unless array_zero_bits?(hash, diff)
fail ClientTokenError.new self,
client_token: dumpHex(ct),
msg: "handshake: wrong nonce for difficulty #{diff}"
end
end
return [ct, h2_client_token]
end
# Once the client passes handshake verification, we generate and cache the
# session keys.
def make_session_key(h2_client_token)
# establish session keys
session_key = RbNaCl::PrivateKey.generate
# report errors with keys if any
if session_key.nil? || session_key.public_key.to_bytes.length != KEY_LEN
fail SevereKeyError.new(self, msg: 'New session key: generation failed or too short')
end
# store session key on the h₂(client_token) tag in redis
Rails.cache.write(
"session_key_#{h2_client_token}",
session_key,
expires_in: Rails.configuration.x.relay.session_timeout )
session_key
end
def adjust_difficulty
return if static_diff? # Throttling disabled if period not set
period = Rails.configuration.x.relay.period
rds.incr "ZAX_session_counter_#{ DateTime.now.minute / period }"
unless rds.exists? ZAX_DIFF_JOB_UP
# begining of next period
job_time = start_diff_period(period, 1)
ttl = job_time.to_i - DateTime.now.to_i
rds.set ZAX_DIFF_JOB_UP, 1, { ex: ttl }
DiffAdjustJob.set(wait_until: job_time).perform_later()
# If traffic spike is over reset to normal difficulty
cleanup_time = start_diff_period(period, ZAX_DIFF_LENGTH)
DiffAdjustJob.set(wait_until: cleanup_time).perform_later()
end
end
end
| 32.190045 | 98 | 0.691453 |
1cb824003ef13a80431755971c736e9dfa6617aa | 929 | class Libmonome < Formula
desc "Interact with monome devices via C, Python, or FFI"
homepage "http://illest.net/libmonome/"
url "https://github.com/monome/libmonome/releases/download/v1.4.0/libmonome-1.4.0.tar.bz2"
sha256 "0a04ae4b882ea290f3578bcba8e181c7a3b333b35b3c2410407126d5418d149a"
head "https://github.com/monome/libmonome.git"
bottle do
sha256 "6473c190c553546e9f648b7dbcc5c43b1b4cfeff54898d7f373c309092c5ad86" => :sierra
sha256 "b6553b4ce4d56cca44493acd9615cc399d5e20b6acb403a36914a0df5151926e" => :el_capitan
sha256 "0c730849c05d8899a6e4bd0f1c3bfdeb791de8fd5d8b10d5c29800b68a2a0906" => :yosemite
sha256 "b79cc0774b4c270336b57092741d4387feea8d60484be10c0fef7c2af61c65f1" => :mavericks
end
depends_on "liblo"
def install
inreplace "wscript", "-Werror", ""
system "./waf", "configure", "--prefix=#{prefix}"
system "./waf", "build"
system "./waf", "install"
end
end
| 37.16 | 92 | 0.76211 |
d588720155da4bc3407d0cb9c8cd5fc999468a9d | 1,613 | # frozen_string_literal: true
# encoding: utf-8
module Seorel
module Model
module InstanceMethods
def seorel?
try(:seorel).present?
end
def seorel_changed_mode?
::Seorel.config.store_seorel_if.eql?(:changed)
end
def should_update_seo_title?
seorel_changed_mode? || !seo_title?
end
def should_update_seo_description?
seorel_changed_mode? || !seo_description?
end
def should_update_seo_image?
seorel_changed_mode? || !seo_image?
end
def set_seorel
build_seorel unless seorel?
seorel.title = seorel_title_value if should_update_seo_title?
seorel.description = seorel_description_value if should_update_seo_description?
seorel.image = seorel_image_value if should_update_seo_image?
end
def seorel_title_value
raw_title = self.class.seorel_title_field && send(self.class.seorel_title_field)
::ActionController::Base.helpers.strip_tags(raw_title.to_s).first(255)
end
def seorel_description_value
raw_description = self.class.seorel_description_field && send(self.class.seorel_description_field)
::ActionController::Base.helpers.strip_tags(raw_description.to_s).first(255)
end
def seorel_image_value
raw_image = self.class.seorel_image_field && send(self.class.seorel_image_field)
::ActionController::Base.helpers.strip_tags(raw_image.to_s)
end
def seorel_default_value?
self.class.seorel_base_field.present?
end
end
end
end
| 28.803571 | 106 | 0.688779 |
e2f371a453a271d6961792c4d975873acad60486 | 598 | Pod::Spec.new do |s|
s.name = 'XMCommon'
s.version = '0.1.1'
s.license = 'MIT'
s.summary = 'extension class.'
s.description = %{XMCommon is a extension Class.}
s.homepage = 'https://github.com/rgshio/XMCommon'
s.author = { 'rgshio' => '[email protected]' }
s.source = { :git => 'https://github.com/rgshio/XMCommon.git', :tag => "v#{s.version}" }
s.source_files = 'Classes/XMExtension/*.{h,m}'
s.frameworks = 'Foundation', 'UIKit', 'CommonCrypto'
s.ios.deployment_target = '7.0' # minimum SDK with autolayout
s.requires_arc = true
end
| 31.473684 | 96 | 0.600334 |
38234dff872e139be706ce430ee36572422a26e2 | 978 | Pod::Spec.new do |s|
s.name = 'ksyhttpcache'
s.version = '1.2.4'
s.license = {
:type => 'Proprietary',
:text => <<-LICENSE
Copyright 2015 kingsoft Ltd. All rights reserved.
LICENSE
}
s.homepage = 'https://github.com/ksvc/ksyhttpcache_ios'
s.authors = { 'ksyun' => '[email protected]' }
s.summary = 'KSYHTTPCache 金山云iOS平台http缓存SDK.'
s.description = <<-DESC
* 金山云ios平台http缓存SDK,可方便地与播放器集成,实现http视频边播放边下载(缓存)功能。
* ksyun http cache sdk for ios platform, it's easy to integrated with media players to provide caching capability when watching http videos.
DESC
s.platform = :ios, '7.0'
s.ios.deployment_target = '7.0'
s.requires_arc = true
s.source = {
:git => 'https://github.com/ksvc/ksyhttpcache_ios.git',
:tag => 'v'+s.version.to_s
}
s.dependency 'CocoaAsyncSocket'
s.dependency 'CocoaLumberjack'
s.vendored_frameworks = 'framework/KSYHTTPCache.framework'
end
| 33.724138 | 146 | 0.654397 |
7acf056d6d0f5434a3d93602357ce40d1199eac2 | 5,080 | Shindo.tests('Fog::AWS[:dynamodb] | item requests', ['aws']) do
@table_name = "fog_table_#{Time.now.to_f.to_s.gsub('.','')}"
unless Fog.mocking?
Fog::AWS[:dynamodb].create_table(
@table_name,
{'HashKeyElement' => {'AttributeName' => 'key', 'AttributeType' => 'S'}},
{'ReadCapacityUnits' => 5, 'WriteCapacityUnits' => 5}
)
Fog.wait_for { Fog::AWS[:dynamodb].describe_table(@table_name).body['Table']['TableStatus'] == 'ACTIVE' }
end
tests('success') do
tests("#put_item('#{@table_name}', {'key' => {'S' => 'key'}}, {'value' => {'S' => 'value'}})").formats('ConsumedCapacityUnits' => Float) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].put_item(@table_name, {'key' => {'S' => 'key'}}, {'value' => {'S' => 'value'}}).body
end
tests("#update_item('#{@table_name}', {'HashKeyElement' => {'S' => 'key'}}, {'value' => {'Value' => {'S' => 'value'}}})").formats('ConsumedCapacityUnits' => Float) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].update_item(@table_name, {'HashKeyElement' => {'S' => 'key'}}, {'value' => {'Value' => {'S' => 'value'}}}).body
end
@batch_get_item_format = {
'Responses' => {
@table_name => {
'ConsumedCapacityUnits' => Float,
'Items' => [{
'key' => { 'S' => String },
'value' => { 'S' => String }
}]
}
},
'UnprocessedKeys' => {}
}
tests("#batch_get_item({'#{@table_name}' => {'Keys' => [{'HashKeyElement' => {'S' => 'key'}}]}})").formats(@batch_get_item_format) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].batch_get_item(
{@table_name => {'Keys' => [{'HashKeyElement' => {'S' => 'key'}}]}}
).body
end
@batch_put_item_format = {
'Responses'=> {
@table_name => {
'ConsumedCapacityUnits' => Float}
},
'UnprocessedItems'=> {}
}
tests("#batch_put_item({ '#{@table_name}' => [{ 'PutRequest' => { 'Item' =>
{ 'HashKeyElement' => { 'S' => 'key' }, 'RangeKeyElement' => { 'S' => 'key' }}}}]})"
).formats(@batch_put_item_format) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].batch_put_item(
{@table_name => [{'PutRequest'=> {'Item'=>
{'HashKeyElement' => { 'S' => 'key' },
'RangeKeyElement' => { 'S' => 'key' }
}}}]}
).body
end
@get_item_format = {
'ConsumedCapacityUnits' => Float,
'Item' => {
'key' => { 'S' => String },
'value' => { 'S' => String }
}
}
tests("#get_item('#{@table_name}', {'HashKeyElement' => {'S' => 'key'}})").formats(@get_item_format) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].get_item(@table_name, {'HashKeyElement' => {'S' => 'key'}}).body
end
tests("#get_item('#{@table_name}', {'HashKeyElement' => {'S' => 'notakey'}})").formats('ConsumedCapacityUnits' => Float) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].get_item(@table_name, {'HashKeyElement' => {'S' => 'notakey'}}).body
end
@query_format = {
'ConsumedCapacityUnits' => Float,
'Count' => Integer,
'Items' => [{
'key' => { 'S' => String },
'value' => { 'S' => String }
}],
'LastEvaluatedKey' => NilClass
}
tests("#query('#{@table_name}', {'S' => 'key'}").formats(@query_format) do
pending if Fog.mocking?
pending # requires a table with range key
Fog::AWS[:dynamodb].query(@table_name, {'S' => 'key'}).body
end
@scan_format = @query_format.merge('ScannedCount' => Integer)
tests("scan('#{@table_name}')").formats(@scan_format) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].scan(@table_name).body
end
tests("#delete_item('#{@table_name}', {'HashKeyElement' => {'S' => 'key'}})").formats('ConsumedCapacityUnits' => Float) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].delete_item(@table_name, {'HashKeyElement' => {'S' => 'key'}}).body
end
tests("#delete_item('#{@table_name}, {'HashKeyElement' => {'S' => 'key'}})").formats('ConsumedCapacityUnits' => Float) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].delete_item(@table_name, {'HashKeyElement' => {'S' => 'key'}}).body
end
end
tests('failure') do
tests("#put_item('notatable', {'key' => {'S' => 'key'}}, {'value' => {'S' => 'value'}})").raises(Excon::Errors::BadRequest) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].put_item('notatable', {'key' => {'S' => 'key'}}, {'value' => {'S' => 'value'}})
end
tests("#update_item('notatable', {'HashKeyElement' => {'S' => 'key'}}, {'value' => {'Value' => {'S' => 'value'}}})").raises(Excon::Errors::BadRequest) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].update_item('notatable', {'HashKeyElement' => {'S' => 'key'}}, {'value' => {'Value' => {'S' => 'value'}}})
end
end
unless Fog.mocking?
Fog::AWS[:dynamodb].delete_table(@table_name)
end
end
| 36.811594 | 170 | 0.529134 |
d50564d8923790bf4da5d45a637e2ffa3a9e0259 | 186 | class ApplicationController < ActionController::Base
before_action :force_sso_user
after_action :verify_authorized, except: [:index, :who_impersonate, :impersonate, :shibboleth]
end
| 37.2 | 96 | 0.817204 |
0170df719d7d64475f055f5df8d6747a9fdb0724 | 781 | cask 'font-monoid-halftight-xtrasmall-dollar-nocalt' do
version :latest
sha256 :no_check
# github.com/larsenwork/monoid was verified as official when first introduced to the cask
url 'https://github.com/larsenwork/monoid/blob/release/Monoid-HalfTight-XtraSmall-Dollar-NoCalt.zip?raw=true'
name 'Monoid-HalfTight-XtraSmall-Dollar-NoCalt'
homepage 'http://larsenwork.com/monoid/'
font 'Monoid-Bold-HalfTight-XtraSmall-Dollar-NoCalt.ttf'
font 'Monoid-Italic-HalfTight-XtraSmall-Dollar-NoCalt.ttf'
font 'Monoid-Regular-HalfTight-XtraSmall-Dollar-NoCalt.ttf'
font 'Monoid-Retina-HalfTight-XtraSmall-Dollar-NoCalt.ttf'
caveats <<~EOS
#{token} is dual licensed with MIT and OFL licenses.
https://github.com/larsenwork/monoid/tree/master#license
EOS
end
| 39.05 | 111 | 0.775928 |
5d4644202ac860220f2d1cd209e8a415a5e70db3 | 2,708 | #--
# Copyright (c) 2006-2009, John Mettraux, [email protected]
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# Made in Japan.
#++
require 'logger'
require 'openwfe/utils'
module OpenWFE
#
# A Mixin for adding logging method to any class
#
module Logging
def ldebug (message=nil, &block)
do_log(:debug, message, &block)
end
def linfo (message=nil, &block)
do_log(:info, message, &block)
end
def lwarn (message=nil, &block)
do_log(:warn, message, &block)
end
def lerror (message=nil, &block)
do_log(:error, message, &block)
end
def lfatal (message=nil, &block)
do_log(:fatal, message, &block)
end
def lunknown (message=nil, &block)
do_log(:unknown, message, &block)
end
def llog (level, message=nil, &block)
do_log(level, message, &block)
end
#
# A simplification of caller_to_s for direct usage when debugging
#
def ldebug_callstack (msg, max_lines=nil)
ldebug { "#{msg}\n" + OpenWFE::caller_to_s(9, max_lines) }
end
private
def do_log (level, message, &block)
return unless $OWFE_LOG
logblock = lambda do
if block
"#{log_prepare(message)} - #{block.call}"
else
"#{log_prepare(message)}"
end
end
$OWFE_LOG.send level, &logblock
end
def log_prepare (message)
return log_author() unless message
"#{log_author} - #{message}"
end
def log_author
if respond_to?(:service_name)
"#{self.class} '#{self.service_name}'"
else
"#{self.class}"
end
end
end
end
| 24.844037 | 79 | 0.656942 |
bfa2aaaa833b01402754303e3d475f9b4a1e44b1 | 313 | # Class of an Hervester or WSDL files
Class WSDLHervester
# method used for initialization of an class
def initialize
end
# method used for download of an wsdl file
def downloader(file_location)
end
# method used to parse wsdl file
def parser
end
# method used to display
def method_name
end
end | 12.52 | 44 | 0.757188 |
e9ee98a128041f4ba6c8ef0e07cff789fce9a559 | 4,727 | require 'active_support/core_ext/object/duplicable'
require 'active_support/core_ext/string/inflections'
module ActiveSupport
module Cache
module Strategy
# Caches that implement LocalCache will be backed by an in-memory cache for the
# duration of a block. Repeated calls to the cache for the same key will hit the
# in-memory cache for faster access.
module LocalCache
autoload :Middleware, 'active_support/cache/strategy/local_cache_middleware'
# Class for storing and registering the local caches.
class LocalCacheRegistry # :nodoc:
extend ActiveSupport::PerThreadRegistry
def initialize
@registry = {}
end
def cache_for(local_cache_key)
@registry[local_cache_key]
end
def set_cache_for(local_cache_key, value)
@registry[local_cache_key] = value
end
def self.set_cache_for(l, v); instance.set_cache_for l, v; end
def self.cache_for(l); instance.cache_for l; end
end
# Simple memory backed cache. This cache is not thread safe and is intended only
# for serving as a temporary memory cache for a single thread.
class LocalStore < Store
def initialize
super
@data = {}
end
# Don't allow synchronizing since it isn't thread safe,
def synchronize # :nodoc:
yield
end
def clear(options = nil)
@data.clear
end
def read_entry(key, options)
@data[key]
end
def write_entry(key, value, options)
@data[key] = value
true
end
def delete_entry(key, options)
[email protected](key)
end
end
# Use a local cache for the duration of block.
def with_local_cache
use_temporary_local_cache(LocalStore.new) { yield }
end
# Middleware class can be inserted as a Rack handler to be local cache for the
# duration of request.
def middleware
@middleware ||= Middleware.new(
"ActiveSupport::Cache::Strategy::LocalCache",
local_cache_key)
end
def clear(options = nil) # :nodoc:
local_cache.clear(options) if local_cache
super
end
def cleanup(options = nil) # :nodoc:
local_cache.clear(options) if local_cache
super
end
def increment(name, amount = 1, options = nil) # :nodoc:
value = bypass_local_cache{super}
set_cache_value(value, name, amount, options)
value
end
def decrement(name, amount = 1, options = nil) # :nodoc:
value = bypass_local_cache{super}
set_cache_value(value, name, amount, options)
value
end
protected
def read_entry(key, options) # :nodoc:
if local_cache
entry = local_cache.read_entry(key, options)
unless entry
entry = super
local_cache.write_entry(key, entry, options)
end
entry
else
super
end
end
def write_entry(key, entry, options) # :nodoc:
local_cache.write_entry(key, entry, options) if local_cache
super
end
def delete_entry(key, options) # :nodoc:
local_cache.delete_entry(key, options) if local_cache
super
end
def set_cache_value(value, name, amount, options)
if local_cache
local_cache.mute do
if value
local_cache.write(name, value, options)
else
local_cache.delete(name, options)
end
end
end
end
private
def local_cache_key
@local_cache_key ||= "#{self.class.name.underscore}_local_cache_#{object_id}".gsub(/[\/-]/, '_').to_sym
end
def local_cache
LocalCacheRegistry.cache_for(local_cache_key)
end
def bypass_local_cache
use_temporary_local_cache(nil) { yield }
end
def use_temporary_local_cache(temporary_cache)
save_cache = LocalCacheRegistry.cache_for(local_cache_key)
begin
LocalCacheRegistry.set_cache_for(local_cache_key, temporary_cache)
yield
ensure
LocalCacheRegistry.set_cache_for(local_cache_key, save_cache)
end
end
end
end
end
end
| 29.360248 | 115 | 0.566744 |
87544b9c9426cd06cac9f4a9e4ac2d0a9d96a09e | 2,010 | 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.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# 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
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
config.action_cable.allowed_request_origins = [
'http://localhost:63342'
]
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
# 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
end
| 35.892857 | 87 | 0.756219 |
e8b0020d7539ff77fbc7bfee73d3a24d4f8f730f | 1,434 | FactoryGirl.define do
factory :user do
password Devise.friendly_token[0, 20]
email '[email protected]'
name 'erikdstock'
after(:create) do |user, _evaluator|
create(:authentication, user: user)
end
# after(:build) { |u| u.class.skip_callback(:create, :after, :queue_initial_refresh) }
# Create a user with only 5 plays so far. At the end of this month
# (may 2016) it should be 12 plays.
factory :user_with_stats do
after(:create) do |user, _evaluator|
artist = create :artist, name: 'MisterWives'
create(:monthly_top_artist, artist: artist, play_count: 5, user: user, month: 1.month.ago)
end
end
end
# # user_with_posts will create post data after the user has been created
# factory :user_with_stats do
# # posts_count is declared as a transient attribute and available in
# # attributes on the factory, as well as the callback via the evaluator
# transient do
# posts_count 5
# end
#
# # the after(:create) yields two values; the user instance itself and the
# # evaluator, which stores all values from the factory, including transient
# # attributes; `create_list`'s second argument is the number of records
# # to create and we make sure the user is associated properly to the post
# after(:create) do |user, evaluator|
# create_list(:post, evaluator.posts_count, user: user)
# end
# end
end
| 36.769231 | 98 | 0.681311 |
388da4a1007888aa17f42c804ee3dd3af0e380ae | 1,555 | module Vodka
class Configuration
attr_accessor :request_secret, # Secret token to use in signing requests, stronger is better
:response_secret, # Secret token to use in signing responses, stronger is better
:digest, # Digest algorithm to use in signing process
:perform_request_signing, # If the value is set to false no signing middlewares will be injected
:her_auto_configure, # Configure Her automatically
:api_url, # REST API endpoint passed to Her
:prefix # Almost the same thing, path prefix for server
def initialize
@digest = Digest::SHA512
@perform_request_signing = true
@her_auto_configure = true
end
def configure_her!
raise Exception.new('api_url must be set') if api_url.nil?
::Her::API.setup(url: api_url) do |c|
c.use(Vodka::Client::Middleware::ErrorAware)
c.use(Vodka::Client::Middleware::SignedRequest) if perform_request_signing
c.use(Faraday::Request::UrlEncoded)
c.use(Vodka::Client::Middleware::SignedResponse) if perform_request_signing
c.use(::Her::Middleware::SecondLevelParseJSON)
c.use(Faraday::Adapter::NetHttp)
end
end
end
module Configurable
def config
@config ||= Configuration.new
end
def configure
yield config if block_given?
config.configure_her! if config.her_auto_configure
end
end
end
| 37.02381 | 114 | 0.630868 |
ed603cdb3ac8a74f4faba5aa171d16b9b06cb20c | 5,009 | =begin
PureCloud Platform API
With the PureCloud Platform API, you can control all aspects of your PureCloud environment. With the APIs you can access the system configuration, manage conversations and more.
OpenAPI spec version: v2
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
License: UNLICENSED
https://help.mypurecloud.com/articles/terms-and-conditions/
Terms of Service: https://help.mypurecloud.com/articles/terms-and-conditions/
=end
require 'date'
module PureCloud
class SetWrapperDayOfWeek
attr_accessor :values
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'values' => :'values'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'values' => :'Array<String>'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v}
if attributes.has_key?(:'values')
if (value = attributes[:'values']).is_a?(Array)
self.values = value
end
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properies with the reasons
def list_invalid_properties
invalid_properties = Array.new
return invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
values == o.values
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[values].hash
end
# build the object from hash
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
else
#TODO show warning in debug mode
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
else
# data not found in attributes(hash), not an issue as the data can be optional
end
end
self
end
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /^(true|t|yes|y|1)$/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
_model = Object.const_get("PureCloud").const_get(type).new
_model.build_from_hash(value)
end
end
def to_s
to_hash.to_s
end
# to_body is an alias to to_body (backward compatibility))
def to_body
to_hash
end
# return the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Method to output non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
def _to_hash(value)
if value.is_a?(Array)
value.compact.map{ |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 24.553922 | 177 | 0.593332 |
7a770da92eb1feb7dcf704c740c41612ab9a7de7 | 2,686 | require 'active_support/concern'
module KonoUtils::Concerns
module BaseModals
extend ActiveSupport::Concern
def create
authorize @obj if defined? Pundit
save_response
end
def destroy
authorize @obj if defined? Pundit
@obj.destroy
respond_to do |f|
f.json { render json: {success: true} }
end
end
def update
authorize @obj if defined? Pundit
@obj.assign_attributes(update_params)
save_response
end
included do
before_action :load_parent_assoc
before_action :load_obj, :only => [:destroy, :update]
private
##
# Metodo promemoria per caricare il modello padre
def load_parent_assoc
@parent_model = nil
raise 'Sovrascrivi funzione "load_parent_assoc" nei figli la definizione di questa variabile: @parent_model'
end
##
# Metodo promemoria per caricare l'oggetto dell'aggiornamento
# ES:
# @obj = @person.person_contacts.find(params[:id])
def load_obj
@obj=nil
raise 'Sovrascrivi funzione "load_obj" in figli la definizione di questa variabile: @obj'
end
##
# Metodo promemoria per pulire i parametri
# ES:
# params.require(:person_contact).permit(:contacttype_id, :contact)
def update_params
raise 'Sovrascrivi in figli'
end
def render_part_to_json(partial, locals, status=200)
render json: {
partial: (
render_to_string(
:partial => partial,
:layout => false, :locals => locals)
)
}, status: status
end
def save_response
raise "Sovrascrivere:
def save_response
respond_to do |f|
if @obj.valid?
@obj.save
f.json do
render_part_to_json('tikal_core/people/person_contacts/panel.html', {:contact => @obj})
end
else
f.json do
render_part_to_json('tikal_core/people/person_contacts/modal_form.html', {:contact => @obj, :id => ''}, 400)
end
end
end
end
ed aggiungere se non già fatto:
def create
@obj = @person.person_contacts.build(update_params)
super
end
def update_params
params.require(:person_contact).permit(:contacttype_id, :contact)
end
"
end
end
end
end | 27.690722 | 134 | 0.540208 |
e92f4a65989e35d36d03aff4ffd1ca9c91c8b2eb | 268 | class CreateStartupApplications < ActiveRecord::Migration[5.1]
def change
create_table :startup_applications do |t|
t.string :name
t.string :email
t.string :phone
t.text :idea
t.string :website
t.timestamps
end
end
end
| 19.142857 | 62 | 0.652985 |
0822de92dbe680919c922104181990457d2eb5e5 | 2,537 | require File.expand_path("../Abstract/abstract-osquery-formula", __FILE__)
class Thrift < AbstractOsqueryFormula
desc "Framework for scalable cross-language services development"
homepage "https://thrift.apache.org/"
license "Apache-2.0"
url "http://www-us.apache.org/dist/thrift/0.10.0/thrift-0.10.0.tar.gz"
sha256 "2289d02de6e8db04cbbabb921aeb62bfe3098c4c83f36eec6c31194301efa10b"
revision 101
bottle do
root_url "https://osquery-packages.s3.amazonaws.com/bottles"
cellar :any_skip_relocation
sha256 "f9bbba4aecd4de780e879dd71bcbd18e819ed8355e700177a543860120f4086b" => :sierra
sha256 "e818505723a34e425cd2e35acccd992f8f79287bfa77ec7bdda4e9df4083d5e2" => :x86_64_linux
end
depends_on "bison" => :build
depends_on "openssl"
patch :DATA
def install
ENV.cxx11
ENV["PY_PREFIX"] = prefix
ENV.append "CPPFLAGS", "-DOPENSSL_NO_SSL3"
exclusions = [
"--without-ruby",
"--disable-tests",
"--without-php_extension",
"--without-haskell",
"--without-java",
"--without-perl",
"--without-php",
"--without-erlang",
"--without-go",
"--without-qt",
"--without-qt4",
"--without-nodejs",
"--without-python",
"--with-cpp",
"--with-openssl=#{Formula["osquery/osquery-local/openssl"].prefix}"
]
ENV.prepend_path "PATH", Formula["bison"].bin
system "./bootstrap.sh" unless build.stable?
system "./configure", "--disable-debug",
"--prefix=#{prefix}",
"--libdir=#{lib}",
"--disable-shared",
"--enable-static",
*exclusions
system "make", "-j#{ENV.make_jobs}"
system "make", "install"
end
end
__END__
diff --git a/lib/cpp/src/thrift/transport/TServerSocket.cpp b/lib/cpp/src/thrift/transport/TServerSocket.cpp
index 87b6383..447c89d 100644
--- a/lib/cpp/src/thrift/transport/TServerSocket.cpp
+++ b/lib/cpp/src/thrift/transport/TServerSocket.cpp
@@ -584,6 +584,12 @@ shared_ptr<TTransport> TServerSocket::acceptImpl() {
// a certain number
continue;
}
+
+ // Special case because we expect setuid syscalls in other threads.
+ if (THRIFT_GET_SOCKET_ERROR == EINTR) {
+ continue;
+ }
+
int errno_copy = THRIFT_GET_SOCKET_ERROR;
GlobalOutput.perror("TServerSocket::acceptImpl() THRIFT_POLL() ", errno_copy);
throw TTransportException(TTransportException::UNKNOWN, "Unknown", errno_copy);
| 32.948052 | 108 | 0.644462 |
1cdb986ba0269d5d7248db65d260ef6c1f1eb644 | 3,975 | #-- encoding: UTF-8
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2021 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
# When included, it adds the ability to rebuild nested sets, thus fixing
# corrupted trees.
#
# AwesomeNestedSet has this functionality as well but it fixes the sets with
# running the callbacks defined in the model. This has two drawbacks:
#
# * It is prone to fail when a validation fails that has nothing to do with
# nested sets.
# * It is slow.
#
# The methods included are purely sql based. The code in here is partly copied
# over from awesome_nested_set's non sql methods.
module OpenProject::NestedSet::RebuildPatch
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
# Rebuilds the left & rights if unset or invalid. Also very useful for converting from acts_as_tree.
# Very similar to original nested_set implementation but uses update_all so that callbacks are not triggered
def rebuild_silently!(roots = nil)
# Don't rebuild a valid tree.
return true if valid?
scope = lambda { |_node| }
if acts_as_nested_set_options[:scope]
scope = lambda { |node|
scope_column_names.inject('') {|str, column_name|
str << "AND #{connection.quote_column_name(column_name)} = #{connection.quote(node.send(column_name.to_sym))} "
}
}
end
# setup index
indices = Hash.new do |h, k|
h[k] = 0
end
set_left_and_rights = lambda { |node|
# set left
node[left_column_name] = indices[scope.call(node)] += 1
# find
children = where(["#{quoted_parent_column_name} = ? #{scope.call(node)}", node])
.order([quoted_left_column_name,
quoted_right_column_name,
acts_as_nested_set_options[:order]].compact.join(', '))
children.each do |n| set_left_and_rights.call(n) end
# set right
node[right_column_name] = indices[scope.call(node)] += 1
changes = node.changes.inject({}) { |hash, (attribute, _values)|
hash[attribute] = node.send(attribute.to_s)
hash
}
where(id: node.id).update_all(changes) unless changes.empty?
}
# Find root node(s)
# or take provided
root_nodes = if roots.is_a? Array
roots
elsif roots.present?
[roots]
else
where("#{quoted_parent_column_name} IS NULL")
.order([quoted_left_column_name,
quoted_right_column_name,
acts_as_nested_set_options[:order]].compact.join(', '))
end
root_nodes.each do |root_node|
set_left_and_rights.call(root_node)
end
end
end
end
| 35.810811 | 123 | 0.653585 |
1cc5d3fe7645f37b045c1ab19eb3b061bad9d09c | 124 | require "immutablejs/rails/version"
module Immutablejs
module Rails
class Engine < ::Rails::Engine
end
end
end
| 13.777778 | 35 | 0.717742 |
e87bd78a3689d4c2130dfd34eec4a72322472e38 | 723 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'formtastic_i18n/version'
Gem::Specification.new do |spec|
spec.name = "formtastic_i18n"
spec.version = FormtasticI18n::VERSION
spec.authors = ["Timo Schilling"]
spec.email = ["[email protected]"]
spec.summary = "I18n translation for the formtastic gem"
spec.homepage = "https://github.com/timoschilling/formtastic_i18n"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
end
| 34.428571 | 73 | 0.662517 |
115e3b498c3170faed0e22874b4a5a43c7528032 | 337 | Rails.application.routes.draw do
mount Hyperstack::Engine => '/hyperstack' # this route should be first in the routes file so it always matches
get '/(*others)', to: 'hyperstack#App'
# get '/(*others)', to: 'hyperstack#app'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
| 48.142857 | 113 | 0.721068 |
b9b37c8885f7278b1566949ed21d4f2e2a33f9ff | 4,187 | module Oz
class CoreElement;
end
OzLoader.require_all('./elements')
class CoreElement
def self.type
:core_element
end
@@locator_options = [:id, :class, :xpath, :text, :href, :for, :name, :css, :index]
def self.locator_options
@@locator_options
end
attr_reader :name, :active, :locator_hash, :type
### Attrib Methods ###
def initialize(name, world, options)
@type = self.class.type
@name = :"#{name}_#{self.class.type}"
@locator_hash = options.select{|locator_type, _| @@locator_options.include? locator_type}
.map{|locator_type, value| [locator_type, value]}.to_h
raise "ELEMENT [#{name}] must have a locator!/nValid locators are: #{@@locator_options}" if @locator_hash.empty?
@world = world
@options = {:active => true}.merge(options)
@active = @options[:active]
@clear = @options[:clear] ? true : false
assign_element_type
end
def browser
@world.browser
end
def parent
@options[:parent] ? @options[:parent].watir_element : browser
end
def watir_element
@watir_element ||= parent.send(@element_type, @locator_hash)
end
def assign_element_type
@element_type = @options[:element_type] ? @options[:element_type] : :div
end
### Behavioral Methods ###
def click
assert_active
@world.logger.action "Clicking [#{@name}]"
begin
watir_element.click
rescue Selenium::WebDriver::Error::UnknownError => e
raise e unless e.message =~ /Element is not clickable at point .* Other element would receive the click/
@world.logger.warn 'Click failed, assuming it was due to animations on the page. Trying again...'
raise "Click kept failing! Original Error: \n#{e}" unless CoreUtils.wait_safely(3){ watir_element.click }
rescue Errno::ECONNREFUSED => e
raise e
end
@on_click.call if @on_click
end
def on_click(&block)
@on_click = block
end
def hover
assert_active
@world.logger.action "Hovering over [#{@name}]"
begin
watir_element.hover
rescue Watir::Exception::UnknownObjectException => e
@world.logger.warn 'Unable to hover over element, attempting to proceed anyway...'
return false
end
@on_hover.call if @on_hover
end
def on_hover(&block)
@on_hover = block
end
def fill(data)
@on_fill.call if @on_fill
end
def on_fill(&block)
@on_fill = block
end
def visible?
@world.logger.warn '[OZ DEPRECATION] Checking `#visisble?` is deprecated. Use `#present?` instead.'
present?
end
def present?
begin
watir_element.wait_until(timeout:0, &:present?)
return true
rescue Watir::Wait::TimeoutError => e
return false
end
end
def flash
return unless @world.configuration['FLASH_VALIDATION']
assert_active
watir_element.flash
end
def value
assert_active
return nil unless present?
watir_element.text
end
def attribute_value(attribute_name)
watir_element.attribute_value(attribute_name)
end
def assert_active
raise "ERROR: Element [#{@name}] being accessed when not active!!\n" unless @active
end
def activate
@active = true
end
def deactivate
@active = false
end
def active?
@active
end
def activate_if(condition)
condition ? activate : deactivate
end
def validate(data)
status = active ? 'is' : 'is not'
validation_point = @world.validation_engine.add_validation_point("Checking that [#{@name}] #{status} displayed...")
if active == present?
validation_point.pass
flash if active
elsif !active && present?
validation_point.fail(" [#{@name}] was found on the page!\n FOUND: #{@name}\n EXPECTED: Element should not be displayed!")
else
validation_point.fail(" [#{@name}] was not found on the page!\n FOUND: None\n EXPECTED: #{@name} should be displayed!")
end
end
end
end | 25.845679 | 140 | 0.624313 |
91e436f445cc737c307d1455f13ecc5fd8a3e486 | 3,141 | require 'fog/core/collection'
require 'fog/rackspace/models/compute_v2/server'
module Fog
module Compute
class RackspaceV2
class Servers < Fog::Collection
model Fog::Compute::RackspaceV2::Server
# Returns list of servers
# @return [Fog::Compute::RackspaceV2::Servers] Retrieves a list servers.
# @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404
# @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400
# @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500
# @raise [Fog::Compute::RackspaceV2::ServiceError]
# @note Fog's current implementation only returns 1000 servers
# @note The filter parameter on the method is just to maintain compatability with other providers that support filtering.
# @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Servers-d1e2078.html
def all(filters = {})
data = service.list_servers.body['servers']
load(data)
end
# Creates a new server and populates ssh keys
# @return [Fog::Compute::RackspaceV2::Server]
# @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404
# @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400
# @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500
# @raise [Fog::Compute::RackspaceV2::ServiceError]
# @note This method is incompatible with Cloud Servers utlizing RackConnect. RackConnect users
# should use server personalization to install keys. Please see Server#personality for more information.
# @example
# service.servers.bootstrap :name => 'bootstrap-server',
# :flavor_id => service.flavors.first.id,
# :image_id => service.images.find {|img| img.name =~ /Ubuntu/}.id,
# :public_key_path => '~/.ssh/fog_rsa.pub',
# :private_key_path => '~/.ssh/fog_rsa'
#
# @raise [Fog::Compute::RackspaceV2::InvalidServerStateException] if server state is an error state
def bootstrap(new_attributes = {})
server = create(new_attributes)
server.wait_for(1500) { ready? && !public_ip_address.empty? }
server.setup(:password => server.password)
server
end
# Retrieves server
# @param [String] server_id for server to be returned
# @return [Fog::Compute::RackspaceV2:Server]
# @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404
# @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400
# @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500
# @raise [Fog::Compute::RackspaceV2::ServiceError]
# @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Get_Server_Details-d1e2623.html
def get(server_id)
data = service.get_server(server_id).body['server']
new(data)
rescue Fog::Compute::RackspaceV2::NotFound
nil
end
end
end
end
end
| 46.880597 | 129 | 0.622732 |
e2e44b86748acef1f43cd5a0238bbf19a0530943 | 5,065 | #!/opt/puppetlabs/puppet/bin/ruby
require 'json'
require 'puppet'
def budgets_create_or_update_by_resource_group_name(*args)
header_params = {}
argstring = args[0].delete('\\')
arg_hash = JSON.parse(argstring)
# Remove task name from arguments - should contain all necessary parameters for URI
arg_hash.delete('_task')
operation_verb = 'Put'
query_params, body_params, path_params = format_params(arg_hash)
uri_string = "https://management.azure.com//subscriptions/%{subscription_id}/resourceGroups/%{resource_group_name}/providers/Microsoft.Consumption/budgets/%{budget_name}" % path_params
unless query_params.empty?
uri_string = uri_string + '?' + to_query(query_params)
end
header_params['Content-Type'] = 'application/json' # first of #{parent_consumes}
return nil unless authenticate(header_params) == true
uri = URI(uri_string)
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
if operation_verb == 'Get'
req = Net::HTTP::Get.new(uri)
elsif operation_verb == 'Put'
req = Net::HTTP::Put.new(uri)
elsif operation_verb == 'Delete'
req = Net::HTTP::Delete.new(uri)
end
header_params.each { |x, v| req[x] = v } unless header_params.empty?
unless body_params.empty?
req.body=body_params.to_json
end
Puppet.debug("URI is (#{operation_verb}) #{uri} headers are #{header_params}")
response = http.request req # Net::HTTPResponse object
Puppet.debug("Called (#{operation_verb}) endpoint at #{uri}")
Puppet.debug("response code is #{response.code} and body is #{response.body}")
response
end
end
def to_query(hash)
if hash
return_value = hash.map { |x, v| "#{x}=#{v}" }.reduce { |x, v| "#{x}&#{v}" }
if !return_value.nil?
return return_value
end
end
return ''
end
def op_param(name, inquery, paramalias, namesnake)
operation_param = { :name => name, :location => inquery, :paramalias => paramalias, :namesnake => namesnake }
return operation_param
end
def format_params(key_values)
query_params = {}
body_params = {}
path_params = {}
key_values.each do |key,value|
if value.include? '{'
key_values[key]=JSON.parse(value.gsub("\'","\""))
end
end
op_params = [
op_param('api-version', 'query', 'api_version', 'api_version'),
op_param('budgetName', 'path', 'budget_name', 'budget_name'),
op_param('error', 'body', 'error', 'error'),
op_param('parameters', 'body', 'parameters', 'parameters'),
op_param('resourceGroupName', 'path', 'resource_group_name', 'resource_group_name'),
op_param('subscriptionId', 'path', 'subscription_id', 'subscription_id'),
]
op_params.each do |i|
location = i[:location]
name = i[:name]
paramalias = i[:paramalias]
name_snake = i[:namesnake]
if location == 'query'
query_params[name] = key_values[name_snake] unless key_values[name_snake].nil?
query_params[name] = ENV["azure__#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil?
elsif location == 'body'
body_params[name] = key_values[name_snake] unless key_values[name_snake].nil?
body_params[name] = ENV["azure_#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil?
else
path_params[name_snake.to_sym] = key_values[name_snake] unless key_values[name_snake].nil?
path_params[name_snake.to_sym] = ENV["azure__#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil?
end
end
return query_params,body_params,path_params
end
def fetch_oauth2_token
Puppet.debug('Getting oauth2 token')
@client_id = ENV['azure_client_id']
@client_secret = ENV['azure_client_secret']
@tenant_id = ENV['azure_tenant_id']
uri = URI("https://login.microsoftonline.com/#{@tenant_id}/oauth2/token")
response = Net::HTTP.post_form(uri,
'grant_type' => 'client_credentials',
'client_id' => @client_id,
'client_secret' => @client_secret,
'resource' => 'https://management.azure.com/')
Puppet.debug("get oauth2 token response code is #{response.code} and body is #{response.body}")
success = response.is_a? Net::HTTPSuccess
if success
return JSON[response.body]["access_token"]
else
raise Puppet::Error, "Unable to get oauth2 token - response is #{response} and body is #{response.body}"
end
end
def authenticate(header_params)
token = fetch_oauth2_token
if token
header_params['Authorization'] = "Bearer #{token}"
return true
else
return false
end
end
def task
# Get operation parameters from an input JSON
params = STDIN.read
result = budgets_create_or_update_by_resource_group_name(params)
if result.is_a? Net::HTTPSuccess
puts result.body
else
raise result.body
end
rescue StandardError => e
result = {}
result[:_error] = {
msg: e.message,
kind: 'puppetlabs-azure_arm/error',
details: { class: e.class.to_s },
}
puts result
exit 1
end
task | 32.467949 | 186 | 0.669497 |
1df7c4b4d1d1f5fdadea9f8be293b0d1cda0cecd | 1,493 | module DataMapper
# Tracks objects to help ensure that each object gets loaded only once.
# See: http://www.martinfowler.com/eaaCatalog/identityMap.html
class IdentityMap
# Get a resource from the IdentityMap
def get(key)
raise ArgumentError, "+key+ is not an Array, but was #{key.class}" unless Array === key
@cache[key]
end
alias [] get
# Add a resource to the IdentityMap
def set(key, resource)
raise ArgumentError, "+key+ is not an Array, but was #{key.class}" unless Array === key
raise ArgumentError, "+resource+ should be a DataMapper::Resource, but was #{resource.class}" unless Resource === resource
@second_level_cache.set(key, resource) if @second_level_cache
@cache[key] = resource
end
alias []= set
# Remove a resource from the IdentityMap
def delete(key)
raise ArgumentError, "+key+ is not an Array, but was #{key.class}" unless Array === key
@second_level_cache.delete(key) if @second_level_cache
@cache.delete(key)
end
private
def initialize(second_level_cache = nil)
@cache = if @second_level_cache = second_level_cache
Hash.new { |h,key| h[key] = @second_level_cache.get(key) }
else
Hash.new
end
end
def cache
@cache
end
def method_missing(method, *args, &block)
cache.__send__(method, *args, &block)
end
end # class IdentityMap
end # module DataMapper
| 28.169811 | 128 | 0.64568 |
187db146525c84ee269737c8db62842b7ef68b9a | 1,297 | module HealthSeven::V2_6
class Fhs < ::HealthSeven::Segment
# File Field Separator
attribute :file_field_separator, St, position: "FHS.1", require: true
# File Encoding Characters
attribute :file_encoding_characters, St, position: "FHS.2", require: true
# File Sending Application
attribute :file_sending_application, Hd, position: "FHS.3"
# File Sending Facility
attribute :file_sending_facility, Hd, position: "FHS.4"
# File Receiving Application
attribute :file_receiving_application, Hd, position: "FHS.5"
# File Receiving Facility
attribute :file_receiving_facility, Hd, position: "FHS.6"
# File Creation Date/Time
attribute :file_creation_date_time, Dtm, position: "FHS.7"
# File Security
attribute :file_security, St, position: "FHS.8"
# File Name/ID
attribute :file_name_id, St, position: "FHS.9"
# File Header Comment
attribute :file_header_comment, St, position: "FHS.10"
# File Control ID
attribute :file_control_id, St, position: "FHS.11"
# Reference File Control ID
attribute :reference_file_control_id, St, position: "FHS.12"
# File Sending Network Address
attribute :file_sending_network_address, Hd, position: "FHS.13"
# File Receiving Network Address
attribute :file_receiving_network_address, Hd, position: "FHS.14"
end
end | 40.53125 | 75 | 0.754048 |
abf79a7c9fbb108d97cdf26f997d6b7c3b8ae707 | 566 | require 'spec_helper'
def run_Candles
load(File.expand_path('../../Candles.rb', __FILE__))
end
describe "Candles" do
it "Sample case" do
allow(STDIN).to receive(:gets).and_return("4\n")
expect { run_Candles }.to output("45\n").to_stdout
end
it "Test case #1" do
allow(STDIN).to receive(:gets).and_return("0\n")
expect { run_Candles }.to output("9\n").to_stdout
end
it "Test case #2" do
allow(STDIN).to receive(:gets).and_return("1\n")
expect { run_Candles }.to output("18\n").to_stdout
end
end
# vim: set ts=2 sw=2 ai si et:
| 24.608696 | 54 | 0.659011 |
bb57bcc3089839bc89bbe597aadcd3123e17ee0f | 686 | require_relative "test_helper"
class BindingTest < StdlibTest
target Binding
using hook.refinement
def test_eval
binding.eval('1', '(eval)', 1)
end
def test_local_variable_defined?
binding.local_variable_defined?(:yes)
yes = true
binding.local_variable_defined?('yes')
end
def test_local_variable_get
foo = 1
binding.local_variable_get(:foo)
binding.local_variable_get('foo')
end
def test_local_variable_set
binding.local_variable_set(:foo, 1)
binding.local_variable_set('foo', 1)
end
def test_local_variables
foo = 1
binding.local_variables
end
def test_source_location
binding.source_location
end
end
| 18.540541 | 42 | 0.728863 |
62afa441d6275d733ba3f96632d1ab070ae64f38 | 56 | require 'zgomot/ui/output'
require 'zgomot/ui/windows'
| 14 | 27 | 0.767857 |
28460bc64d94c64e49e387f41328acea458d9359 | 977 | # encoding: utf-8
module Backup
module Configuration
module Database
class MySQL < Base
class << self
##
# Name of the database that needs to get dumped.
# To dump all databases, set this to `:all` or leave blank.
attr_accessor :name
##
# Credentials for the specified database
attr_accessor :username, :password
##
# Connectivity options
attr_accessor :host, :port, :socket
##
# Tables to skip while dumping the database
attr_accessor :skip_tables
##
# Tables to dump, tables that aren't specified won't get dumped
attr_accessor :only_tables
##
# Additional "mysqldump" options
attr_accessor :additional_options
##
# Path to mysqldump utility (optional)
attr_accessor :mysqldump_utility
end
end
end
end
end
| 22.72093 | 73 | 0.561924 |
620cb121d29d6436e8306fa5a8c049d192dafaae | 20,223 | =begin
#OpenAPI Petstore
#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
OpenAPI spec version: 1.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.0.0-SNAPSHOT
=end
require 'uri'
module Petstore
class PetApi
attr_accessor :api_client
def initialize(api_client = ApiClient.default)
@api_client = api_client
end
# Add a new pet to the store
# @param body Pet object that needs to be added to the store
# @param [Hash] opts the optional parameters
# @return [nil]
def add_pet(body, opts = {})
add_pet_with_http_info(body, opts)
nil
end
# Add a new pet to the store
# @param body Pet object that needs to be added to the store
# @param [Hash] opts the optional parameters
# @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers
def add_pet_with_http_info(body, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PetApi.add_pet ...'
end
# verify the required parameter 'body' is set
if @api_client.config.client_side_validation && body.nil?
fail ArgumentError, "Missing the required parameter 'body' when calling PetApi.add_pet"
end
# resource path
local_var_path = '/pet'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(body)
auth_names = ['petstore_auth']
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PetApi#add_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Deletes a pet
# @param pet_id Pet id to delete
# @param [Hash] opts the optional parameters
# @option opts [String] :api_key
# @return [nil]
def delete_pet(pet_id, opts = {})
delete_pet_with_http_info(pet_id, opts)
nil
end
# Deletes a pet
# @param pet_id Pet id to delete
# @param [Hash] opts the optional parameters
# @option opts [String] :api_key
# @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers
def delete_pet_with_http_info(pet_id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PetApi.delete_pet ...'
end
# verify the required parameter 'pet_id' is set
if @api_client.config.client_side_validation && pet_id.nil?
fail ArgumentError, "Missing the required parameter 'pet_id' when calling PetApi.delete_pet"
end
# resource path
local_var_path = '/pet/{petId}'.sub('{' + 'petId' + '}', pet_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
header_params[:'api_key'] = opts[:'api_key'] if !opts[:'api_key'].nil?
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
data, status_code, headers = @api_client.call_api(:DELETE, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PetApi#delete_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Finds Pets by status
# Multiple status values can be provided with comma separated strings
# @param status Status values that need to be considered for filter
# @param [Hash] opts the optional parameters
# @return [Array<Pet>]
def find_pets_by_status(status, opts = {})
data, _status_code, _headers = find_pets_by_status_with_http_info(status, opts)
data
end
# Finds Pets by status
# Multiple status values can be provided with comma separated strings
# @param status Status values that need to be considered for filter
# @param [Hash] opts the optional parameters
# @return [Array<(Array<Pet>, Fixnum, Hash)>] Array<Pet> data, response status code and response headers
def find_pets_by_status_with_http_info(status, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PetApi.find_pets_by_status ...'
end
# verify the required parameter 'status' is set
if @api_client.config.client_side_validation && status.nil?
fail ArgumentError, "Missing the required parameter 'status' when calling PetApi.find_pets_by_status"
end
# resource path
local_var_path = '/pet/findByStatus'
# query parameters
query_params = {}
query_params[:'status'] = @api_client.build_collection_param(status, :csv)
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Array<Pet>')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PetApi#find_pets_by_status\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Finds Pets by tags
# Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
# @param tags Tags to filter by
# @param [Hash] opts the optional parameters
# @return [Array<Pet>]
def find_pets_by_tags(tags, opts = {})
data, _status_code, _headers = find_pets_by_tags_with_http_info(tags, opts)
data
end
# Finds Pets by tags
# Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
# @param tags Tags to filter by
# @param [Hash] opts the optional parameters
# @return [Array<(Array<Pet>, Fixnum, Hash)>] Array<Pet> data, response status code and response headers
def find_pets_by_tags_with_http_info(tags, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PetApi.find_pets_by_tags ...'
end
# verify the required parameter 'tags' is set
if @api_client.config.client_side_validation && tags.nil?
fail ArgumentError, "Missing the required parameter 'tags' when calling PetApi.find_pets_by_tags"
end
# resource path
local_var_path = '/pet/findByTags'
# query parameters
query_params = {}
query_params[:'tags'] = @api_client.build_collection_param(tags, :csv)
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Array<Pet>')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PetApi#find_pets_by_tags\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Find pet by ID
# Returns a single pet
# @param pet_id ID of pet to return
# @param [Hash] opts the optional parameters
# @return [Pet]
def get_pet_by_id(pet_id, opts = {})
data, _status_code, _headers = get_pet_by_id_with_http_info(pet_id, opts)
data
end
# Find pet by ID
# Returns a single pet
# @param pet_id ID of pet to return
# @param [Hash] opts the optional parameters
# @return [Array<(Pet, Fixnum, Hash)>] Pet data, response status code and response headers
def get_pet_by_id_with_http_info(pet_id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PetApi.get_pet_by_id ...'
end
# verify the required parameter 'pet_id' is set
if @api_client.config.client_side_validation && pet_id.nil?
fail ArgumentError, "Missing the required parameter 'pet_id' when calling PetApi.get_pet_by_id"
end
# resource path
local_var_path = '/pet/{petId}'.sub('{' + 'petId' + '}', pet_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['api_key']
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Pet')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PetApi#get_pet_by_id\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Update an existing pet
# @param body Pet object that needs to be added to the store
# @param [Hash] opts the optional parameters
# @return [nil]
def update_pet(body, opts = {})
update_pet_with_http_info(body, opts)
nil
end
# Update an existing pet
# @param body Pet object that needs to be added to the store
# @param [Hash] opts the optional parameters
# @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers
def update_pet_with_http_info(body, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PetApi.update_pet ...'
end
# verify the required parameter 'body' is set
if @api_client.config.client_side_validation && body.nil?
fail ArgumentError, "Missing the required parameter 'body' when calling PetApi.update_pet"
end
# resource path
local_var_path = '/pet'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(body)
auth_names = ['petstore_auth']
data, status_code, headers = @api_client.call_api(:PUT, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PetApi#update_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Updates a pet in the store with form data
# @param pet_id ID of pet that needs to be updated
# @param [Hash] opts the optional parameters
# @option opts [String] :name Updated name of the pet
# @option opts [String] :status Updated status of the pet
# @return [nil]
def update_pet_with_form(pet_id, opts = {})
update_pet_with_form_with_http_info(pet_id, opts)
nil
end
# Updates a pet in the store with form data
# @param pet_id ID of pet that needs to be updated
# @param [Hash] opts the optional parameters
# @option opts [String] :name Updated name of the pet
# @option opts [String] :status Updated status of the pet
# @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers
def update_pet_with_form_with_http_info(pet_id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PetApi.update_pet_with_form ...'
end
# verify the required parameter 'pet_id' is set
if @api_client.config.client_side_validation && pet_id.nil?
fail ArgumentError, "Missing the required parameter 'pet_id' when calling PetApi.update_pet_with_form"
end
# resource path
local_var_path = '/pet/{petId}'.sub('{' + 'petId' + '}', pet_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded'])
# form parameters
form_params = {}
form_params['name'] = opts[:'name'] if !opts[:'name'].nil?
form_params['status'] = opts[:'status'] if !opts[:'status'].nil?
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PetApi#update_pet_with_form\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# uploads an image
# @param pet_id ID of pet to update
# @param [Hash] opts the optional parameters
# @option opts [String] :additional_metadata Additional data to pass to server
# @option opts [File] :file file to upload
# @return [ApiResponse]
def upload_file(pet_id, opts = {})
data, _status_code, _headers = upload_file_with_http_info(pet_id, opts)
data
end
# uploads an image
# @param pet_id ID of pet to update
# @param [Hash] opts the optional parameters
# @option opts [String] :additional_metadata Additional data to pass to server
# @option opts [File] :file file to upload
# @return [Array<(ApiResponse, Fixnum, Hash)>] ApiResponse data, response status code and response headers
def upload_file_with_http_info(pet_id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PetApi.upload_file ...'
end
# verify the required parameter 'pet_id' is set
if @api_client.config.client_side_validation && pet_id.nil?
fail ArgumentError, "Missing the required parameter 'pet_id' when calling PetApi.upload_file"
end
# resource path
local_var_path = '/pet/{petId}/uploadImage'.sub('{' + 'petId' + '}', pet_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])
# form parameters
form_params = {}
form_params['additionalMetadata'] = opts[:'additional_metadata'] if !opts[:'additional_metadata'].nil?
form_params['file'] = opts[:'file'] if !opts[:'file'].nil?
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'ApiResponse')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PetApi#upload_file\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# uploads an image (required)
# @param pet_id ID of pet to update
# @param required_file file to upload
# @param [Hash] opts the optional parameters
# @option opts [String] :additional_metadata Additional data to pass to server
# @return [ApiResponse]
def upload_file_with_required_file(pet_id, required_file, opts = {})
data, _status_code, _headers = upload_file_with_required_file_with_http_info(pet_id, required_file, opts)
data
end
# uploads an image (required)
# @param pet_id ID of pet to update
# @param required_file file to upload
# @param [Hash] opts the optional parameters
# @option opts [String] :additional_metadata Additional data to pass to server
# @return [Array<(ApiResponse, Fixnum, Hash)>] ApiResponse data, response status code and response headers
def upload_file_with_required_file_with_http_info(pet_id, required_file, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PetApi.upload_file_with_required_file ...'
end
# verify the required parameter 'pet_id' is set
if @api_client.config.client_side_validation && pet_id.nil?
fail ArgumentError, "Missing the required parameter 'pet_id' when calling PetApi.upload_file_with_required_file"
end
# verify the required parameter 'required_file' is set
if @api_client.config.client_side_validation && required_file.nil?
fail ArgumentError, "Missing the required parameter 'required_file' when calling PetApi.upload_file_with_required_file"
end
# resource path
local_var_path = '/fake/{petId}/uploadImageWithRequiredFile'.sub('{' + 'petId' + '}', pet_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data'])
# form parameters
form_params = {}
form_params['requiredFile'] = required_file
form_params['additionalMetadata'] = opts[:'additional_metadata'] if !opts[:'additional_metadata'].nil?
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'ApiResponse')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: PetApi#upload_file_with_required_file\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
end
end
| 39.421053 | 164 | 0.667903 |
bb0b18fe65c8f703221079eff1b9ad4dcdc1c2bf | 274 | class CreateSubscriptions < ActiveRecord::Migration
def change
create_table :subscriptions do |t|
t.references :leader, index: true, foreign_key: true
t.references :follower, index: true, foreign_key: true
t.timestamps null: false
end
end
end
| 24.909091 | 60 | 0.711679 |
7ab5b45573d3cff5e4580516bd1d4cd582a1ea5a | 1,062 | require 'active_record/migration'
require 'rails/generators/active_record'
module Roomer
module Generators
class MigrationGenerator < Rails::Generators::NamedBase
include Rails::Generators::Migration
extend ActiveRecord::Generators::Migration
include Roomer::Helpers::GeneratorHelper
source_root File.expand_path("../templates", __FILE__)
argument :attributes, :type => :array, :default => [], :banner => "field:type field:type"
class_option :shared, :type => :boolean, :default => false,
:aliases => "-s", :desc => "shared?"
# Generates the migration
def create_migration_file
set_local_assigns!
migration_template "migration.rb", "#{migration_dir}/roomer_#{file_name}"
end
protected
attr_reader :migration_action
def set_local_assigns!
if file_name =~ /^(add|remove)_.*_(?:to|from)_(.*)/
@migration_action = $1
@table_name = $2.pluralize
end
end
end
end
end
| 29.5 | 95 | 0.623352 |
4a60010d56d81a153a3b74fe0b9a2dc60e87aab8 | 1,320 | # frozen_string_literal: true
# WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
require 'aws-sdk-core'
require 'aws-sigv4'
require_relative 'aws-sdk-sms/types'
require_relative 'aws-sdk-sms/client_api'
require_relative 'aws-sdk-sms/client'
require_relative 'aws-sdk-sms/errors'
require_relative 'aws-sdk-sms/resource'
require_relative 'aws-sdk-sms/customizations'
# This module provides support for AWS Server Migration Service. This module is available in the
# `aws-sdk-sms` gem.
#
# # Client
#
# The {Client} class provides one method for each API operation. Operation
# methods each accept a hash of request parameters and return a response
# structure.
#
# sms = Aws::SMS::Client.new
# resp = sms.create_app(params)
#
# See {Client} for more information.
#
# # Errors
#
# Errors returned from AWS Server Migration Service are defined in the
# {Errors} module and all extend {Errors::ServiceError}.
#
# begin
# # do stuff
# rescue Aws::SMS::Errors::ServiceError
# # rescues all AWS Server Migration Service API errors
# end
#
# See {Errors} for more information.
#
# @service
module Aws::SMS
GEM_VERSION = '1.23.0'
end
| 24.90566 | 96 | 0.733333 |
21262c5c99244ae3e3a7dda2886a3425f3c60c42 | 322 | class Recipe < ApplicationRecord
belongs_to :user
belongs_to :original, class_name: "Recipe", optional: true
has_many :spinoffs, class_name: "Recipe", foreign_key: "original_id"
has_many :collector_favorites, foreign_key: "favorite_id"
has_many :collectors, class_name: "User", through: :collector_favorites
end
| 40.25 | 73 | 0.782609 |
e985ad8953f44e5a26fb506e3ca3af3daf933af8 | 1,764 | module SmartAnswer
class StatePensionAgeFlow < Flow
def define
content_id "5491c439-1c83-4044-80d3-32cc3613b739"
name "state-pension-age"
status :published
# Q1
radio :which_calculation? do
option :age
option :bus_pass
on_response do |response|
self.which_calculation = response
end
next_node do
question :dob_age?
end
end
# Q2:Age
date_question :dob_age? do
date_of_birth_defaults
validate { |response| response <= Time.zone.today }
on_response do |response|
self.calculator = Calculators::StatePensionAgeCalculator.new(dob: response)
end
next_node do
if which_calculation == "age"
if calculator.pension_age_based_on_gender?
question :gender?
elsif calculator.before_state_pension_date?
outcome :not_yet_reached_sp_age
else
outcome :has_reached_sp_age
end
else
outcome :bus_pass_result
end
end
end
# Q3
radio :gender? do
option :male
option :female
option :prefer_not_to_say
next_node do |response|
calculator.gender = response.to_sym
if calculator.non_binary?
outcome :has_reached_sp_age_non_binary
elsif calculator.before_state_pension_date?
outcome :not_yet_reached_sp_age
else
outcome :has_reached_sp_age
end
end
end
outcome :bus_pass_result
outcome :not_yet_reached_sp_age
outcome :has_reached_sp_age
outcome :has_reached_sp_age_non_binary
end
end
end
| 23.210526 | 85 | 0.598073 |
1166f1eaeb6777b3320f33e5e56ef031c373a160 | 410 | class Issue
include MongoMapper::Document
key :account_id, ObjectId, :required => true
key :name, String, :required => true
key :description, String
key :projected, Date
key :notes, Array
timestamps!
attr_accessible :account_id, :description, :name, :new_note
attr_accessor :new_note
attr_reader :new_note
has_many :ticket
has_many :note
def new_note=(new_note)
end
end | 20.5 | 61 | 0.712195 |
f8df11da6377f78b5d69b37cd5132d32ac6cb54b | 75 | # frozen_string_literal: true
json.partial! 'genres/genre', genre: @genre
| 18.75 | 43 | 0.76 |
03eee09f737bb86530efc01d944ef8f7ae16c7da | 1,947 | # frozen_string_literal: true
require 'spec_helper'
describe 'ActionMailer hooks' do
describe 'smime signature interceptor' do
before do
class_spy(ActionMailer::Base).as_stubbed_const
# rspec-rails calls ActionMailer::Base.deliveries.clear after every test
# https://github.com/rspec/rspec-rails/commit/71c12388e2bad78aaeea6443a393ede78341a7a3
allow(ActionMailer::Base).to receive_message_chain(:deliveries, :clear)
end
it 'is disabled by default' do
load Rails.root.join('config/initializers/action_mailer_hooks.rb')
expect(ActionMailer::Base).not_to(
have_received(:register_interceptor).with(Gitlab::Email::Hook::SmimeSignatureInterceptor))
end
describe 'interceptor testbed' do
where(:email_enabled, :email_smime_enabled, :smime_interceptor_enabled) do
[
[false, false, false],
[false, true, false],
[true, false, false],
[true, true, true]
]
end
with_them do
before do
stub_config_setting(email_enabled: email_enabled)
stub_config_setting(email_smime: { enabled: email_smime_enabled })
end
it 'is enabled depending on settings' do
load Rails.root.join('config/initializers/action_mailer_hooks.rb')
if smime_interceptor_enabled
# Premailer must be registered before S/MIME or signatures will be mangled
expect(ActionMailer::Base).to(
have_received(:register_interceptor).with(::Premailer::Rails::Hook).ordered)
expect(ActionMailer::Base).to(
have_received(:register_interceptor).with(Gitlab::Email::Hook::SmimeSignatureInterceptor).ordered)
else
expect(ActionMailer::Base).not_to(
have_received(:register_interceptor).with(Gitlab::Email::Hook::SmimeSignatureInterceptor))
end
end
end
end
end
end
| 34.767857 | 112 | 0.671803 |
62753abfa110107b6a2634bcac75d804b4b5d8b4 | 585 | require 'spec_helper'
describe 'session creation' do
it 'should begin without a session' do
get(SESSION_PATH)
json.should_not have_key('sessionId')
end
it 'should generate a session ID' do
post(SESSION_PATH)
json.should have_key('sessionId')
end
it 'should not create a session when requesting session creation with existing session ID' do
pending
end
it 'should detect a session ID collision and generate a new session ID' do
pending
end
it 'should detect and report race conditions when creating new sessions' do
pending
end
end
| 21.666667 | 95 | 0.729915 |
62d1d08a25441b6925cc9460b0da9d9cef0685b5 | 2,433 | # -*- coding: utf-8 -*-
# gems
require 'rubygems'
require 'bundler'
Bundler.require
if ENV['RACK_ENV'] == 'production'
# production config / requires
else
# development or testing only
require 'pry'
require 'awesome_print'
use Rack::ShowExceptions
end
# require the dependencies
$LOAD_PATH.unshift(File.dirname(__FILE__))
require File.join(File.dirname(__FILE__), 'app', 'init')
require 'app/root'
require 'app/api_base'
require 'app/harp_api'
require 'app/harp_debug_api'
require 'app/harp_user_api'
require 'app/sample'
require 'app/editor'
require 'data_mapper'
require 'delayed_job_data_mapper'
if ENV['RACK_ENV'] == 'production'
# production config / requires
DataMapper::Logger.new($stdout, :info)
else
DataMapper::Logger.new($stdout, :debug)
end
DataMapper::Model.raise_on_save_failure = true # globally across all models
DataMapper.setup(:default, ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/dev.db")
require 'harp-runtime/models/base'
require 'harp-runtime/models/compute'
DataMapper.finalize
DataMapper.auto_upgrade!
Delayed::Worker.backend.auto_upgrade!
# Following are Swagger directives, for REST API documentation.
##~ sapi = source2swagger.namespace("harp-runtime")
##~ sapi.swaggerVersion = "1.2"
##~ sapi.apiVersion = "0.1.0"
##~ auth = sapi.authorizations.add :apiKey => { :type => "apiKey", :passAs => "header" }
#
# Harp Debug API
#
##~ a = sapi.apis.add
##
##~ a.set :path => "/harp-debug.{format}", :format => "json"
##~ a.description = "Harp runtime invocation for debugging."
map "/api/v1/harp-debug" do
run HarpDebugApiApp
end
#
# Harp API
#
##~ a = sapi.apis.add
##
##~ a.set :path => "/harp.{format}", :format => "json"
##~ a.description = "Harp runtime invocation"
map "/api/v1/harp" do
run HarpApiApp
end
#
# Harp User API
#
##~ a = sapi.apis.add
##
##~ a.set :path => "/user.{format}", :format => "json"
##~ a.description = "Harp User API"
map "/api/v1/user" do
run HarpUserApiApp
end
# Sample API
#
##~ a = sapi.apis.add
##
##~ a.set :path => "/sample"
##~ a.description = "API for sample Harp scripts"
map "/api/v1/sample" do
run SampleApp
end
map "/edit" do
run EditorApp
end
# Serve swagger-ui from bower directory
map "/swagger-ui" do
run Rack::Directory.new("./bower_components/swagger-ui/dist")
end
# Serve swagger-ui from bower directory
map "/bower_components" do
run Rack::Directory.new("./bower_components")
end
map '/' do
run RootApp
end
| 21.723214 | 88 | 0.69626 |
5d7b6b24cf9c797c573c1dbb07201adb908bbeac | 561 | module Docker
class ServiceStarter
attr_reader :host_node
##
# @param [HostNode] host_node
def initialize(host_node)
@host_node = host_node
end
##
# @param [String] service_name
def start_service_instance(service_name)
self.request_start_service(service_name)
end
##
# @param [Hash] service_spec
def request_start_service(name)
client.request('/service_pods/start', name)
end
##
# @return [RpcClient]
def client
RpcClient.new(host_node.node_id, 5)
end
end
end
| 18.096774 | 49 | 0.648841 |
ed810e64bd7a63bbee27d9e7318de598d29cabb5 | 56 | BetterErrors.editor = :macvim if Rails.env.development?
| 28 | 55 | 0.803571 |
1decca2a816fcaea3fd29be485fb73b70fb9ad27 | 1,021 | class InvitationCode < ApplicationRecord
hobo_model # Don't put anything above this
fields do
name :string, :unique, :null => false
total :integer, :null => false
used :integer, :null => false
trial_days :integer, :null => false
start_at :date, :null => false
end_at :date, :null => false
timestamps
end
attr_accessible :name, :total, :used, :trial_days, :start_at, :end_at, :partner, :partner_id
belongs_to :partner, :inverse_of => :invitation_codes
scope :available, lambda {|*name_param|
where("name = ? and now() between start_at and end_at and used < total", name_param)
}
def remaining
total - used
end
# --- Permissions --- #
def create_permitted?
acting_user.administrator?
end
def update_permitted?
acting_user.administrator || !name_changed? && !total_changed? && !trial_days_changed?
end
def destroy_permitted?
acting_user.administrator?
end
def view_permitted?(field)
true
end
end | 22.688889 | 94 | 0.661117 |
d535e31cacf673cd7bf2e04afd5e8114a5ec067e | 387 | class CreateEntitiesLists < ActiveRecord::Migration[5.1]
def change
create_table :entities_lists, id: :uuid do |t|
t.string :listname
t.integer :position, default: 0
t.string :color
t.text :description
t.integer :visibility, default: 0
t.references :agent, foreign_key: { on_delete: :cascade }, type: :uuid
t.timestamps
end
end
end
| 25.8 | 76 | 0.658915 |
abd0e268020554af479ab8abef0af5a614bf5412 | 2,479 | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Auxiliary
include Msf::Exploit::Remote::Capture
def initialize(info = {})
super(
'Name' => 'Forge Cisco DTP Packets',
'Description' => %q{
This module forges DTP packets to initialize a trunk port.
},
'Author' => [ 'Spencer McIntyre' ],
'License' => MSF_LICENSE,
'Actions' =>
[
[ 'Service' ]
],
'PassiveActions' => [ 'Service' ],
'DefaultAction' => 'Service'
)
register_options(
[
OptString.new('SMAC', [false, 'The spoofed mac (if unset, derived from netifaces)']),
], self.class)
deregister_options('RHOST', 'PCAPFILE')
end
def setup
super
unless datastore['SMAC'] || datastore['INTERFACE']
raise ArgumentError, 'Must specify SMAC or INTERFACE'
end
end
def build_dtp_frame
p = PacketFu::EthPacket.new
p.eth_daddr = '01:00:0c:cc:cc:cc'
p.eth_saddr = smac
llc_hdr = "\xaa\xaa\x03\x00\x00\x0c\x20\x04"
dtp_hdr = "\x01" # version
dtp_hdr << "\x00\x01\x00\x0d\x00\x00\x00\x00\x00\x00\x00\x00\x00" # domain
dtp_hdr << "\x00\x02\x00\x05\x03" # status
dtp_hdr << "\x00\x03\x00\x05\x45" # dtp type
dtp_hdr << "\x00\x04\x00\x0a" << PacketFu::EthHeader.mac2str(smac) # neighbor
p.eth_proto = llc_hdr.length + dtp_hdr.length
p.payload = llc_hdr << dtp_hdr
p
end
def is_mac?(mac)
!!(mac =~ /^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/)
end
def smac
@spoof_mac ||= datastore['SMAC']
@spoof_mac ||= get_mac(datastore['INTERFACE']) if netifaces_implemented?
return @spoof_mac
end
def run
unless smac()
print_error 'Source MAC (SMAC) should be defined'
else
unless is_mac? smac
print_error "Source MAC (SMAC) `#{smac}' is badly formatted."
else
print_status "Starting DTP spoofing service..."
open_pcap({'FILTER' => "ether host 01:00:0c:cc:cc:cc"})
interface = datastore['INTERFACE'] || Pcap.lookupdev
dtp = build_dtp_frame()
@run = true
while @run
capture.inject(dtp.to_s)
select(nil, nil, nil, 60)
end
close_pcap
end
end
end
end
| 28.170455 | 98 | 0.570795 |
d5b268ba2971e77e720bd532d5f947c5e115eb48 | 511 | module Dashboard
class RemotePhoneCallEventsController < Dashboard::BaseController
private
def association_chain
if parent_resource
parent_resource.remote_phone_call_events
else
current_account.remote_phone_call_events
end
end
def parent_resource
phone_call if phone_call_id
end
def phone_call_id
params[:phone_call_id]
end
def phone_call
@phone_call ||= current_account.phone_calls.find(phone_call_id)
end
end
end
| 19.653846 | 69 | 0.714286 |
ab24b2778866710ab0bc68b6c1c669308166c6dc | 6,316 | =begin
#Selling Partner API for Fulfillment Inbound
#The Selling Partner API for Fulfillment Inbound lets you create applications that create and update inbound shipments of inventory to Amazon's fulfillment network.
OpenAPI spec version: v0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 3.0.26
=end
require 'date'
module AmzSpApi::FulfillmentInboundApiModel
class InboundShipmentPlanRequestItemList
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
}
end
# Attribute type mapping.
def self.openapi_types
{
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `AmzSpApi::FulfillmentInboundApiModel::InboundShipmentPlanRequestItemList` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `AmzSpApi::FulfillmentInboundApiModel::InboundShipmentPlanRequestItemList`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
# call parent's initialize
super(attributes)
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = super
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class && super(o)
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
super(attributes)
self.class.openapi_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
elsif attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
end
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
AmzSpApi::FulfillmentInboundApiModel.const_get(type).build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = super
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end end
end
| 31.267327 | 250 | 0.639329 |
ac10794882415ecb521db79eb3525781012b2c4c | 173 | module Kaseya::VSA
class Client::Logs < Api
def alarms_by_agent(agent_guid, params = {})
get_many "assetmgmt/logs/#{agent_guid}/alarms", params
end
end
end | 24.714286 | 60 | 0.687861 |
08bde33d7b3405433b86da875bae9a927cea3577 | 7,961 | #
# Author:: Steven Danna ([email protected])
# Copyright:: Copyright (c) 2012 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 'spec_helper'
require 'chef/user'
require 'tempfile'
describe Chef::User do
before(:each) do
@user = Chef::User.new
end
describe "initialize" do
it "should be a Chef::User" do
@user.should be_a_kind_of(Chef::User)
end
end
describe "name" do
it "should let you set the name to a string" do
@user.name("ops_master").should == "ops_master"
end
it "should return the current name" do
@user.name "ops_master"
@user.name.should == "ops_master"
end
# It is not feasible to check all invalid characters. Here are a few
# that we probably care about.
it "should not accept invalid characters" do
# capital letters
lambda { @user.name "Bar" }.should raise_error(ArgumentError)
# slashes
lambda { @user.name "foo/bar" }.should raise_error(ArgumentError)
# ?
lambda { @user.name "foo?" }.should raise_error(ArgumentError)
# &
lambda { @user.name "foo&" }.should raise_error(ArgumentError)
end
it "should not accept spaces" do
lambda { @user.name "ops master" }.should raise_error(ArgumentError)
end
it "should throw an ArgumentError if you feed it anything but a string" do
lambda { @user.name Hash.new }.should raise_error(ArgumentError)
end
end
describe "admin" do
it "should let you set the admin bit" do
@user.admin(true).should == true
end
it "should return the current admin value" do
@user.admin true
@user.admin.should == true
end
it "should default to false" do
@user.admin.should == false
end
it "should throw an ArgumentError if you feed it anything but true or false" do
lambda { @user.name Hash.new }.should raise_error(ArgumentError)
end
end
describe "public_key" do
it "should let you set the public key" do
@user.public_key("super public").should == "super public"
end
it "should return the current public key" do
@user.public_key("super public")
@user.public_key.should == "super public"
end
it "should throw an ArgumentError if you feed it something lame" do
lambda { @user.public_key Hash.new }.should raise_error(ArgumentError)
end
end
describe "private_key" do
it "should let you set the private key" do
@user.private_key("super private").should == "super private"
end
it "should return the private key" do
@user.private_key("super private")
@user.private_key.should == "super private"
end
it "should throw an ArgumentError if you feed it something lame" do
lambda { @user.private_key Hash.new }.should raise_error(ArgumentError)
end
end
describe "when serializing to JSON" do
before(:each) do
@user.name("black")
@user.public_key("crowes")
@json = @user.to_json
end
it "serializes as a JSON object" do
@json.should match(/^\{.+\}$/)
end
it "includes the name value" do
@json.should include(%q{"name":"black"})
end
it "includes the public key value" do
@json.should include(%{"public_key":"crowes"})
end
it "includes the 'admin' flag" do
@json.should include(%q{"admin":false})
end
it "includes the private key when present" do
@user.private_key("monkeypants")
@user.to_json.should include(%q{"private_key":"monkeypants"})
end
it "does not include the private key if not present" do
@json.should_not include("private_key")
end
it "includes the password if present" do
@user.password "password"
@user.to_json.should include(%q{"password":"password"})
end
it "does not include the password if not present" do
@json.should_not include("password")
end
end
describe "when deserializing from JSON" do
before(:each) do
user = { "name" => "mr_spinks",
"public_key" => "turtles",
"private_key" => "pandas",
"password" => "password",
"admin" => true }
@user = Chef::User.from_json(user.to_json)
end
it "should deserialize to a Chef::User object" do
@user.should be_a_kind_of(Chef::User)
end
it "preserves the name" do
@user.name.should == "mr_spinks"
end
it "preserves the public key" do
@user.public_key.should == "turtles"
end
it "preserves the admin status" do
@user.admin.should be_true
end
it "includes the private key if present" do
@user.private_key.should == "pandas"
end
it "includes the password if present" do
@user.password.should == "password"
end
end
describe "API Interactions" do
before (:each) do
@user = Chef::User.new
@user.name "foobar"
@http_client = double("Chef::REST mock")
Chef::REST.stub(:new).and_return(@http_client)
end
describe "list" do
before(:each) do
Chef::Config[:chef_server_url] = "http://www.example.com"
@osc_response = { "admin" => "http://www.example.com/users/admin"}
@ohc_response = [ { "user" => { "username" => "admin" }} ]
Chef::User.stub(:load).with("admin").and_return(@user)
@osc_inflated_response = { "admin" => @user }
end
it "lists all clients on an OSC server" do
@http_client.stub(:get_rest).with("users").and_return(@osc_response)
Chef::User.list.should == @osc_response
end
it "inflate all clients on an OSC server" do
@http_client.stub(:get_rest).with("users").and_return(@osc_response)
Chef::User.list(true).should == @osc_inflated_response
end
it "lists all clients on an OHC/OPC server" do
@http_client.stub(:get_rest).with("users").and_return(@ohc_response)
# We expect that Chef::User.list will give a consistent response
# so OHC API responses should be transformed to OSC-style output.
Chef::User.list.should == @osc_response
end
it "inflate all clients on an OHC/OPC server" do
@http_client.stub(:get_rest).with("users").and_return(@ohc_response)
Chef::User.list(true).should == @osc_inflated_response
end
end
describe "create" do
it "creates a new user via the API" do
@user.password "password"
@http_client.should_receive(:post_rest).with("users", {:name => "foobar", :admin => false, :password => "password"}).and_return({})
@user.create
end
end
describe "read" do
it "loads a named user from the API" do
@http_client.should_receive(:get_rest).with("users/foobar").and_return({"name" => "foobar", "admin" => true, "public_key" => "pubkey"})
user = Chef::User.load("foobar")
user.name.should == "foobar"
user.admin.should == true
user.public_key.should == "pubkey"
end
end
describe "update" do
it "updates an existing user on via the API" do
@http_client.should_receive(:put_rest).with("users/foobar", {:name => "foobar", :admin => false}).and_return({})
@user.update
end
end
describe "destroy" do
it "deletes the specified user via the API" do
@http_client.should_receive(:delete_rest).with("users/foobar")
@user.destroy
end
end
end
end
| 29.705224 | 143 | 0.642633 |
bf8f50bbb74d544ed71a126477a96358fa11df0c | 6,434 | # WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
module Aws::EC2
class KeyPair
extend Aws::Deprecations
# @overload def initialize(name, options = {})
# @param [String] name
# @option options [Client] :client
# @overload def initialize(options = {})
# @option options [required, String] :name
# @option options [Client] :client
def initialize(*args)
options = Hash === args.last ? args.pop.dup : {}
@name = extract_name(args, options)
@data = options.delete(:data)
@client = options.delete(:client) || Client.new(options)
end
# @!group Read-Only Attributes
# @return [String]
def name
@name
end
alias :key_name :name
# The SHA-1 digest of the DER encoded private key.
# @return [String]
def key_fingerprint
data[:key_fingerprint]
end
# An unencrypted PEM encoded RSA private key.
# @return [String]
def key_material
data[:key_material]
end
# @!endgroup
# @return [Client]
def client
@client
end
# @raise [NotImplementedError]
# @api private
def load
msg = "#load is not implemented, data only available via enumeration"
raise NotImplementedError, msg
end
alias :reload :load
# @raise [NotImplementedError] Raises when {#data_loaded?} is `false`.
# @return [Types::KeyPair]
# Returns the data for this {KeyPair}.
def data
load unless @data
@data
end
# @return [Boolean]
# Returns `true` if this resource is loaded. Accessing attributes or
# {#data} on an unloaded resource will trigger a call to {#load}.
def data_loaded?
!!@data
end
# @deprecated Use [Aws::EC2::Client] #wait_until instead
#
# Waiter polls an API operation until a resource enters a desired
# state.
#
# @note The waiting operation is performed on a copy. The original resource remains unchanged
#
# ## Basic Usage
#
# Waiter will polls until it is successful, it fails by
# entering a terminal state, or until a maximum number of attempts
# are made.
#
# # polls in a loop until condition is true
# resource.wait_until(options) {|resource| condition}
#
# ## Example
#
# instance.wait_until(max_attempts:10, delay:5) {|instance| instance.state.name == 'running' }
#
# ## Configuration
#
# You can configure the maximum number of polling attempts, and the
# delay (in seconds) between each polling attempt. The waiting condition is set
# by passing a block to {#wait_until}:
#
# # poll for ~25 seconds
# resource.wait_until(max_attempts:5,delay:5) {|resource|...}
#
# ## Callbacks
#
# You can be notified before each polling attempt and before each
# delay. If you throw `:success` or `:failure` from these callbacks,
# it will terminate the waiter.
#
# started_at = Time.now
# # poll for 1 hour, instead of a number of attempts
# proc = Proc.new do |attempts, response|
# throw :failure if Time.now - started_at > 3600
# end
#
# # disable max attempts
# instance.wait_until(before_wait:proc, max_attempts:nil) {...}
#
# ## Handling Errors
#
# When a waiter is successful, it returns the Resource. When a waiter
# fails, it raises an error.
#
# begin
# resource.wait_until(...)
# rescue Aws::Waiters::Errors::WaiterFailed
# # resource did not enter the desired state in time
# end
#
#
# @yield param [Resource] resource to be used in the waiting condition
#
# @raise [Aws::Waiters::Errors::FailureStateError] Raised when the waiter terminates
# because the waiter has entered a state that it will not transition
# out of, preventing success.
#
# yet successful.
#
# @raise [Aws::Waiters::Errors::UnexpectedError] Raised when an error is encountered
# while polling for a resource that is not expected.
#
# @raise [NotImplementedError] Raised when the resource does not
#
# @option options [Integer] :max_attempts (10) Maximum number of
# attempts
# @option options [Integer] :delay (10) Delay between each
# attempt in seconds
# @option options [Proc] :before_attempt (nil) Callback
# invoked before each attempt
# @option options [Proc] :before_wait (nil) Callback
# invoked before each wait
# @return [Resource] if the waiter was successful
def wait_until(options = {}, &block)
self_copy = self.dup
attempts = 0
options[:max_attempts] = 10 unless options.key?(:max_attempts)
options[:delay] ||= 10
options[:poller] = Proc.new do
attempts += 1
if block.call(self_copy)
[:success, self_copy]
else
self_copy.reload unless attempts == options[:max_attempts]
:retry
end
end
Aws::Waiters::Waiter.new(options).wait({})
end
# @!group Actions
# @example Request syntax with placeholder values
#
# key_pair.delete({
# dry_run: false,
# })
# @param [Hash] options ({})
# @option options [Boolean] :dry_run
# Checks whether you have the required permissions for the action,
# without actually making the request, and provides an error response.
# If you have the required permissions, the error response is
# `DryRunOperation`. Otherwise, it is `UnauthorizedOperation`.
# @return [EmptyStructure]
def delete(options = {})
options = options.merge(key_name: @name)
resp = @client.delete_key_pair(options)
resp.data
end
# @deprecated
# @api private
def identifiers
{ name: @name }
end
deprecated(:identifiers)
private
def extract_name(args, options)
value = args[0] || options.delete(:name)
case value
when String then value
when nil then raise ArgumentError, "missing required option :name"
else
msg = "expected :name to be a String, got #{value.class}"
raise ArgumentError, msg
end
end
class Collection < Aws::Resources::Collection; end
end
end
| 30.065421 | 102 | 0.627448 |
e8f755fc5f9028e9a168342c7ccedebe49164d00 | 58 | # frozen_string_literal: true
RailsRoutingChecker.valid!
| 14.5 | 29 | 0.844828 |
ed4b9203c91502e05943eee40359190fde4dc132 | 2,246 | require 'one_gadget/gadget'
# https://gitlab.com/libcdb/libcdb/blob/master/libc/libc6_2.19-10ubuntu2_i386/lib/i386-linux-gnu/libc-2.19.so
#
# Intel 80386
#
# GNU C Library (Ubuntu GLIBC 2.19-10ubuntu2) stable release version 2.19, by Roland McGrath et al.
# Copyright (C) 2014 Free Software Foundation, Inc.
# This is free software; see the source for copying conditions.
# There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
# Compiled by GNU CC version 4.8.3.
# Compiled on a Linux 3.16.3 system on 2014-09-30.
# Available extensions:
# crypt add-on version 2.1 by Michael Glad and others
# GNU Libidn by Simon Josefsson
# Native POSIX Threads Library by Ulrich Drepper et al
# BIND-8.2.3-T5B
# libc ABIs: UNIQUE IFUNC
# For bug reporting instructions, please see:
# <https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>.
build_id = File.basename(__FILE__, '.rb').split('-').last
OneGadget::Gadget.add(build_id, 255507,
constraints: ["ebx is the GOT address of libc", "[esp+0x34] == NULL"],
effect: "execve(\"/bin/sh\", esp+0x34, environ)")
OneGadget::Gadget.add(build_id, 255543,
constraints: ["ebx is the GOT address of libc", "[eax] == NULL || eax == NULL", "[[esp+0x8]] == NULL || [esp+0x8] == NULL"],
effect: "execve(\"/bin/sh\", eax, [esp+0x8])")
OneGadget::Gadget.add(build_id, 255547,
constraints: ["ebx is the GOT address of libc", "[[esp+0x4]] == NULL || [esp+0x4] == NULL", "[[esp+0x8]] == NULL || [esp+0x8] == NULL"],
effect: "execve(\"/bin/sh\", [esp+0x4], [esp+0x8])")
OneGadget::Gadget.add(build_id, 417275,
constraints: ["ebx is the GOT address of libc", "[esp+0x8] == NULL"],
effect: "execl(\"/bin/sh\", \"sh\", [esp+0x8])")
OneGadget::Gadget.add(build_id, 417281,
constraints: ["ebx is the GOT address of libc", "eax == NULL"],
effect: "execl(\"/bin/sh\", eax)")
OneGadget::Gadget.add(build_id, 417285,
constraints: ["ebx is the GOT address of libc", "[esp+0x4] == NULL"],
effect: "execl(\"/bin/sh\", [esp+0x4])")
| 53.47619 | 158 | 0.60463 |
f8b3853da5a6b0ef55a405bebf4c1671e99b1ac5 | 252 | module CsCertificates
class UdlModuleCertificate < Certificate
def initialize(args={})
super(args)
@user_module_assessment = args.fetch(:user_module_assessment, nil)
end
def build_pdf
@pdf.text "This is a test pdf."
end
end
end
| 18 | 70 | 0.72619 |
1d538b2d6301e31edb3db2ae7b4a725079c5bf09 | 3,951 | #!/opt/puppetlabs/puppet/bin/ruby
require 'json'
require 'puppet'
def model_update_composite_entity(*args)
header_params = {}
argstring = args[0].delete('\\')
arg_hash = JSON.parse(argstring)
# Remove task name from arguments - should contain all necessary parameters for URI
arg_hash.delete('_task')
operation_verb = 'Put'
query_params, body_params, path_params = format_params(arg_hash)
uri_string = "https:////apps/%{app_id}/versions/%{version_id}/compositeentities/%{c_entity_id}" % path_params
unless query_params.empty?
uri_string = uri_string + '?' + to_query(query_params)
end
header_params['Content-Type'] = 'application/json' # first of #{parent_consumes}
return nil unless authenticate(header_params) == true
uri = URI(uri_string)
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
if operation_verb == 'Get'
req = Net::HTTP::Get.new(uri)
elsif operation_verb == 'Put'
req = Net::HTTP::Put.new(uri)
elsif operation_verb == 'Delete'
req = Net::HTTP::Delete.new(uri)
end
header_params.each { |x, v| req[x] = v } unless header_params.empty?
unless body_params.empty?
req.body=body_params.to_json
end
Puppet.debug("URI is (#{operation_verb}) #{uri} headers are #{header_params}")
response = http.request req # Net::HTTPResponse object
Puppet.debug("Called (#{operation_verb}) endpoint at #{uri}")
Puppet.debug("response code is #{response.code} and body is #{response.body}")
response
end
end
def to_query(hash)
if hash
return_value = hash.map { |x, v| "#{x}=#{v}" }.reduce { |x, v| "#{x}&#{v}" }
if !return_value.nil?
return return_value
end
end
return ''
end
def op_param(name, inquery, paramalias, namesnake)
operation_param = { :name => name, :location => inquery, :paramalias => paramalias, :namesnake => namesnake }
return operation_param
end
def format_params(key_values)
query_params = {}
body_params = {}
path_params = {}
key_values.each do |key,value|
if value.include? '{'
key_values[key]=JSON.parse(value.gsub("\'","\""))
end
end
op_params = [
op_param('appId', 'path', 'app_id', 'app_id'),
op_param('cEntityId', 'path', 'c_entity_id', 'c_entity_id'),
op_param('code', 'body', 'code', 'code'),
op_param('compositeModelUpdateObject', 'body', 'composite_model_update_object', 'composite_model_update_object'),
op_param('message', 'body', 'message', 'message'),
op_param('versionId', 'path', 'version_id', 'version_id'),
]
op_params.each do |i|
location = i[:location]
name = i[:name]
paramalias = i[:paramalias]
name_snake = i[:namesnake]
if location == 'query'
query_params[name] = key_values[name_snake] unless key_values[name_snake].nil?
query_params[name] = ENV["azure__#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil?
elsif location == 'body'
body_params[name] = key_values[name_snake] unless key_values[name_snake].nil?
body_params[name] = ENV["azure_#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil?
else
path_params[name_snake.to_sym] = key_values[name_snake] unless key_values[name_snake].nil?
path_params[name_snake.to_sym] = ENV["azure__#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil?
end
end
return query_params,body_params,path_params
end
def authenticate(header_params)
header_params["Ocp-Apim-Subscription-Key"] = ENV["<no value>_api_key"]
end
def task
# Get operation parameters from an input JSON
params = STDIN.read
result = model_update_composite_entity(params)
if result.is_a? Net::HTTPSuccess
puts result.body
else
raise result.body
end
rescue StandardError => e
result = {}
result[:_error] = {
msg: e.message,
kind: 'puppetlabs-azure_arm/error',
details: { class: e.class.to_s },
}
puts result
exit 1
end
task | 30.392308 | 119 | 0.675778 |
f7e95af89892d6988ca1c2500fc503b938bec880 | 150 | ##
# BasicObject
assert('BasicObject') do
BasicObject.class == Class
end
assert('BasicObject superclass') do
BasicObject.superclass == nil
end
| 12.5 | 35 | 0.733333 |
267958147e149810681cd6e9ccaf087d5651673d | 1,804 | # frozen_string_literal: true
require_relative "lib/gem_test_yuno/version"
Gem::Specification.new do |spec|
spec.name = "gem_test_yuno"
spec.version = GemTestYuno::VERSION
spec.authors = ["Yunosuke Minegishi"]
spec.email = ["[email protected]"]
spec.summary = "This is a test gem for me."
spec.description = "This is a test gem for me."
spec.homepage = "https://github.com/yunosuke924/gem_test_yuno"
spec.license = "MIT"
spec.required_ruby_version = ">= 2.4.0"
spec.metadata["allowed_push_host"] = "https://rubygems.org"
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/yunosuke924/gem_test_yuno"
spec.metadata["changelog_uri"] = "https://github.com/yunosuke924/gem_test_yuno/blob/main/CHANGELOG.md"
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path(__dir__)) do
`git ls-files -z`.split("\x0").reject do |f|
(f == __FILE__) || f.match(%r{\A(?:(?:test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
end
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
# Uncomment to register a new dependency of your gem
# spec.add_dependency "example-gem", "~> 1.0"
spec.add_development_dependency "bundler", "~> 2.0"
spec.add_development_dependency "rake", "~> 13.0"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "rubocop", "~> 1.7"
# For more information and examples about making a new gem, checkout our
# guide at: https://bundler.io/guides/creating_gem.html
end
| 40.088889 | 104 | 0.686807 |
abd1b04939813b24d46c3a532e62b598b720cc00 | 138 | require 'test_helper'
class Api::PhotosControllerTest < ActionController::TestCase
# test "the truth" do
# assert true
# end
end
| 17.25 | 60 | 0.724638 |
7a0b0a5e1e51ae8865099143c2da2db14092af71 | 1,080 | #!/usr/bin/env ruby
require 'sigdump/setup'
require 'emony/configuration'
require 'emony/engine'
config = Emony::Configuration.new(
sources: [
{
type: :network,
}
],
filters: {
'*' => [
{
type: :numeric,
key: 'reqtime',
float: true,
result_in_float: false,
op: [multiply: 1000],
},
],
},
aggregations: {
'*' => {
time: 'time',
time_format: '%Y-%m-%d %H:%M:%S',
window: {duration: 5, wait: 1},
sub_windows: [{duration: 10, wait: 2, allowed_gap: 3}, {duration: 60, wait: 2, allowed_gap: 3}],
items: {
count: {type: :count},
rps: {type: :persec},
n: {type: :standard, key: 'reqtime'},
#histo: {type: :histogram, key: 'reqtime', width: 20},
},
groups: {
#path: {type: :path, key: 'path', default_level: 2},
},
},
},
outputs: {
'*' => {type: :copy, outputs: [{type: :stdout}, {type: :forward, host: 'localhost', port: 37867}]},
},
)
engine = Emony::Engine.new(config)
engine.prepare
engine.run
| 22.978723 | 103 | 0.513889 |
082570c55b3f5b856ae94863865a8fcd68e4946a | 1,945 | require "cases/helper"
require 'models/binary'
class SanitizeTest < ActiveRecord::TestCase
def setup
end
def test_sanitize_sql_hash_handles_associations
quoted_bambi = ActiveRecord::Base.connection.quote("Bambi")
quoted_column_name = ActiveRecord::Base.connection.quote_column_name("name")
quoted_table_name = ActiveRecord::Base.connection.quote_table_name("adorable_animals")
expected_value = "#{quoted_table_name}.#{quoted_column_name} = #{quoted_bambi}"
assert_equal expected_value, Binary.send(:sanitize_sql_hash, {adorable_animals: {name: 'Bambi'}})
end
def test_sanitize_sql_array_handles_string_interpolation
quoted_bambi = ActiveRecord::Base.connection.quote_string("Bambi")
assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=%s", "Bambi"])
assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=%s", "Bambi".mb_chars])
quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote_string("Bambi\nand\nThumper")
assert_equal "name=#{quoted_bambi_and_thumper}",Binary.send(:sanitize_sql_array, ["name=%s", "Bambi\nand\nThumper"])
assert_equal "name=#{quoted_bambi_and_thumper}",Binary.send(:sanitize_sql_array, ["name=%s", "Bambi\nand\nThumper".mb_chars])
end
def test_sanitize_sql_array_handles_bind_variables
quoted_bambi = ActiveRecord::Base.connection.quote("Bambi")
assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi"])
assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi".mb_chars])
quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote("Bambi\nand\nThumper")
assert_equal "name=#{quoted_bambi_and_thumper}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi\nand\nThumper"])
assert_equal "name=#{quoted_bambi_and_thumper}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi\nand\nThumper".mb_chars])
end
end
| 55.571429 | 129 | 0.760925 |
620928acb51a0453798dd802f13f814149c9bde9 | 1,214 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Logic::Mgmt::V2018_07_01_preview
module Models
#
# The integration account session filter.
#
class IntegrationAccountSessionFilter
include MsRestAzure
# @return [DateTime] The changed time of integration account sessions.
attr_accessor :changed_time
#
# Mapper for IntegrationAccountSessionFilter class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'IntegrationAccountSessionFilter',
type: {
name: 'Composite',
class_name: 'IntegrationAccountSessionFilter',
model_properties: {
changed_time: {
client_side_validation: true,
required: true,
serialized_name: 'changedTime',
type: {
name: 'DateTime'
}
}
}
}
}
end
end
end
end
| 26.391304 | 76 | 0.58402 |
e86c9b976bbede09a822af5e68faa107bbe63734 | 397 | # frozen_string_literal: true
module Contex
class RailtiePostload < Rails::Railtie
initializer 'rails_context.postload' do |app|
path_rejector = lambda { |s| s == Rails.root.join('app', 'contexts').to_s }
app.config.eager_load_paths = app.config.eager_load_paths.reject(&path_rejector)
ActiveSupport::Dependencies.autoload_paths.reject!(&path_rejector)
end
end
end
| 30.538462 | 86 | 0.732997 |
79c798bb1a069ba1ed9024769f85c5dfe28d987e | 2,712 | #### releasinator config ####
configatron.product_name = "PayPal Python SDK"
# List of items to confirm from the person releasing. Required, but empty list is ok.
configatron.prerelease_checklist_items = [
"Sanity check the master branch."
]
def validate_version_match()
if 'v'+package_version() != @current_release.version
Printer.fail("Package.json version #{package_version} does not match changelog version #{@current_release.version}.")
abort()
end
Printer.success("Package.json version #{package_version} matches latest changelog version #{@current_release.version}.")
end
def validate_paths
@validator.validate_in_path("pip")
@validator.validate_in_path("virtualenv")
end
def validate_virtualenvwrapper
if !File.exist?("/Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh")
Printer.fail("mkvirtualenv is not setup in this system")
abort()
end
Printer.success("mkvirtualenv setup properly in this system")
end
configatron.custom_validation_methods = [
method(:validate_paths),
method(:validate_version_match),
method(:validate_virtualenvwrapper)
]
def build_method
command = "source /usr/local/bin/virtualenvwrapper.sh;"
command += "mkvirtualenv pythonsdk;"
command += "workon pythonsdk;"
command += "pip install -r requirements.txt;"
command += "nosetests --with-coverage --cover-package=paypalrestsdk --include=paypalrestsdk/* --exclude=functional*"
CommandProcessor.command(command, live_output=true)
end
# The command that builds the sdk. Required.
configatron.build_method = method(:build_method)
def publish_to_package_manager(version)
# you need to run 'python setup.py register' first time. it's one time activity
#CommandProcessor.command("python setup.py register", live_output=true)
CommandProcessor.command("python setup.py sdist upload", live_output=true)
end
# The method that publishes the sdk to the package manager. Required.
configatron.publish_to_package_manager_method = method(:publish_to_package_manager)
def wait_for_package_manager(version)
CommandProcessor.wait_for("wget -U \"non-empty-user-agent\" -qO- https://pypi.python.org/pypi/paypalrestsdk/#{package_version} | cat")
end
# The method that waits for the package manager to be done. Required
configatron.wait_for_package_manager_method = method(:wait_for_package_manager)
# Whether to publish the root repo to GitHub. Required.
configatron.release_to_github = true
def package_version()
File.open("paypalrestsdk/config.py", 'r') do |f|
f.each_line do |line|
if line.match (/__version__ = \"\d+\.\d+\.\d+\"/)
return line.strip.split('=')[1].strip.split('"')[1]
end
end
end
end
| 34.769231 | 136 | 0.753319 |
6158095e4d1f01e08a0f51d87ad3d67c65b04836 | 41 | module EpiDeploy
VERSION = "2.1.0"
end
| 10.25 | 19 | 0.682927 |
0159f45e380d5c7d2f2537b8d04a46d8513fb915 | 10,776 | # -------------------------------------------------------------------------- #
# Copyright 2002-2022, OpenNebula Project, OpenNebula Systems #
# #
# 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 'opennebula/xml_utils'
module OpenNebula
# The Pool class represents a generic OpenNebula Pool in XML format
# and provides the basic functionality to handle the Pool elements
class Pool < XMLPool
include Enumerable
alias_method :each_with_xpath, :each
attr_reader :pool_name
attr_reader :element_name
PAGINATED_POOLS=%w{VM_POOL IMAGE_POOL TEMPLATE_POOL VN_POOL
SECGROUP_POOL DOCUMENT_POOL}
protected
#pool:: _String_ XML name of the root element
#element:: _String_ XML name of the Pool elements
#client:: _Client_ represents a XML-RPC connection
def initialize(pool,element,client)
super(nil)
@pool_name = pool.upcase
@element_name = element.upcase
@client = client
end
# Default Factory Method for the Pools. The factory method returns an
# suitable PoolElement object. Each Pool MUST implement the
# corresponding factory method
# element_xml:: _XML_ XML element describing the pool element
# [return] a PoolElement object
def factory(element_xml)
OpenNebula::PoolElement.new(element_xml,client)
end
#######################################################################
# Common XML-RPC Methods for all the Pool Types
#######################################################################
#Gets the pool without any filter. Host, Group and User Pools
# xml_method:: _String_ the name of the XML-RPC method
def info(xml_method)
return xmlrpc_info(xml_method)
end
alias_method :info!, :info
def info_extended(xml_method)
return xmlrpc_info(xml_info)
end
def info_all(xml_method, *args)
return xmlrpc_info(xml_method, INFO_ALL, -1, -1, *args)
end
def info_mine(xml_method, *args)
return xmlrpc_info(xml_method, INFO_MINE, -1, -1, *args)
end
def info_group(xml_method, *args)
return xmlrpc_info(xml_method, INFO_GROUP, -1, -1, *args)
end
def info_primary_group(xml_method, *args)
return xmlrpc_info(xml_method, INFO_PRIMARY_GROUP, -1, -1, *args)
end
def info_filter(xml_method, who, start_id, end_id, *args)
return xmlrpc_info(xml_method, who, start_id, end_id, *args)
end
# Retrieves the monitoring data for all the Objects in the pool
#
# @param [String] xml_method xml-rcp method
# @param [Array<String>] xpath_expressions Elements to retrieve.
# @param args arguemnts for the xml_method call
#
# @return [Hash<String, <Hash<String, Array<Array<int>>>>>,
# OpenNebula::Error] The first level hash uses the Object ID as keys,
# and as value a Hash with the requested xpath expressions,
# and an Array of 'timestamp, value'.
def monitoring(xml_method, xpaths, *args)
rc = @client.call(xml_method, *args)
if ( OpenNebula.is_error?(rc) )
return rc
end
xmldoc = XMLElement.new
xmldoc.initialize_xml(rc, 'MONITORING_DATA')
hash = {}
# Get all existing Object IDs
ids = xmldoc.retrieve_elements('/MONITORING_DATA/MONITORING/ID')
if ids.nil?
return hash
else
ids.uniq!
end
ids.each { |id|
hash[id] = OpenNebula.process_monitoring(xmldoc, id, xpaths)
}
return hash
end
def monitoring_last(xml_method, *args)
rc = @client.call(xml_method, *args)
if OpenNebula.is_error?(rc)
return rc
end
xmldoc = XMLElement.new
xmldoc.initialize_xml(rc, 'MONITORING_DATA')
xmldoc.to_hash
end
private
# Calls to the corresponding info method to retreive the pool
# representation in XML format
# xml_method:: _String_ the name of the XML-RPC method
# args:: _Array_ with additional arguments for the info call
# [return] nil in case of success or an Error object
def xmlrpc_info(xml_method, *args)
rc = @client.call(xml_method, *args)
if !OpenNebula.is_error?(rc)
initialize_xml(rc, @pool_name)
rc = nil
end
return rc
end
public
# Constants for info queries (include/RequestManagerPoolInfoFilter.h)
INFO_GROUP = -1
INFO_ALL = -2
INFO_MINE = -3
INFO_PRIMARY_GROUP = -4
# Iterates over every PoolElement in the Pool and calls the block with a
# a PoolElement obtained calling the factory method
# block:: _Block_
def each(&block)
each_element(block) if @xml
end
# DO NOT USE - ONLY REXML BACKEND
def to_str
str = ""
REXML::Formatters::Pretty.new(1).write(@xml,str)
return str
end
# Gets a hash from a pool
#
# size:: nil => default page size
# < 2 => not paginated
# >=2 => page size
#
# The default page size can be changed with the environment variable
# ONE_POOL_PAGE_SIZE. Any value > 2 will set a page size, a non
# numeric value disables pagination.
def get_hash(size=nil)
allow_paginated = PAGINATED_POOLS.include?(@pool_name)
if OpenNebula.pool_page_size && allow_paginated &&
( ( size && size >= 2 ) || !size )
size = OpenNebula.pool_page_size if !size
hash = info_paginated(size)
return hash if OpenNebula.is_error?(hash)
{ @pool_name => { @element_name => hash } }
else
rc = info
return rc if OpenNebula.is_error?(rc)
to_hash
end
end
# Gets a pool in hash form using pagination
#
# size:: _Integer_ size of each page
def info_paginated(size)
array = Array.new
current = 0
parser = ParsePoolSax.new(@pool_name, @element_name)
while true
a = @client.call("#{@pool_name.delete('_').downcase}.info",
@user_id, current, -size, -1)
return a if OpenNebula.is_error?(a)
a_array=parser.parse(a)
array += a_array
current += size
break if !a || a_array.length<size
end
array.compact!
array = nil if array.length == 0
array
end
# Gets a hash from a info page from pool
# size:: nil => default page size
# > 0 => page size
# current first element of the page
# extended true to get extended information
# state state of the objects
# hash:: return page as a hash
def get_page(size, current, extended = false, state = -1)
rc = nil
state ||= -1
if PAGINATED_POOLS.include?(@pool_name)
pool_name = @pool_name.delete('_').downcase
if extended && pool_name == "vmpool"
method = "#{pool_name}.infoextended"
else
method = "#{pool_name}.info"
end
size = OpenNebula.pool_page_size if (!size || size == 0)
rc = @client.call(method, @user_id, current, -size, state)
return rc if OpenNebula.is_error?(rc)
initialize_xml(rc, @pool_name)
else
rc = info
end
return rc
end
# Iterates over pool page
def loop_page(size, state, extended)
current = 0
element = @pool_name.split('_')[0]
page = OpenNebula::XMLElement.new
loop do
rc = get_page(size, current, extended, state)
break rc if OpenNebula.is_error?(rc)
page.initialize_xml(rc, @pool_name)
break if page["//#{element}"].nil?
current += yield(element, page)
end
end
# Iterates over pool pages
# size:: nil => default page size
# > 0 => page size
# state state of objects
def each_page(size, state = -1, extended = false)
loop_page(size, state, extended) do |element, page|
page.each("//#{element}") do |obj|
yield(obj)
end
size
end
end
# Iterates over pool pages to delete them
# size:: nil => default page size
# > 0 => page size
# state state of objects
def each_page_delete(size, state = -1, extended = false)
loop_page(size, state, extended) do |element, page|
no_deleted = 0
page.each("//#{element}") do |obj|
no_deleted += 1 if !yield(obj)
end
no_deleted
end
end
# Return true if pool is paginated
def is_paginated?
PAGINATED_POOLS.include?(@pool_name)
end
end
end
| 32.555891 | 80 | 0.516518 |
7af7e9d70bcb8b09cf720b8de0bdc4a9897b18cc | 124 | require "devcamp_view_tool_vaibhavsfirstgem/version"
module DevcampViewToolVaibhavsfirstgem
# Your code goes here...
end
| 20.666667 | 52 | 0.83871 |
f77633b3e544ed5392b8c6cfd5a0b2435ed66713 | 348 | module SpreeRemoveBs3
module_function
# Returns the version of the currently loaded SpreeRemoveBs3 as a
# <tt>Gem::Version</tt>.
def version
Gem::Version.new VERSION::STRING
end
module VERSION
MAJOR = 0
MINOR = 0
TINY = 1
PRE = 'alpha'.freeze
STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
| 18.315789 | 67 | 0.649425 |
873ffb68888567a24293cd462cb86b5066d4efa3 | 1,251 | # encoding: utf-8
module Mutant
class Mutator
class Node
# Mutator for case nodes
class Case < self
handle(:case)
children :condition
private
# Emit mutations
#
# @return [undefined]
#
# @api private
#
def dispatch
emit_condition_mutations
emit_when_mutations
emit_else_mutations
emit_nil
end
# Emit when mutations
#
# @return [undefined]
#
# @api private
#
def emit_when_mutations
indices = children.each_index.drop(1).take(children.length - 2)
one = indices.one?
indices.each do |index|
mutate_child(index)
delete_child(index) unless one
end
end
# Emit else mutations
#
# @return [undefined]
#
# @api private
#
def emit_else_mutations
else_branch = children.last
else_index = children.length - 1
if else_branch
mutate_child(else_index)
emit_child_update(else_index, nil)
end
end
end # Case
end # Node
end # Mutator
end # Mutant
| 19.857143 | 73 | 0.513189 |
4adf76b6f1e95f5f595373c9da7e93328c94a172 | 814 | require "spring/watcher"
module Spring
@commands = {}
class << self
attr_reader :commands
end
def self.register_command(name, klass)
commands[name] = klass
end
def self.command?(name)
commands.include? name
end
def self.command(name)
commands.fetch name
end
require "spring/commands/rails"
require "spring/commands/rake"
require "spring/commands/testunit"
require "spring/commands/rspec"
require "spring/commands/cucumber"
# If the config/spring.rb contains requires for commands from other gems,
# then we need to be under bundler.
require "bundler/setup"
# Load custom commands, if any.
# needs to be at the end to allow modification of existing commands.
config = File.expand_path("./config/spring.rb")
require config if File.exist?(config)
end
| 22 | 75 | 0.718673 |
e971af9b5c2776a2a670d1f60c109846bd99e36d | 1,127 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20190317155758) do
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.string "remember_digest"
t.boolean "admin", default: false
t.index ["email"], name: "index_users_on_email", unique: true
end
end
| 41.740741 | 86 | 0.755102 |
399a6884474d5dc0698df116ad55edb43fc6b535 | 830 | require 'pact/symbolize_keys'
module Pact
# Specifies that the actual object should be considered a match if
# it includes the same keys, and the values of the keys are of the same class.
class SomethingLike
include SymbolizeKeys
attr_reader :contents
def initialize contents
@contents = contents
end
def to_hash
{
:json_class => self.class.name,
:contents => contents
}
end
def as_json opts = {}
to_hash
end
def to_json opts = {}
as_json.to_json opts
end
def self.json_create hash
new(symbolize_keys(hash)[:contents])
end
def eq other
self == other
end
def == other
other.is_a?(SomethingLike) && other.contents == self.contents
end
def generate
contents
end
end
end
| 16.6 | 80 | 0.624096 |
7a3d33be863ec341a3288d9bd999b6c8ea284313 | 1,291 | $:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "topological_inventory/core/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "topological_inventory-core"
s.version = TopologicalInventory::Core::VERSION
s.authors = ["Adam Grare"]
s.email = ["[email protected]"]
s.homepage = "https://github.com/ManageIQ/topological_inventory-core"
s.summary = "Core Models and Schema for the Topological Inventory Service."
s.description = "Core Models and Schema for the Topological Inventory Service.."
s.license = "Apache-2.0"
s.files = Dir["{app,config,db,lib}/**/*", "LICENSE.txt", "Rakefile", "README.md"]
s.add_runtime_dependency "acts_as_tenant"
s.add_runtime_dependency "inventory_refresh", "~> 0.3.0"
s.add_runtime_dependency "manageiq-messaging", "~> 0.1.0"
s.add_runtime_dependency "manageiq-password", "~> 0.3"
s.add_runtime_dependency "pg", "> 0"
s.add_runtime_dependency "rails", "~> 5.2.2"
s.add_runtime_dependency "rest-client", ">= 1.8.0"
s.add_development_dependency "active_record_doctor"
s.add_development_dependency "rspec-rails", "~>3.8"
s.add_development_dependency "simplecov"
s.add_development_dependency "webmock"
end
| 40.34375 | 83 | 0.714175 |
e90592a2914b64fcf44e02d872d18dbe9a2b17d0 | 1,492 | module Codekraft
module Api
module Service
class SubscriptionService < Base
def initialize
super(Codekraft::Api::Model::Subscription)
end
def fetchAll params
params[:user] = @current_user
subscriptions = super(params).to_a
if subscriptions.size > 0
notifications_descs = Codekraft::Api::Model::NotificationDesc.where("id not in (?)", subscriptions.map{ |sub| sub.notification_desc_id })
else
notifications_descs = Codekraft::Api::Model::NotificationDesc.all
end
notifications_descs.each do |desc|
subscriptions.push Codekraft::Api::Model::Subscription.new({user: @current_user, notification_desc_id: desc.id, email_push: true, mobile_push: true})
end
{
subscriptions: subscriptions.map { |sub| Codekraft::Api::Serializer::SubscriptionSerializer.new(sub, {root: false}) }
}
end
def toggle params
subscription = @model.find_by(user: @current_user, notification_desc_id: params[:notification_desc_id])
if subscription.nil?
subscription = Codekraft::Api::Model::Subscription.create!({user: @current_user, notification_desc_id: params[:notification_desc_id], email_push: true, mobile_push: true})
end
subscription[params[:type]] = !subscription[params[:type]]
subscription.save!
subscription
end
end
end
end
end
| 35.52381 | 183 | 0.644772 |
5d4047f779abda3270258a9ba4a1ff9b9fa327ec | 2,645 | #!/usr/bin/env ruby
# Copyright (C) 2012-2014 Open Source Robotics Foundation
# 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.
# Description:
# This script removes old snapshots of the gazebosim.org server, and creates
# a new snapshot if the most recent snapshot is older than 1 day. Snapshots
# are removed if they are older than one week.
#
# A cronjob runs on gazebosim.org that assumes this file is located in /home/ubuntu/bin/
require 'rubygems'
require 'net/http'
require 'net/ssh'
require 'aws-sdk'
if ARGV.size < 2
puts "backup.rb <access_key> <secret_key>"
abort("")
end
# Two weeks in seconds
two_weeks = 2*7*24*60*60
# One day in seconds
one_day = 24*60*60
# Timestamp of the last snapshot
last_snapshot = 0
AWS.config(
:access_key_id => ARGV[0],
:secret_access_key => ARGV[1])
ec2 = AWS::EC2.new
# Find old gazebo sim snapshots
ec2.snapshots.filter("tag:Name","gazebosim.org").each {|snapshot|
# Only consider snapshot with Name == gazebosim.org
if snapshot.tags["Name"] == "gazebosim.org"
# Only delete a snap shot if it's older than two weeks.
if Time.now.to_i - snapshot.tags["Time"].to_i > two_weeks
puts "Deleting snapshot with id #{snapshot.id}"
snapshot.delete
else
# Store the timestamp of the most recent snapshot
last_snapshot = [last_snapshot, snapshot.tags["Time"].to_i].max
end
end
}
# Create a new snapshot if the most recent snapshot is older than one day.
if Time.now.to_i - last_snapshot >= one_day
# Find the gazebosim volume
ec2.volumes.each {|volume|
# Only consider volumes that are in use
if volume.status == :in_use
volume.attachments.each {|attachment|
# Check for the gazebosim.org name
if attachment.status == :attached &&
attachment.instance.tags["Name"] == "gazebosim.org"
# Create a snapshot
puts "Creating snapshot of gazebosim volume id #{volume.id}"
snapshot = volume.create_snapshot("gazebosim_#{Time.now.to_i}")
snapshot.tags.Name = "gazebosim.org"
snapshot.add_tag("Time", :value => "#{Time.now.to_i}")
end
}
end
}
end
| 30.755814 | 88 | 0.697921 |
5d248f54ea806ca07b67dc444f2bb7484d24c0d1 | 444 | # frozen_string_literal: true
require 'spec_helper'
require 'vk/api/notes/responses/get_comments_response'
RSpec.describe Vk::API::Notes::Responses::GetCommentsResponse do
subject(:model) { described_class }
it { is_expected.to be < Dry::Struct }
it { is_expected.to be < Vk::Schema::Response }
describe 'attributes' do
subject(:attributes) { model.instance_methods(false) }
it { is_expected.to include :response }
end
end
| 27.75 | 64 | 0.738739 |
1a478205608303d1ba4438609e07d0dd574ef4bf | 59 | class CustomSessionsController < ApplicationController
end
| 19.666667 | 54 | 0.898305 |
283ed1e9a59c47356e32f6a0f5356d219c03e2c6 | 7,690 | class SphinxDoc < Formula
include Language::Python::Virtualenv
desc "Tool to create intelligent and beautiful documentation"
homepage "https://www.sphinx-doc.org/"
url "https://files.pythonhosted.org/packages/f6/3a/c51fc285c0c5c30bcd9426bf096187840683d9383df716a6b6a4ca0a8bde/Sphinx-2.2.1.tar.gz"
sha256 "31088dfb95359384b1005619827eaee3056243798c62724fd3fa4b84ee4d71bd"
bottle do
cellar :any_skip_relocation
root_url "https://homebrew.bintray.com/bottles"
sha256 "bafdefa981b741cd27cc0ec74d6661134230aadd10bd43469d4ab0b43e2a1a11" => :catalina
sha256 "1b0f273578e576fa1cbf78610b9f34cd47de8615c92f1622762832b11e9f8ab9" => :mojave
sha256 "f185f0fce2824534a4c2662315e2a63ba043fdd34f1fe72b4a4b49fb5fad8b08" => :high_sierra
end
keg_only <<~EOS
this formula is mainly used internally by other formulae.
Users are advised to use `pip` to install sphinx-doc
EOS
depends_on "troyliu0105/caffe/python"
# generated from sphinx, numpydoc and python-docs-theme
resource "alabaster" do
url "https://files.pythonhosted.org/packages/cc/b4/ed8dcb0d67d5cfb7f83c4d5463a7614cb1d078ad7ae890c9143edebbf072/alabaster-0.7.12.tar.gz"
sha256 "a661d72d58e6ea8a57f7a86e37d86716863ee5e92788398526d58b26a4e4dc02"
end
resource "Babel" do
url "https://files.pythonhosted.org/packages/bd/78/9fb975cbb3f4b136de2cd4b5e5ce4a3341169ebf4c6c03630996d05428f1/Babel-2.7.0.tar.gz"
sha256 "e86135ae101e31e2c8ec20a4e0c5220f4eed12487d5cf3f78be7e98d3a57fc28"
end
resource "certifi" do
url "https://files.pythonhosted.org/packages/06/b8/d1ea38513c22e8c906275d135818fee16ad8495985956a9b7e2bb21942a1/certifi-2019.3.9.tar.gz"
sha256 "b26104d6835d1f5e49452a26eb2ff87fe7090b89dfcaee5ea2212697e1e1d7ae"
end
resource "chardet" do
url "https://files.pythonhosted.org/packages/fc/bb/a5768c230f9ddb03acc9ef3f0d4a3cf93462473795d18e9535498c8f929d/chardet-3.0.4.tar.gz"
sha256 "84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae"
end
resource "docutils" do
url "https://files.pythonhosted.org/packages/84/f4/5771e41fdf52aabebbadecc9381d11dea0fa34e4759b4071244fa094804c/docutils-0.14.tar.gz"
sha256 "51e64ef2ebfb29cae1faa133b3710143496eca21c530f3f71424d77687764274"
end
resource "idna" do
url "https://files.pythonhosted.org/packages/ad/13/eb56951b6f7950cadb579ca166e448ba77f9d24efc03edd7e55fa57d04b7/idna-2.8.tar.gz"
sha256 "c357b3f628cf53ae2c4c05627ecc484553142ca23264e593d327bcde5e9c3407"
end
resource "imagesize" do
url "https://files.pythonhosted.org/packages/41/f5/3cf63735d54aa9974e544aa25858d8f9670ac5b4da51020bbfc6aaade741/imagesize-1.1.0.tar.gz"
sha256 "f3832918bc3c66617f92e35f5d70729187676313caa60c187eb0f28b8fe5e3b5"
end
resource "Jinja2" do
url "https://files.pythonhosted.org/packages/93/ea/d884a06f8c7f9b7afbc8138b762e80479fb17aedbbe2b06515a12de9378d/Jinja2-2.10.1.tar.gz"
sha256 "065c4f02ebe7f7cf559e49ee5a95fb800a9e4528727aec6f24402a5374c65013"
end
resource "MarkupSafe" do
url "https://files.pythonhosted.org/packages/b9/2e/64db92e53b86efccfaea71321f597fa2e1b2bd3853d8ce658568f7a13094/MarkupSafe-1.1.1.tar.gz"
sha256 "29872e92839765e546828bb7754a68c418d927cd064fd4708fab9fe9c8bb116b"
end
resource "numpydoc" do
url "https://files.pythonhosted.org/packages/6a/f3/7cfe4c616e4b9fe05540256cc9c6661c052c8a4cec2915732793b36e1843/numpydoc-0.9.1.tar.gz"
sha256 "e08f8ee92933e324ff347771da15e498dbf0bc6295ed15003872b34654a0a627"
end
resource "packaging" do
url "https://files.pythonhosted.org/packages/16/51/d72654dbbaa4a4ffbf7cb0ecd7d12222979e0a660bf3f42acc47550bf098/packaging-19.0.tar.gz"
sha256 "0c98a5d0be38ed775798ece1b9727178c4469d9c3b4ada66e8e6b7849f8732af"
end
resource "Pygments" do
url "https://files.pythonhosted.org/packages/7e/ae/26808275fc76bf2832deb10d3a3ed3107bc4de01b85dcccbe525f2cd6d1e/Pygments-2.4.2.tar.gz"
sha256 "881c4c157e45f30af185c1ffe8d549d48ac9127433f2c380c24b84572ad66297"
end
resource "pyparsing" do
url "https://files.pythonhosted.org/packages/5d/3a/24d275393f493004aeb15a1beae2b4a3043526e8b692b65b4a9341450ebe/pyparsing-2.4.0.tar.gz"
sha256 "1873c03321fc118f4e9746baf201ff990ceb915f433f23b395f5580d1840cb2a"
end
resource "python-docs-theme" do
url "https://files.pythonhosted.org/packages/77/f9/8c63766fe271549db3a578b652dea6678b90b593300315507b9c922f7173/python-docs-theme-2018.7.tar.gz"
sha256 "018a5bf2a7318c9c9a8346303dac8afc6bc212d92e86561c9b95a3372714155a"
end
resource "pytz" do
url "https://files.pythonhosted.org/packages/df/d5/3e3ff673e8f3096921b3f1b79ce04b832e0100b4741573154b72b756a681/pytz-2019.1.tar.gz"
sha256 "d747dd3d23d77ef44c6a3526e274af6efeb0a6f1afd5a69ba4d5be4098c8e141"
end
resource "requests" do
url "https://files.pythonhosted.org/packages/01/62/ddcf76d1d19885e8579acb1b1df26a852b03472c0e46d2b959a714c90608/requests-2.22.0.tar.gz"
sha256 "11e007a8a2aa0323f5a921e9e6a2d7e4e67d9877e85773fba9ba6419025cbeb4"
end
resource "six" do
url "https://files.pythonhosted.org/packages/dd/bf/4138e7bfb757de47d1f4b6994648ec67a51efe58fa907c1e11e350cddfca/six-1.12.0.tar.gz"
sha256 "d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73"
end
resource "snowballstemmer" do
url "https://files.pythonhosted.org/packages/20/6b/d2a7cb176d4d664d94a6debf52cd8dbae1f7203c8e42426daa077051d59c/snowballstemmer-1.2.1.tar.gz"
sha256 "919f26a68b2c17a7634da993d91339e288964f93c274f1343e3bbbe2096e1128"
end
resource "sphinxcontrib-applehelp" do
url "https://files.pythonhosted.org/packages/1b/71/8bafa145e48131049dd4f731d6f6eeefe0c34c3017392adbec70171ad407/sphinxcontrib-applehelp-1.0.1.tar.gz"
sha256 "edaa0ab2b2bc74403149cb0209d6775c96de797dfd5b5e2a71981309efab3897"
end
resource "sphinxcontrib-devhelp" do
url "https://files.pythonhosted.org/packages/57/5f/bf9a0f7454df68a7a29033a5cf8d53d0797ae2e426b1b419e4622726ec7d/sphinxcontrib-devhelp-1.0.1.tar.gz"
sha256 "6c64b077937330a9128a4da74586e8c2130262f014689b4b89e2d08ee7294a34"
end
resource "sphinxcontrib-htmlhelp" do
url "https://files.pythonhosted.org/packages/f1/f2/88e9d6dc4a17f1e95871f8b634adefcc5d691334f7a121e9f384d1dc06fd/sphinxcontrib-htmlhelp-1.0.2.tar.gz"
sha256 "4670f99f8951bd78cd4ad2ab962f798f5618b17675c35c5ac3b2132a14ea8422"
end
resource "sphinxcontrib-jsmath" do
url "https://files.pythonhosted.org/packages/b2/e8/9ed3830aeed71f17c026a07a5097edcf44b692850ef215b161b8ad875729/sphinxcontrib-jsmath-1.0.1.tar.gz"
sha256 "a9925e4a4587247ed2191a22df5f6970656cb8ca2bd6284309578f2153e0c4b8"
end
resource "sphinxcontrib-qthelp" do
url "https://files.pythonhosted.org/packages/0c/f0/690cd10603e3ea8d184b2fffde1d965dd337b87a1d5f7625d0f6791094f4/sphinxcontrib-qthelp-1.0.2.tar.gz"
sha256 "79465ce11ae5694ff165becda529a600c754f4bc459778778c7017374d4d406f"
end
resource "sphinxcontrib-serializinghtml" do
url "https://files.pythonhosted.org/packages/cd/cc/fd7d17cfae18e5a92564bb899bc05e13260d7a633f3cffdaad4e5f3ce46a/sphinxcontrib-serializinghtml-1.1.3.tar.gz"
sha256 "c0efb33f8052c04fd7a26c0a07f1678e8512e0faec19f4aa8f2473a8b81d5227"
end
resource "urllib3" do
url "https://files.pythonhosted.org/packages/4c/13/2386233f7ee40aa8444b47f7463338f3cbdf00c316627558784e3f542f07/urllib3-1.25.3.tar.gz"
sha256 "dbe59173209418ae49d485b87d1681aefa36252ee85884c31346debd19463232"
end
def install
virtualenv_install_with_resources
end
test do
system bin/"sphinx-quickstart", "-pPorject", "-aAuthor", "-v1.0", "-q", testpath
system bin/"sphinx-build", testpath, testpath/"build"
assert_predicate testpath/"build/index.html", :exist?
end
end
| 48.0625 | 159 | 0.825098 |
7ab0701f9248879ca72e88b1cc2b63ec8b62a504 | 4,357 | require 'rails_helper'
RSpec.describe PostsController, type: :controller do
before do
@bob = User.create(
email: '[email protected]',
first_name: 'bob',
last_name: 'sinclair',
password: 'secret',
password_confirmation: 'secret'
)
sign_in(@bob)
end
describe '#index' do
before do
@posts = @bob
.feed
.recents
.paginate(page: @controller.params[:page], per_page: 10)
@first_half = @posts.first(5)
@second_half = @posts.offset(5).first(5)
@combined = @first_half + @second_half
@title = 'Your feed'
get :index
end
it 'GETs' do
expect(response).to have_http_status(:success)
end
it 'sets @posts' do
expect(assigns(:posts)).to eq(@posts)
end
it 'sets @first_half' do
expect(assigns(:first_half)).to eq(@first_half)
end
it 'sets @second_half' do
expect(assigns(:second_half)).to eq(@second_half)
end
it 'sets @title' do
expect(assigns(:title)).to eq(@title)
end
end
describe '#new' do
before do
get :new
end
it 'GETs' do
expect(response).to have_http_status(:success)
end
it 'sets @post as a new Post' do
expect(assigns(:post)).to be_a_new(Post)
end
end
describe '#show' do
before do
@post = @bob.posts.create(
title: 'Bob wrote this',
content: 'Whatever'
)
get :show, params: { id: @post.id }
end
it 'GETs' do
expect(response).to have_http_status(:success)
end
it 'sets @post' do
expect(assigns(:post)).to eq(@post)
end
it 'sets @comments' do
expect(assigns(:comments)).to eq(@post.comments.order('created_at DESC'))
end
end
describe '#edit' do
before do
@post = @bob.posts.create(
title: 'Bob wrote this',
content: 'Whatever'
)
get :edit, params: { id: @post.id }
end
it 'GETs' do
expect(response).to have_http_status(:success)
end
it 'sets @post' do
expect(assigns(:post)).to eq(@post)
end
end
describe '#update' do
before do
@post = @bob.posts.create(
title: 'Bob wrote this',
content: 'Whatever'
)
patch :update, params: { id: @post.id, post: { title: 'Bob is cool' } }
end
it 'redirects' do
expect(response).to have_http_status(:redirect)
end
it 'redirects to #show' do
expect(response).to redirect_to(post_path(@post))
end
it 'sets @post' do
expect(assigns(:post)).to eq(@post)
end
it 'changes the data' do
expect(assigns(:post).title).to eq('Bob is cool')
end
it 'sets flash[:success]' do
expect(@controller.flash[:success]).to eq('Post updated')
end
end
describe '#destroy' do
before do
@post = @bob.posts.create(
title: 'Bob wrote this',
content: 'Whatever'
)
@id = @post.id
@count = Post.count
delete :destroy, params: { id: @post.id }
end
it 'redirects' do
expect(response).to have_http_status(:redirect)
end
it 'redirects to root' do
expect(response).to redirect_to(root_path)
end
it 'sets @post' do
expect(assigns(:post)).to eq(@post)
end
it 'deletes the post' do
expect(Post.count).to eq(@count - 1)
expect(Post.find_by(id: @id)).to be_nil
end
it 'sets flash[:success]' do
expect(@controller.flash[:success]).to eq('Post deleted')
end
end
describe '#create' do
before do
post(
:create,
params: {
post: {
title: 'Bob wrote this',
content: 'Whatever'
}
}
)
@post = Post.new(title: 'Bob wrote this', content: 'Whatever')
end
it 'redirects' do
expect(response).to have_http_status(:redirect)
end
it 'redirect to #show' do
expect(response).to redirect_to(post_path(assigns(:post)))
end
it 'sets @post as a new post' do
expect(assigns(:post)).not_to be_nil
end
it 'sets flash[:success]' do
expect(@controller.flash[:success]).to eq('Post created')
end
it 'sets @post attributes' do
expect(assigns(:post).title).to eq(@post.title)
expect(assigns(:post).content).to eq(@post.content)
end
end
end
| 20.84689 | 79 | 0.578839 |
6a5d483dcf8ab0e1efb0c21b6671feee992767f4 | 2,327 | # 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.
#
# This file is the source Rails uses to define your schema when running `rails
# db:schema:load`. When creating a new database, `rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_04_18_091824) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "microposts", force: :cascade do |t|
t.text "content"
t.bigint "user_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.string "picture"
t.index ["user_id", "created_at"], name: "index_microposts_on_user_id_and_created_at"
t.index ["user_id"], name: "index_microposts_on_user_id"
end
create_table "relationships", force: :cascade do |t|
t.integer "follower_id"
t.integer "followed_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["followed_id"], name: "index_relationships_on_followed_id"
t.index ["follower_id", "followed_id"], name: "index_relationships_on_follower_id_and_followed_id", unique: true
t.index ["follower_id"], name: "index_relationships_on_follower_id"
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.string "password_digest"
t.string "remember_digest"
t.boolean "admin", default: false
t.string "activation_digest"
t.boolean "activated", default: false
t.datetime "activated_at"
t.string "reset_digest"
t.datetime "reset_sent_at"
t.index ["email"], name: "index_users_on_email", unique: true
end
add_foreign_key "microposts", "users"
end
| 41.553571 | 116 | 0.73743 |
39f1c4126b34a0e82aa1f75d5e07c3d6b5759db0 | 7,281 | # == Schema Information
#
# Table name: user_stories
#
# id :integer not null, primary key
# name :string
# description :string
# acceptance_condition :string
# priority :integer
# effort :integer
# status :integer default("unnasigned")
# is_task :boolean default(FALSE)
# finished_date :datetime
# product_backlog_id :integer
# sprint_backlog_id :integer
# epic_id :integer
# theme_id :integer
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class UserStoriesController < ApplicationController
before_action :authenticate_user!
before_action :set_user_story_and_product_backlog, only: [:edit, :update, :destroy]
def new
@user_story = UserStory.new
@product_backlog = ProductBacklog.find(params[:product_backlog_id])
@project = @product_backlog.project
@efforts = [1,2,3,5,8,13,21,34]
@themes = @product_backlog.project.themes
@epics = @product_backlog.project.epics
@available_sprints = Sprint.where(["project_id = ?", @product_backlog.project.id]).where(:status => :created)
end
def create
if request.post?
begin
@product_backlog = ProductBacklog.find(params[:product_backlog_id])
@user_story = UserStory.new(user_story_params)
@user_story.save!
if params[:sprint_id] && !params[:sprint_id].empty?
sprint = Sprint.find(params[:sprint_id])
@user_story.assign
@user_story.update_column(:sprint_backlog_id, sprint.sprint_backlog.id)
@user_story.save!
sprint.sprint_backlog.user_stories << @user_story
end
@product_backlog.user_stories << @user_story
@project = @product_backlog.project
@mvp_themes = Hash.new
@theme_user_story = Hash.new
@themes = @project.themes.select { |theme| theme.status == "active" }
@themes.each do |theme|
@theme_user_story[theme.id] = theme.user_stories.select { |user_story| user_story.status == "unnasigned" }
@mvp_themes[theme.id] = UserStory.gethighestpriority(@theme_user_story[theme.id])
end
@mvp_epics = Hash.new
@epic_user_story = Hash.new
@epics = @project.epics.select { |epic| epic.status == "active" }
@epics.each do |epic|
@epic_user_story[epic.id] = epic.user_stories.select { |user_story| user_story.status == "unnasigned" }
@mvp_epics[epic.id] = UserStory.gethighestpriority(@epic_user_story[epic.id])
end
icebox_user_stories = @product_backlog.user_stories.where(:epic_id => nil).where(:theme_id => nil)
@icebox_user_stories = icebox_user_stories.select { |user_story| user_story.status == "unnasigned" }
@mvp_user_story = UserStory.gethighestpriority(@product_backlog.user_stories)
flash[:notice] = "User story successfully created"
redirect_to product_backlog_show_path(:id => @project.id)
rescue Exception => e
flash[:alert] = "Cannot create user story #{params[:user_story][:name]}. Reason: #{e}. Please try again."
flash.keep(:alert)
# product_backlog = ProductBacklog.find(params[:user_story][:product_backlog_id])
redirect_to product_backlog_show_path(:id => @product_backlog.id)
end
end
end
def edit
@efforts = [1,2,3,5,8,13,21,34]
@themes = @product_backlog.project.themes
@epics = @product_backlog.project.epics
@available_sprints = Sprint.where(["project_id = ?", @product_backlog.project.id]).where(:status => :created)
end
def update
begin
@user_story.update_attributes!(user_story_params)
if params[:sprint_id]
@sprint = Sprint.find(params[:sprint_id])
@sprint_backlog = @sprint.sprint_backlog
if !@user_story.sprint_backlog.nil?
# cleanup..
previous_sprint_backlog = @user_story.sprint_backlog
previous_sprint_backlog.user_stories.delete(@user_story)
@user_story.sprint_backlog = nil
end
@user_story.update_column(:sprint_backlog_id, @sprint_backlog.id)
@user_story.assign
@user_story.save!
@sprint_backlog.user_stories << @user_story
end
@mvp_themes = Hash.new
@theme_user_story = Hash.new
@themes = @project.themes.select { |theme| theme.status == "active" }
@themes.each do |theme|
@theme_user_story[theme.id] = theme.user_stories.select { |user_story| user_story.status == "unnasigned" }
@mvp_themes[theme.id] = UserStory.gethighestpriority(@theme_user_story[theme.id])
end
@mvp_epics = Hash.new
@epic_user_story = Hash.new
@epics = @project.epics.select { |epic| epic.status == "active" }
@epics.each do |epic|
@epic_user_story[epic.id] = epic.user_stories.select { |user_story| user_story.status == "unnasigned" }
@mvp_epics[epic.id] = UserStory.gethighestpriority(@epic_user_story[epic.id])
end
icebox_user_stories = @product_backlog.user_stories.where(:epic_id => nil).where(:theme_id => nil)
@icebox_user_stories = icebox_user_stories.select { |user_story| user_story.status == "unnasigned" }
@mvp_user_story = UserStory.gethighestpriority(@product_backlog.user_stories)
flash[:notice] = "User story #{@user_story.name} successfully updated"
redirect_to product_backlog_show_path(:id => @product_backlog.project_id)
rescue Exception => e
flash[:alert] = "Cannot update user story #{@user_story.name}. Reason: #{e}.Please try again."
flash.keep(:alert)
product_backlog = ProductBacklog.find(params[:user_story][:product_backlog_id])
redirect_to product_backlog_show_path(:id => product_backlog.project_id)
end
end
def destroy
@user_story.set_inactive
@user_story.save!
@mvp_themes = Hash.new
@theme_user_story = Hash.new
@themes = @project.themes.select { |theme| theme.status == "active" }
@themes.each do |theme|
@theme_user_story[theme.id] = theme.user_stories.select { |user_story| user_story.status == "unnasigned" }
@mvp_themes[theme.id] = UserStory.gethighestpriority(@theme_user_story[theme.id])
end
@mvp_epics = Hash.new
@epic_user_story = Hash.new
@epics = @project.epics.select { |epic| epic.status == "active" }
@epics.each do |epic|
@epic_user_story[epic.id] = epic.user_stories.select { |user_story| user_story.status == "unnasigned" }
@mvp_epics[epic.id] = UserStory.gethighestpriority(@epic_user_story[epic.id])
end
icebox_user_stories = @product_backlog.user_stories.where(:epic_id => nil).where(:theme_id => nil)
@icebox_user_stories = icebox_user_stories.select { |user_story| user_story.status == "unnasigned" }
@mvp_user_story = UserStory.gethighestpriority(@product_backlog.user_stories)
flash[:notice] = "User story destroyed"
redirect_back(fallback_location: projects_path)
end
private
def set_user_story_and_product_backlog
@user_story = UserStory.find(params[:id])
@product_backlog = ProductBacklog.find(@user_story.product_backlog_id)
@project = @product_backlog.project
end
def user_story_params
params.require(:user_story).permit(:name, :description, :effort, :priority,
:product_backlog_id, :sprint_backlog_id, :epic_id, :theme_id, :acceptance_condition, documents_files: [])
end
end
| 40.45 | 113 | 0.699354 |
5dd10d80057d4081030d180d6896dcfdd8453e5b | 705 | #!/usr/bin/env ruby
$LOAD_PATH << File.join(__dir__, "../lib")
require "set"
IS_LATEST_RUBY = Gem::Version.new(RUBY_VERSION).yield_self do |ruby_version|
Gem::Version.new('3.0.0') <= ruby_version && ruby_version < Gem::Version.new('3.1.0')
end
unless IS_LATEST_RUBY
unless ENV["CI"]
STDERR.puts "⚠️⚠️⚠️⚠️ stdlib test assumes Ruby 3.0 but RUBY_VERSION==#{RUBY_VERSION} ⚠️⚠️⚠️⚠️"
end
end
KNOWN_FAILS = %w(dbm).map do |lib|
/cannot load such file -- #{lib}/
end
ARGV.each do |arg|
begin
load arg
rescue LoadError => exn
if KNOWN_FAILS.any? {|pat| pat =~ exn.message }
STDERR.puts "Loading #{arg} failed, ignoring it: #{exn.inspect}"
else
raise
end
end
end
| 22.03125 | 98 | 0.64539 |
0138a0f39ffbf4c417878e00517cae339ffe61c3 | 7,849 | require "plugin"
########################################################
# Author: Almudena Bocinos Rioboo
#
# Defines the main methods that are necessary to execute PluginAdapters
# Inherit: Plugin
########################################################
class PluginAbAdapters < Plugin
# adapters found at end of sequence are even 2 nt wide, cut in 5 because of statistics
MIN_ADAPTER_SIZE = 5
MIN_FAR_ADAPTER_SIZE = 13
MIN_LEFT_ADAPTER_SIZE = 9
def do_blasts(seqs)
# find MIDS with less results than max_target_seqs value
blast=BatchBlast.new("-db #{@params.get_param('adapters_ab_db')}",'blastn'," -task blastn-short -perc_identity #{@params.get_param('blast_percent_ab')} -word_size #{MIN_ADAPTER_SIZE}")
# con culling limit hay situaciones en las que un hit largo con 1 mismatch es ignorado porque hay otro más corto que no tiene ningun error, no es aceptable.
#blast=BatchBlast.new("-db #{@params.get_param('adapters_ab_db')}",'blastn'," -task blastn-short -perc_identity #{@params.get_param('blast_percent_ab')} -word_size #{MIN_ADAPTER_SIZE} -culling_limit=1")
$LOG.debug('BLAST:'+blast.get_blast_cmd)
fastas=[]
seqs.each do |seq|
fastas.push ">"+seq.seq_name
fastas.push seq.seq_fasta
end
# fastas=fastas.join("\n")
#blast_table_results = blast.do_blast(fastas)
#blast_table_results = BlastTableResult.new(blast_table_results)
t1=Time.now
blast_table_results = blast.do_blast(fastas,:table,false)
add_plugin_stats('execution_time','blast',Time.now-t1)
#f=File.new("/tmp/salida_#{fastas.first.gsub('>','').gsub('/','_')}.blast",'w+')
#f.puts blast.get_blast_cmd
#f.puts blast_table_results
#f.close
t1=Time.now
blast_table_results = BlastTableResult.new(blast_table_results)
add_plugin_stats('execution_time','parse',Time.now-t1)
# t1=Time.now
# blast_table_results = blast.do_blast(fastas,:xml,false)
# add_plugin_stats('execution_time','blast',Time.now-t1)
# t1=Time.now
# blast_table_results = BlastStreamxmlResult.new(blast_table_results)
# add_plugin_stats('execution_time','parse',Time.now-t1)
# puts blast_table_results.inspect
return blast_table_results
end
# filter hits that are far the extreme and do not have a valid length
def filter_hits(hits,end_pos)
hits.reverse_each do |hit|
if (hit.q_end < (end_pos-40)) && ((hit.q_end-hit.q_beg+1)<(@params.get_ab_adapter(hit.subject_id).length*0.80).to_i)
hits.delete(hit)
# puts "DELETE #{hit.inspect}"
# else
# puts "ACCEPTED #{hit.inspect}, >= #{(@params.get_ab_adapter(hit.subject_id).length*0.2).to_i}"
end
end
end
def exec_seq(seq,blast_query)
if blast_query.query_id != seq.seq_name
raise "Blast and seq names does not match, blast:#{blast_query.query_id} sn:#{seq.seq_name}"
end
$LOG.debug "[#{self.class.to_s}, seq: #{seq.seq_name}]: looking for adapters into the sequence"
# blast=BatchBlast.new("-db #{File.join($FORMATTED_DB_PATH,'adapters_ab.fasta')}",'blastn'," -task blastn-short -evalue #{@params.get_param('blast_evalue_ab')} -perc_identity #{@params.get_param('blast_percent_ab')} -word_size #{MIN_ADAPTER_SIZE}")
# blast with only one sequence, no with many sequences from a database
#---------------------------------------------------------------------
# blast_table_results = blast.do_blast(seq.seq_fasta) #rise seq to adapterss executing over blast
#BlastTableResult.new(res)
# puts blast_query.inspect
# puts blast_table_results.inspect
filter_hits(blast_query.hits, seq.seq_fasta.length)
adapters=[]
# blast_table_results.querys.each do |query| # first round to save adapters without overlap
merge_hits(blast_query.hits,adapters)
# end
begin
adapters2=adapters # second round to save adapters without overlap
adapters = []
merge_hits(adapters2,adapters)
end until (adapters2.count == adapters.count)
# puts "MERGED"
# puts "="*50
# adapters.each {|a| puts a.inspect}
[email protected]_param('max_ab_to_end').to_i
# type = 'ActionAbAdapter'
actions=[]
adapter_size=0
#@stats['adapter_size']={}
adapters.each do |c| # adds the correspondent action to the sequence
# puts "is the adapter near to the end of sequence ? #{c.q_end+seq.insert_start+max_to_end} >= ? #{seq.seq_fasta_orig.size-1}"
adapter_size=c.q_end-c.q_beg+1
#if ((c.q_end+seq.insert_start+max_to_end)>=seq.seq_fasta_orig.size-1)
right_action = true
#if ab adapter is very near to the end of original sequence
if c.q_end>=seq.seq_fasta.length-max_to_end
message = c.subject_id
type = 'ActionAbAdapter'
ignore=false
add_stats('adapter_type','normal')
elsif (c.q_beg <= 4) && (adapter_size>=MIN_LEFT_ADAPTER_SIZE) #left adapter
message = c.subject_id
type = 'ActionAbLeftAdapter'
ignore = false
right_action = false
add_stats('adapter_type','left')
elsif (adapter_size>=MIN_FAR_ADAPTER_SIZE)
message = c.subject_id
type = 'ActionAbFarAdapter'
ignore = false
add_stats('adapter_type','far')
else
ignore=true
end
if !ignore
a = seq.new_action(c.q_beg,c.q_end,type)
a.message = message
a.reversed = c.reversed
if right_action
a.right_action = true #mark as rigth action to get the left insert
else
a.left_action = true
end
actions.push a
# puts "adapter_size #{adapter_size}"
#@stats[:adapter_size]={adapter_size => 1}
add_stats('adapter_size',adapter_size)
add_stats('adapter_id',message)
end
end
if !actions.empty?
seq.add_actions(actions)
add_stats('sequences_with_adapter','count')
end
#
end
#Returns an array with the errors due to parameters are missing
def self.check_params(params)
errors=[]
comment='Blast E-value used as cut-off when searching for 454 AB adapters'
# default_value = 1e-6
default_value = 1
params.check_param(errors,'blast_evalue_ab','Float',default_value,comment)
comment='Minimum required identity (%) for a reliable 454 AB adapter'
default_value = 95
params.check_param(errors,'blast_percent_ab','Integer',default_value,comment)
comment='454 AB adapters can be found only at the read end (not within it). The following variable indicates the number of nucleotides that are allowed for considering the AB adapters to be located at the end'
default_value = 9
params.check_param(errors,'max_ab_to_end','Integer',default_value,comment)
comment='Path for 454 AB adapters database'
default_value = File.join($FORMATTED_DB_PATH,'adapters_ab.fasta')
params.check_param(errors,'adapters_ab_db','DB',default_value,comment)
return errors
end
def self.get_graph_title(plugin_name,stats_name)
case stats_name
when 'adapter_type'
'AB adapters by type'
when 'adapter_size'
'AB adapters by size'
end
end
def self.get_graph_filename(plugin_name,stats_name)
return stats_name
# case stats_name
# when 'adapter_type'
# 'AB adapters by type'
# when 'adapter_size'
# 'AB adapters by size'
# end
end
def self.valid_graphs
return ['adapter_type']
end
end
| 34.275109 | 254 | 0.637024 |
873a391b7802e7bbd71f7e0741a2eed7dfd51ea3 | 5,255 | # encoding: utf-8
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
require 'azure_mgmt_resourcegraph'
module Azure::ResourceGraph::Profiles::Latest
module Mgmt
Operations = Azure::ResourceGraph::Mgmt::V2019_04_01::Operations
module Models
QueryResponse = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::QueryResponse
QueryRequestOptions = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::QueryRequestOptions
FacetRequest = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::FacetRequest
ErrorDetails = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::ErrorDetails
Column = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::Column
OperationListResult = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::OperationListResult
Facet = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::Facet
Error = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::Error
QueryRequest = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::QueryRequest
ErrorResponse = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::ErrorResponse
FacetRequestOptions = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::FacetRequestOptions
OperationDisplay = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::OperationDisplay
Table = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::Table
Operation = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::Operation
FacetResult = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::FacetResult
FacetError = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::FacetError
FacetSortOrder = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::FacetSortOrder
ResultTruncated = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::ResultTruncated
ColumnDataType = Azure::ResourceGraph::Mgmt::V2019_04_01::Models::ColumnDataType
end
#
# ResourceGraphManagementClass
#
class ResourceGraphManagementClass
attr_reader :operations, :configurable, :base_url, :options, :model_classes
def initialize(options = {})
if options.is_a?(Hash) && options.length == 0
@options = setup_default_options
else
@options = options
end
reset!(options)
@configurable = self
@base_url = options[:base_url].nil? ? nil:options[:base_url]
@options = options[:options].nil? ? nil:options[:options]
@client_0 = Azure::ResourceGraph::Mgmt::V2019_04_01::ResourceGraphClient.new(configurable.credentials, base_url, options)
if(@client_0.respond_to?(:subscription_id))
@client_0.subscription_id = configurable.subscription_id
end
add_telemetry(@client_0)
@operations = @client_0.operations
@model_classes = ModelClasses.new
end
def add_telemetry(client)
profile_information = 'Profiles/Latest/ResourceGraph/Mgmt'
client.add_user_agent_information(profile_information)
end
def method_missing(method, *args)
if @client_0.respond_to?method
@client_0.send(method, *args)
else
super
end
end
end
class ModelClasses
def query_response
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::QueryResponse
end
def query_request_options
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::QueryRequestOptions
end
def facet_request
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::FacetRequest
end
def error_details
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::ErrorDetails
end
def column
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::Column
end
def operation_list_result
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::OperationListResult
end
def facet
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::Facet
end
def error
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::Error
end
def query_request
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::QueryRequest
end
def error_response
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::ErrorResponse
end
def facet_request_options
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::FacetRequestOptions
end
def operation_display
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::OperationDisplay
end
def table
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::Table
end
def operation
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::Operation
end
def facet_result
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::FacetResult
end
def facet_error
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::FacetError
end
def facet_sort_order
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::FacetSortOrder
end
def result_truncated
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::ResultTruncated
end
def column_data_type
Azure::ResourceGraph::Mgmt::V2019_04_01::Models::ColumnDataType
end
end
end
end
| 38.07971 | 129 | 0.69686 |
1dc9f9351c6d81076f6873191be81cfa3861886b | 2,066 | class Freeling < Formula
desc "Suite of language analyzers"
homepage "http://nlp.lsi.upc.edu/freeling/"
url "https://github.com/TALP-UPC/FreeLing/releases/download/4.2/FreeLing-src-4.2.tar.gz"
sha256 "f96afbdb000d7375426644fb2f25baff9a63136dddce6551ea0fd20059bfce3b"
license "AGPL-3.0-only"
revision 4
bottle do
sha256 arm64_big_sur: "b381f9741689e57db0de8cfa8e71758127fd33aaff347ce650f15669a143ac3c"
sha256 big_sur: "6b1ff3a166a5293d4a83bb3efe2ad5649c2f7ed10b915ddc8dbafffcd05643f6"
sha256 catalina: "2b3fe6a2bb6cd65545a3db34bfa441d31d8195a9aa120acd189c6aee7d4ec6dc"
sha256 mojave: "d503e02b17843adcc24bdd451322602b21274fbd977103e31c7f89ab435890fd"
end
depends_on "cmake" => :build
depends_on "boost"
depends_on "icu4c"
conflicts_with "dynet", because: "freeling ships its own copy of dynet"
conflicts_with "eigen", because: "freeling ships its own copy of eigen"
conflicts_with "foma", because: "freeling ships its own copy of foma"
conflicts_with "hunspell", because: "both install 'analyze' binary"
def install
# Allow compilation without extra data (more than 1 GB), should be fixed
# in next release
# https://github.com/TALP-UPC/FreeLing/issues/112
inreplace "CMakeLists.txt", "SET(languages \"as;ca;cs;cy;de;en;es;fr;gl;hr;it;nb;pt;ru;sl\")",
"SET(languages \"en;es;pt\")"
inreplace "CMakeLists.txt", "SET(variants \"es/es-old;es/es-ar;es/es-cl;ca/balear;ca/valencia\")",
"SET(variants \"es/es-old;es/es-ar;es/es-cl\")"
mkdir "build" do
system "cmake", "..", *std_cmake_args
system "make", "install"
end
libexec.install "#{bin}/fl_initialize"
inreplace "#{bin}/analyze",
". $(cd $(dirname $0) && echo $PWD)/fl_initialize",
". #{libexec}/fl_initialize"
end
test do
expected = <<~EOS
Hello hello NN 1
world world NN 1
EOS
assert_equal expected, pipe_output("#{bin}/analyze -f #{pkgshare}/config/en.cfg", "Hello world").chomp
end
end
| 38.981132 | 106 | 0.689255 |
f73270cd48d906006a5c8c059bc26f100bcafb34 | 160 | class AddTaxAmountToErpOrdersOrderDetails < ActiveRecord::Migration[5.1]
def change
add_column :erp_orders_order_details, :tax_amount, :decimal
end
end
| 26.666667 | 72 | 0.80625 |
268b16a5fe641302a9ae6f33e3429fe064a0d099 | 413 | module VertexClient
module Response
class LineItem
attr_reader :total_tax, :product, :quantity, :price
def initialize(params={})
@product = params[:product]
@quantity = params[:quantity] ? params[:quantity].to_i : 0
@price = BigDecimal(params[:price] || 0)
@total_tax = BigDecimal(params[:total_tax] || 0)
end
end
end
end
| 25.8125 | 72 | 0.578692 |
8771084f15b4cbccac8ade11956230e5ef3f16d2 | 748 | # myExperiment: app/models/permission_sweeper.rb
#
# Copyright (c) 2007 University of Manchester and the University of Southampton.
# See license.txt for details.
class PermissionSweeper < ActionController::Caching::Sweeper
include CachingHelper
observe Permission
def after_create(permission)
expire_listing(permission.contributor_id, permission.contributor_type) if permission.contributor_type == 'Network'
end
def after_update(permission)
expire_listing(permission.contributor_id, permission.contributor_type) if permission.contributor_type == 'Network'
end
def after_destroy(permission)
expire_listing(permission.contributor_id, permission.contributor_type) if permission.contributor_type == 'Network'
end
end
| 32.521739 | 118 | 0.80615 |
6167478ea05a820ca48b11ba6315e67270555a61 | 31,624 | # encoding: utf-8
require File.dirname(__FILE__) + '/spec_helper'
class TestAutolink
include Twitter::Autolink
end
describe Twitter::Autolink do
def original_text; end
def url; end
describe "auto_link_custom" do
before do
@autolinked_text = TestAutolink.new.auto_link(original_text) if original_text
end
describe "username autolinking" do
context "username preceded by a space" do
def original_text; "hello @jacob"; end
it "should be linked" do
expect(@autolinked_text).to link_to_screen_name('jacob')
end
end
context "username in camelCase" do
def original_text() "@jaCob iS cOoL" end
it "should be linked" do
expect(@autolinked_text).to link_to_screen_name('jaCob')
end
end
context "username at beginning of line" do
def original_text; "@jacob you're cool"; end
it "should be linked" do
expect(@autolinked_text).to link_to_screen_name('jacob')
end
end
context "username preceded by word character" do
def original_text; "meet@the beach"; end
it "should not be linked" do
expect(Nokogiri::HTML(@autolinked_text).search('a')).to be_empty
end
end
context "username preceded by non-word character" do
def original_text; "great.@jacob"; end
it "should be linked" do
expect(@autolinked_text).to link_to_screen_name('jacob')
end
end
context "username containing non-word characters" do
def original_text; "@zach&^$%^"; end
it "should not be linked" do
expect(@autolinked_text).to link_to_screen_name('zach')
end
end
context "username over twenty characters" do
def original_text
@twenty_character_username = "zach" * 5
"@" + @twenty_character_username + "1"
end
it "should not be linked" do
expect(@autolinked_text).to link_to_screen_name(@twenty_character_username)
end
end
context "username followed by japanese" do
def original_text; "@jacobの"; end
it "should be linked" do
expect(@autolinked_text).to link_to_screen_name('jacob')
end
end
context "username preceded by japanese" do
def original_text; "あ@matz"; end
it "should be linked" do
expect(@autolinked_text).to link_to_screen_name('matz')
end
end
context "username surrounded by japanese" do
def original_text; "あ@yoshimiの"; end
it "should be linked" do
expect(@autolinked_text).to link_to_screen_name('yoshimi')
end
end
context "username using full-width at-sign" do
def original_text
"#{[0xFF20].pack('U')}jacob"
end
it "should be linked" do
expect(@autolinked_text).to link_to_screen_name('jacob')
end
end
end
describe "list path autolinking" do
context "when List is not available" do
it "should not be linked" do
@autolinked_text = TestAutolink.new.auto_link_usernames_or_lists("hello @jacob/my-list", :suppress_lists => true)
expect(@autolinked_text).to_not link_to_list_path('jacob/my-list')
expect(@autolinked_text).to include('my-list')
end
end
context "slug preceded by a space" do
def original_text; "hello @jacob/my-list"; end
it "should be linked" do
expect(@autolinked_text).to link_to_list_path('jacob/my-list')
end
end
context "username followed by a slash but no list" do
def original_text; "hello @jacob/ my-list"; end
it "should NOT be linked" do
expect(@autolinked_text).to_not link_to_list_path('jacob/my-list')
expect(@autolinked_text).to link_to_screen_name('jacob')
end
end
context "empty username followed by a list" do
def original_text; "hello @/my-list"; end
it "should NOT be linked" do
expect(Nokogiri::HTML(@autolinked_text).search('a')).to be_empty
end
end
context "list slug at beginning of line" do
def original_text; "@jacob/my-list"; end
it "should be linked" do
expect(@autolinked_text).to link_to_list_path('jacob/my-list')
end
end
context "username preceded by alpha-numeric character" do
def original_text; "meet@the/beach"; end
it "should not be linked" do
expect(Nokogiri::HTML(@autolinked_text).search('a')).to be_empty
end
end
context "username preceded by non-word character" do
def original_text; "great.@jacob/my-list"; end
it "should be linked" do
@autolinked_text = TestAutolink.new.auto_link("great.@jacob/my-list")
expect(@autolinked_text).to link_to_list_path('jacob/my-list')
end
end
context "username containing non-word characters" do
def original_text; "@zach/test&^$%^"; end
it "should be linked" do
expect(@autolinked_text).to link_to_list_path('zach/test')
end
end
context "username over twenty characters" do
def original_text
@twentyfive_character_list = "jack/" + ("a" * 25)
"@#{@twentyfive_character_list}12345"
end
it "should be linked" do
expect(@autolinked_text).to link_to_list_path(@twentyfive_character_list)
end
end
end
describe "hashtag autolinking" do
context "with an all numeric hashtag" do
def original_text; "#123"; end
it "should not be linked" do
expect(@autolinked_text).to_not have_autolinked_hashtag('#123')
end
end
context "with a hashtag with alphanumeric characters" do
def original_text; "#ab1d"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_hashtag('#ab1d')
end
end
context "with a hashtag with underscores" do
def original_text; "#a_b_c_d"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_hashtag(original_text)
end
end
context "with a hashtag that is preceded by a word character" do
def original_text; "ab#cd"; end
it "should not be linked" do
expect(@autolinked_text).to_not have_autolinked_hashtag(original_text)
end
end
context "with a page anchor in a url" do
def original_text; "Here's my url: http://foobar.com/#home"; end
it "should not link the hashtag" do
expect(@autolinked_text).to_not have_autolinked_hashtag('#home')
end
it "should link the url" do
expect(@autolinked_text).to have_autolinked_url('http://foobar.com/#home')
end
end
context "with a hashtag that starts with a number but has word characters" do
def original_text; "#2ab"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_hashtag(original_text)
end
end
context "with multiple valid hashtags" do
def original_text; "I'm frickin' awesome #ab #cd #ef"; end
it "links each hashtag" do
expect(@autolinked_text).to have_autolinked_hashtag('#ab')
expect(@autolinked_text).to have_autolinked_hashtag('#cd')
expect(@autolinked_text).to have_autolinked_hashtag('#ef')
end
end
context "with a hashtag preceded by a ." do
def original_text; "ok, great.#abc"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_hashtag('#abc')
end
end
context "with a hashtag preceded by a &" do
def original_text; "&#nbsp;"; end
it "should not be linked" do
expect(@autolinked_text).to_not have_autolinked_hashtag('#nbsp;')
end
end
context "with a hashtag that ends in an !" do
def original_text; "#great!"; end
it "should be linked, but should not include the !" do
expect(@autolinked_text).to have_autolinked_hashtag('#great')
end
end
context "with a hashtag followed by Japanese" do
def original_text; "#twj_devの"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_hashtag('#twj_devの')
end
end
context "with a hashtag preceded by a full-width space" do
def original_text; "#{[0x3000].pack('U')}#twj_dev"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_hashtag('#twj_dev')
end
end
context "with a hashtag followed by a full-width space" do
def original_text; "#twj_dev#{[0x3000].pack('U')}"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_hashtag('#twj_dev')
end
end
context "with a hashtag using full-width hash" do
def original_text; "#{[0xFF03].pack('U')}twj_dev"; end
it "should be linked" do
link = Nokogiri::HTML(@autolinked_text).search('a')
expect((link.inner_text.respond_to?(:force_encoding) ? link.inner_text.force_encoding("utf-8") : link.inner_text)).to be == "#{[0xFF03].pack('U')}twj_dev"
expect(link.first['href']).to be == 'https://twitter.com/search?q=%23twj_dev'
end
end
context "with a hashtag containing an accented latin character" do
def original_text
# the hashtag is #éhashtag
"##{[0x00e9].pack('U')}hashtag"
end
it "should be linked" do
expect(@autolinked_text).to be == "<a class=\"tweet-url hashtag\" href=\"https://twitter.com/search?q=%23éhashtag\" rel=\"nofollow\" title=\"#éhashtag\">#éhashtag</a>"
end
end
end
describe "URL autolinking" do
def url; "http://www.google.com"; end
context "when embedded in plain text" do
def original_text; "On my search engine #{url} I found good links."; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_url(url)
end
end
context "when surrounded by Japanese;" do
def original_text; "いまなにしてる#{url}いまなにしてる"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_url(url)
end
end
context "with a path surrounded by parentheses;" do
def original_text; "I found a neatness (#{url})"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_url(url)
end
context "when the URL ends with a slash;" do
def url; "http://www.google.com/"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_url(url)
end
end
context "when the URL has a path;" do
def url; "http://www.google.com/fsdfasdf"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_url(url)
end
end
end
context "when path contains parens" do
def original_text; "I found a neatness (#{url})"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_url(url)
end
context "wikipedia" do
def url; "http://en.wikipedia.org/wiki/Madonna_(artist)"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_url(url)
end
end
context "IIS session" do
def url; "http://msdn.com/S(deadbeef)/page.htm"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_url(url)
end
end
context "unbalanced parens" do
def url; "http://example.com/i_has_a_("; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_url("http://example.com/i_has_a_")
end
end
context "balanced parens with a double quote inside" do
def url; "http://foo.com/foo_(\")_bar" end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_url("http://foo.com/foo_")
end
end
context "balanced parens hiding XSS" do
def url; 'http://x.xx.com/("style="color:red"onmouseover="alert(1)' end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_url("http://x.xx.com/")
end
end
end
context "when preceded by a :" do
def original_text; "Check this out @hoverbird:#{url}"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_url(url)
end
end
context "with a URL ending in allowed punctuation" do
it "does not consume ending punctuation" do
matcher = TestAutolink.new
%w| ? ! , . : ; ] ) } = \ ' |.each do |char|
expect(matcher.auto_link("#{url}#{char}")).to have_autolinked_url(url)
end
end
end
context "with a URL preceded in forbidden characters" do
it "should be linked" do
matcher = TestAutolink.new
%w| \ ' / ! = |.each do |char|
expect(matcher.auto_link("#{char}#{url}")).to have_autolinked_url(url)
end
end
end
context "when embedded in a link tag" do
def original_text; "<link rel='true'>#{url}</link>"; end
it "should be linked" do
expect(@autolinked_text).to have_autolinked_url(url)
end
end
context "with multiple URLs" do
def original_text; "http://www.links.org link at start of page, link at end http://www.foo.org"; end
it "should autolink each one" do
expect(@autolinked_text).to have_autolinked_url('http://www.links.org')
expect(@autolinked_text).to have_autolinked_url('http://www.foo.org')
end
end
context "with multiple URLs in different formats" do
def original_text; "http://foo.com https://bar.com http://mail.foobar.org"; end
it "should autolink each one, in the proper order" do
expect(@autolinked_text).to have_autolinked_url('http://foo.com')
expect(@autolinked_text).to have_autolinked_url('https://bar.com')
expect(@autolinked_text).to have_autolinked_url('http://mail.foobar.org')
end
end
context "with a URL having a long TLD" do
def original_text; "Yahoo integriert Facebook http://golem.mobi/0912/71607.html"; end
it "should autolink it" do
expect(@autolinked_text).to have_autolinked_url('http://golem.mobi/0912/71607.html')
end
end
context "with a url lacking the protocol" do
def original_text; "I like www.foobar.com dudes"; end
it "does not link at all" do
link = Nokogiri::HTML(@autolinked_text).search('a')
expect(link).to be_empty
end
end
context "with a @ in a URL" do
context "with XSS attack" do
def original_text; 'http://x.xx.com/@"style="color:pink"onmouseover=alert(1)//'; end
it "should not allow XSS follwing @" do
expect(@autolinked_text).to have_autolinked_url('http://x.xx.com/')
end
end
context "with a username not followed by a /" do
def original_text; 'http://example.com/@foobar'; end
it "should link url" do
expect(@autolinked_text).to have_autolinked_url('http://example.com/@foobar')
end
end
context "with a username followed by a /" do
def original_text; 'http://example.com/@foobar/'; end
it "should not link the username but link full url" do
expect(@autolinked_text).to have_autolinked_url('http://example.com/@foobar/')
expect(@autolinked_text).to_not link_to_screen_name('foobar')
end
end
end
context "regex engine quirks" do
context "does not spiral out of control on repeated periods" do
def original_text; "Test a ton of periods http://example.com/path.........................................."; end
it "should autolink" do
expect(@autolinked_text).to have_autolinked_url('http://example.com/path')
end
end
context "does not spiral out of control on repeated dashes" do
def original_text; "Single char file ext http://www.bestbuy.com/site/Currie+Technologies+-+Ezip+400+Scooter/9885188.p?id=1218189013070&skuId=9885188"; end
it "should autolink" do
expect(@autolinked_text).to have_autolinked_url('http://www.bestbuy.com/site/Currie+Technologies+-+Ezip+400+Scooter/9885188.p?id=1218189013070&skuId=9885188')
end
end
end
end
describe "Autolink all" do
before do
@linker = TestAutolink.new
end
it "should allow url/hashtag overlap" do
auto_linked = @linker.auto_link("https://twitter.com/#search")
expect(auto_linked).to have_autolinked_url('https://twitter.com/#search')
end
it "should not add invalid option in HTML tags" do
auto_linked = @linker.auto_link("https://twitter.com/ is a URL, not a hashtag", :hashtag_class => 'hashtag_classname')
expect(auto_linked).to have_autolinked_url('https://twitter.com/')
expect(auto_linked).to_not include('hashtag_class')
expect(auto_linked).to_not include('hashtag_classname')
end
it "should autolink url/hashtag/mention in text with Unicode supplementary characters" do
auto_linked = @linker.auto_link("#{[0x10400].pack('U')} #hashtag #{[0x10400].pack('U')} @mention #{[0x10400].pack('U')} http://twitter.com/")
expect(auto_linked).to have_autolinked_hashtag('#hashtag')
expect(auto_linked).to link_to_screen_name('mention')
expect(auto_linked).to have_autolinked_url('http://twitter.com/')
end
end
end
describe "autolinking options" do
before do
@linker = TestAutolink.new
end
it "should show display_url when :url_entities provided" do
linked = @linker.auto_link("http://t.co/0JG5Mcq", :url_entities => [{
"url" => "http://t.co/0JG5Mcq",
"display_url" => "blog.twitter.com/2011/05/twitte…",
"expanded_url" => "http://blog.twitter.com/2011/05/twitter-for-mac-update.html",
"indices" => [
84,
103
]
}])
html = Nokogiri::HTML(linked)
expect(html.search('a')).to_not be_empty
expect(html.search('a[@href="http://t.co/0JG5Mcq"]')).to_not be_empty
expect(html.search('span[@class=js-display-url]').inner_text).to be == "blog.twitter.com/2011/05/twitte"
expect(html.inner_text).to be == " http://blog.twitter.com/2011/05/twitter-for-mac-update.html …"
expect(html.search('span[@style="position:absolute;left:-9999px;"]').size).to be == 4
end
it "should accept invisible_tag_attrs option" do
linked = @linker.auto_link("http://t.co/0JG5Mcq",
{
:url_entities => [{
"url" => "http://t.co/0JG5Mcq",
"display_url" => "blog.twitter.com/2011/05/twitte…",
"expanded_url" => "http://blog.twitter.com/2011/05/twitter-for-mac-update.html",
"indices" => [
0,
19
]
}],
:invisible_tag_attrs => "style='dummy;'"
})
html = Nokogiri::HTML(linked)
expect(html.search('span[@style="dummy;"]').size).to be == 4
end
it "should show display_url if available in entity" do
linked = @linker.auto_link_entities("http://t.co/0JG5Mcq",
[{
:url => "http://t.co/0JG5Mcq",
:display_url => "blog.twitter.com/2011/05/twitte…",
:expanded_url => "http://blog.twitter.com/2011/05/twitter-for-mac-update.html",
:indices => [0, 19]
}]
)
html = Nokogiri::HTML(linked)
expect(html.search('a')).to_not be_empty
expect(html.search('a[@href="http://t.co/0JG5Mcq"]')).to_not be_empty
expect(html.search('span[@class=js-display-url]').inner_text).to be == "blog.twitter.com/2011/05/twitte"
expect(html.inner_text).to be == " http://blog.twitter.com/2011/05/twitter-for-mac-update.html …"
end
it "should apply :class as a CSS class" do
linked = @linker.auto_link("http://example.com/", :class => 'myclass')
expect(linked).to have_autolinked_url('http://example.com/')
expect(linked).to match(/myclass/)
end
it "should apply :url_class only on URL" do
linked = @linker.auto_link("http://twitter.com")
expect(linked).to have_autolinked_url('http://twitter.com')
expect(expect(linked)).to_not match(/class/)
linked = @linker.auto_link("http://twitter.com", :url_class => 'testClass')
expect(linked).to have_autolinked_url('http://twitter.com')
expect(linked).to match(/class=\"testClass\"/)
linked = @linker.auto_link("#hash @tw", :url_class => 'testClass')
expect(linked).to match(/class=\"tweet-url hashtag\"/)
expect(linked).to match(/class=\"tweet-url username\"/)
expect(linked).to_not match(/class=\"testClass\"/)
end
it "should add rel=nofollow by default" do
linked = @linker.auto_link("http://example.com/")
expect(linked).to have_autolinked_url('http://example.com/')
expect(linked).to match(/nofollow/)
end
it "should include the '@' symbol in a username when passed :username_include_symbol" do
linked = @linker.auto_link("@user", :username_include_symbol => true)
expect(linked).to link_to_screen_name('user', '@user')
end
it "should include the '@' symbol in a list when passed :username_include_symbol" do
linked = @linker.auto_link("@user/list", :username_include_symbol => true)
expect(linked).to link_to_list_path('user/list', '@user/list')
end
it "should not add rel=nofollow when passed :suppress_no_follow" do
linked = @linker.auto_link("http://example.com/", :suppress_no_follow => true)
expect(linked).to have_autolinked_url('http://example.com/')
expect(linked).to_not match(/nofollow/)
end
it "should not add a target attribute by default" do
linked = @linker.auto_link("http://example.com/")
expect(linked).to have_autolinked_url('http://example.com/')
expect(linked).to_not match(/target=/)
end
it "should respect the :target option" do
linked = @linker.auto_link("http://example.com/", :target => 'mywindow')
expect(linked).to have_autolinked_url('http://example.com/')
expect(linked).to match(/target="mywindow"/)
end
it "should customize href by username_url_block option" do
linked = @linker.auto_link("@test", :username_url_block => lambda{|a| "dummy"})
expect(linked).to have_autolinked_url('dummy', 'test')
end
it "should customize href by list_url_block option" do
linked = @linker.auto_link("@test/list", :list_url_block => lambda{|a| "dummy"})
expect(linked).to have_autolinked_url('dummy', 'test/list')
end
it "should customize href by hashtag_url_block option" do
linked = @linker.auto_link("#hashtag", :hashtag_url_block => lambda{|a| "dummy"})
expect(linked).to have_autolinked_url('dummy', '#hashtag')
end
it "should customize href by cashtag_url_block option" do
linked = @linker.auto_link("$CASH", :cashtag_url_block => lambda{|a| "dummy"})
expect(linked).to have_autolinked_url('dummy', '$CASH')
end
it "should customize href by link_url_block option" do
linked = @linker.auto_link("http://example.com/", :link_url_block => lambda{|a| "dummy"})
expect(linked).to have_autolinked_url('dummy', 'http://example.com/')
end
it "should modify link attributes by link_attribute_block" do
linked = @linker.auto_link("#hash @mention",
:link_attribute_block => lambda{|entity, attributes|
attributes[:"dummy-hash-attr"] = "test" if entity[:hashtag]
}
)
expect(linked).to match(/<a[^>]+hashtag[^>]+dummy-hash-attr=\"test\"[^>]+>/)
expect(linked).to_not match(/<a[^>]+username[^>]+dummy-hash-attr=\"test\"[^>]+>/)
expect(linked).to_not match(/link_attribute_block/i)
linked = @linker.auto_link("@mention http://twitter.com/",
:link_attribute_block => lambda{|entity, attributes|
attributes["dummy-url-attr"] = entity[:url] if entity[:url]
}
)
expect(linked).to_not match(/<a[^>]+username[^>]+dummy-url-attr=\"http:\/\/twitter.com\/\"[^>]*>/)
expect(linked).to match(/<a[^>]+dummy-url-attr=\"http:\/\/twitter.com\/\"/)
end
it "should modify link text by link_text_block" do
linked = @linker.auto_link("#hash @mention",
:link_text_block => lambda{|entity, text|
entity[:hashtag] ? "#replaced" : "pre_#{text}_post"
}
)
expect(linked).to match(/<a[^>]+>#replaced<\/a>/)
expect(linked).to match(/<a[^>]+>pre_mention_post<\/a>/)
linked = @linker.auto_link("#hash @mention", {
:link_text_block => lambda{|entity, text|
"pre_#{text}_post"
},
:symbol_tag => "s", :text_with_symbol_tag => "b", :username_include_symbol => true
})
expect(linked).to match(/<a[^>]+>pre_<s>#<\/s><b>hash<\/b>_post<\/a>/)
expect(linked).to match(/<a[^>]+>pre_<s>@<\/s><b>mention<\/b>_post<\/a>/)
end
it "should apply :url_target only to auto-linked URLs" do
auto_linked = @linker.auto_link("#hashtag @mention http://test.com/", {:url_target => '_blank'})
expect(auto_linked).to have_autolinked_hashtag('#hashtag')
expect(auto_linked).to link_to_screen_name('mention')
expect(auto_linked).to have_autolinked_url('http://test.com/')
expect(auto_linked).to_not match(/<a[^>]+hashtag[^>]+target[^>]+>/)
expect(auto_linked).to_not match(/<a[^>]+username[^>]+target[^>]+>/)
expect(auto_linked).to match(/<a[^>]+test.com[^>]+target=\"_blank\"[^>]*>/)
end
it "should apply target='_blank' only to auto-linked URLs when :target_blank is set to true" do
auto_linked = @linker.auto_link("#hashtag @mention http://test.com/", {:target_blank => true})
expect(auto_linked).to have_autolinked_hashtag('#hashtag')
expect(auto_linked).to link_to_screen_name('mention')
expect(auto_linked).to have_autolinked_url('http://test.com/')
expect(auto_linked).to match(/<a[^>]+hashtag[^>]+target=\"_blank\"[^>]*>/)
expect(auto_linked).to match(/<a[^>]+username[^>]+target=\"_blank\"[^>]*>/)
expect(auto_linked).to match(/<a[^>]+test.com[^>]+target=\"_blank\"[^>]*>/)
end
end
describe "link_url_with_entity" do
before do
@linker = TestAutolink.new
end
it "should use display_url and expanded_url" do
expect(@linker.send(:link_url_with_entity,
{
:url => "http://t.co/abcde",
:display_url => "twitter.com",
:expanded_url => "http://twitter.com/"},
{:invisible_tag_attrs => "class='invisible'"}).gsub('"', "'")).to be == "<span class='tco-ellipsis'><span class='invisible'> </span></span><span class='invisible'>http://</span><span class='js-display-url'>twitter.com</span><span class='invisible'>/</span><span class='tco-ellipsis'><span class='invisible'> </span></span>";
end
it "should correctly handle display_url ending with '…'" do
expect(@linker.send(:link_url_with_entity,
{
:url => "http://t.co/abcde",
:display_url => "twitter.com…",
:expanded_url => "http://twitter.com/abcdefg"},
{:invisible_tag_attrs => "class='invisible'"}).gsub('"', "'")).to be == "<span class='tco-ellipsis'><span class='invisible'> </span></span><span class='invisible'>http://</span><span class='js-display-url'>twitter.com</span><span class='invisible'>/abcdefg</span><span class='tco-ellipsis'><span class='invisible'> </span>…</span>";
end
it "should correctly handle display_url starting with '…'" do
expect(@linker.send(:link_url_with_entity,
{
:url => "http://t.co/abcde",
:display_url => "…tter.com/abcdefg",
:expanded_url => "http://twitter.com/abcdefg"},
{:invisible_tag_attrs => "class='invisible'"}).gsub('"', "'")).to be == "<span class='tco-ellipsis'>…<span class='invisible'> </span></span><span class='invisible'>http://twi</span><span class='js-display-url'>tter.com/abcdefg</span><span class='invisible'></span><span class='tco-ellipsis'><span class='invisible'> </span></span>";
end
it "should not create spans if display_url and expanded_url are on different domains" do
expect(@linker.send(:link_url_with_entity,
{
:url => "http://t.co/abcde",
:display_url => "pic.twitter.com/xyz",
:expanded_url => "http://twitter.com/foo/statuses/123/photo/1"},
{:invisible_tag_attrs => "class='invisible'"}).gsub('"', "'")).to be == "pic.twitter.com/xyz"
end
end
describe "symbol_tag" do
before do
@linker = TestAutolink.new
end
it "should put :symbol_tag around symbol" do
expect(@linker.auto_link("@mention", {:symbol_tag => 's', :username_include_symbol=>true})).to match(/<s>@<\/s>mention/)
expect(@linker.auto_link("#hash", {:symbol_tag => 's'})).to match(/<s>#<\/s>hash/)
result = @linker.auto_link("@mention #hash $CASH", {:symbol_tag => 'b', :username_include_symbol=>true})
expect(result).to match(/<b>@<\/b>mention/)
expect(result).to match(/<b>#<\/b>hash/)
expect(result).to match(/<b>\$<\/b>CASH/)
end
it "should put :text_with_symbol_tag around text" do
result = @linker.auto_link("@mention #hash $CASH", {:text_with_symbol_tag => 'b'})
expect(result).to match(/<b>mention<\/b>/)
expect(result).to match(/<b>hash<\/b>/)
expect(result).to match(/<b>CASH<\/b>/)
end
it "should put :symbol_tag around symbol and :text_with_symbol_tag around text" do
result = @linker.auto_link("@mention #hash $CASH", {:symbol_tag => 's', :text_with_symbol_tag => 'b', :username_include_symbol=>true})
expect(result).to match(/<s>@<\/s><b>mention<\/b>/)
expect(result).to match(/<s>#<\/s><b>hash<\/b>/)
expect(result).to match(/<s>\$<\/s><b>CASH<\/b>/)
end
end
describe "html_escape" do
before do
@linker = TestAutolink.new
end
it "should escape html entities properly" do
expect(@linker.html_escape("&")).to be == "&"
expect(@linker.html_escape(">")).to be == ">"
expect(@linker.html_escape("<")).to be == "<"
expect(@linker.html_escape("\"")).to be == """
expect(@linker.html_escape("'")).to be == "'"
expect(@linker.html_escape("&<>\"")).to be == "&<>""
expect(@linker.html_escape("<div>")).to be == "<div>"
expect(@linker.html_escape("a&b")).to be == "a&b"
expect(@linker.html_escape("<a href=\"https://twitter.com\" target=\"_blank\">twitter & friends</a>")).to be == "<a href="https://twitter.com" target="_blank">twitter & friends</a>"
expect(@linker.html_escape("&")).to be == "&amp;"
expect(@linker.html_escape(nil)).to be == nil
end
end
end
| 37.424852 | 350 | 0.617854 |
f70bf2d66adcaa79f7d299a9f828ef671846851b | 2,768 | ##
# Float ISO Test
assert('Float', '15.2.9') do
assert_equal Class, Float.class
end
assert('Float superclass', '15.2.9.2') do
assert_equal Numeric, Float.superclass
end
assert('Float#+', '15.2.9.3.1') do
a = 3.123456788 + 0.000000001
b = 3.123456789 + 1
assert_float(3.123456789, a)
assert_float(4.123456789, b)
end
assert('Float#-', '15.2.9.3.2') do
a = 3.123456790 - 0.000000001
b = 5.123456789 - 1
assert_float(3.123456789, a)
assert_float(4.123456789, b)
end
assert('Float#*', '15.2.9.3.3') do
a = 3.125 * 3.125
b = 3.125 * 1
assert_float(9.765625, a)
assert_float(3.125 , b)
end
assert('Float#/', '15.2.9.3.4') do
a = 3.123456789 / 3.123456789
b = 3.123456789 / 1
assert_float(1.0 , a)
assert_float(3.123456789, b)
end
assert('Float#%', '15.2.9.3.5') do
a = 3.125 % 3.125
b = 3.125 % 1
assert_float(0.0 , a)
assert_float(0.125, b)
end
assert('Float#<=>', '15.2.9.3.6') do
a = 3.125 <=> 3.123
b = 3.125 <=> 3.125
c = 3.125 <=> 3.126
a2 = 3.125 <=> 3
c2 = 3.125 <=> 4
assert_equal( 1, a)
assert_equal( 0, b)
assert_equal(-1, c)
assert_equal( 1, a2)
assert_equal(-1, c2)
end
assert('Float#==', '15.2.9.3.7') do
assert_true 3.1 == 3.1
assert_false 3.1 == 3.2
end
assert('Float#ceil', '15.2.9.3.8') do
a = 3.123456789.ceil
b = 3.0.ceil
c = -3.123456789.ceil
d = -3.0.ceil
assert_equal( 4, a)
assert_equal( 3, b)
assert_equal(-3, c)
assert_equal(-3, d)
end
assert('Float#finite?', '15.2.9.3.9') do
assert_true 3.123456789.finite?
assert_false (1.0 / 0.0).finite?
end
assert('Float#floor', '15.2.9.3.10') do
a = 3.123456789.floor
b = 3.0.floor
c = -3.123456789.floor
d = -3.0.floor
assert_equal( 3, a)
assert_equal( 3, b)
assert_equal(-4, c)
assert_equal(-3, d)
end
assert('Float#infinite?', '15.2.9.3.11') do
a = 3.123456789.infinite?
b = (1.0 / 0.0).infinite?
c = (-1.0 / 0.0).infinite?
assert_nil a
assert_equal( 1, b)
assert_equal(-1, c)
end
assert('Float#round', '15.2.9.3.12') do
a = 3.123456789.round
b = 3.5.round
c = 3.4999.round
d = (-3.123456789).round
e = (-3.5).round
f = 12345.67.round(-1)
g = 3.423456789.round(0)
h = 3.423456789.round(1)
i = 3.423456789.round(3)
assert_equal( 3, a)
assert_equal( 4, b)
assert_equal( 3, c)
assert_equal( -3, d)
assert_equal( -4, e)
assert_equal(12350, f)
assert_equal( 3, g)
assert_float( 3.4, h)
assert_float(3.423, i)
end
assert('Float#to_f', '15.2.9.3.13') do
a = 3.123456789
assert_float(a, a.to_f)
end
assert('Float#to_i', '15.2.9.3.14') do
assert_equal(3, 3.123456789.to_i)
end
assert('Float#truncate', '15.2.9.3.15') do
assert_equal( 3, 3.123456789.truncate)
assert_equal(-3, -3.1.truncate)
end
| 18.958904 | 43 | 0.607298 |
ed7045b644950e4e6172ded820e490c23e08aae9 | 4,864 | module Glueby
class FeeProvider
class Tasks
attr_reader :fee_provider
STATUS = {
# FeeProvider is ready to pay fees.
ready: 'Ready',
# FeeProvider is ready to pay fees, but it doesn't have enough amount to fill the UTXO pool by UTXOs which is for paying fees.
insufficient_amount: 'Insufficient Amount',
# FeeProvider is not ready to pay fees. It has no UTXOs for paying fee and amounts.
not_ready: 'Not Ready'
}
def initialize
@fee_provider = Glueby::FeeProvider.new
end
# Create UTXOs for paying fee from TPC amount of the wallet FeeProvider has. Then show the status.
#
# About the UTXO Pool
# FeeProvider have the UTXO pool. the pool is manged to keep some number of UTXOs that have fixed fee value. The
# value is configurable by :fixed_fee. This method do the management to the pool.
def manage_utxo_pool
txb = Tapyrus::TxBuilder.new
sum, utxos = collect_outputs
return if utxos.empty?
utxos.each { |utxo| txb.add_utxo(utxo) }
address = wallet.receive_address
shortage = [fee_provider.utxo_pool_size - current_utxo_pool_size, 0].max
can_create = (sum - fee_provider.fixed_fee) / fee_provider.fixed_fee
fee_outputs_count_to_be_created = [shortage, can_create].min
return if fee_outputs_count_to_be_created == 0
fee_outputs_count_to_be_created.times do
txb.pay(address, fee_provider.fixed_fee)
end
tx = txb.change_address(address)
.fee(fee_provider.fixed_fee)
.build
tx = wallet.sign_tx(tx)
wallet.broadcast(tx, without_fee_provider: true)
ensure
status
end
# Show the status of the UTXO pool
def status
status = :ready
if current_utxo_pool_size < fee_provider.utxo_pool_size
if tpc_amount < value_to_fill_utxo_pool
status = :insufficient_amount
message = <<~MESSAGE
1. Please replenishment TPC which is for paying fee to FeeProvider.
FeeProvider needs #{value_to_fill_utxo_pool} tapyrus at least for paying 20 transaction fees.
FeeProvider wallet's address is '#{wallet.receive_address}'
2. Then create UTXOs for paying in UTXO pool with 'rake glueby:fee_provider:manage_utxo_pool'
MESSAGE
else
message = "Please create UTXOs for paying in UTXO pool with 'rake glueby:fee_provider:manage_utxo_pool'\n"
end
end
status = :not_ready if current_utxo_pool_size == 0
puts <<~EOS
Status: #{STATUS[status]}
TPC amount: #{delimit(tpc_amount)}
UTXO pool size: #{delimit(current_utxo_pool_size)}
#{"\n" if message}#{message}
Configuration:
fixed_fee = #{delimit(fee_provider.fixed_fee)}
utxo_pool_size = #{delimit(fee_provider.utxo_pool_size)}
EOS
end
# Show the address of Fee Provider
def address
puts wallet.receive_address
end
private
def check_wallet_amount!
if tpc_amount < fee_provider.fixed_fee
raise InsufficientTPC, <<~MESSAGE
FeeProvider has insufficient TPC to create fee outputs to fill the UTXO pool.
1. Please replenishment TPC which is for paying fee to FeeProvider. FeeProvider needs #{fee_provider.utxo_pool_size * fee_provider.fixed_fee} tapyrus at least. FeeProvider wallet's address is '#{wallet.receive_address}'
2. Then create UTXOs for paying in UTXO pool with 'rake glueby:fee_provider:manage_utxo_pool'
MESSAGE
end
end
def tpc_amount
wallet.balance(false)
end
def collect_outputs
wallet.list_unspent.inject([0, []]) do |sum, output|
next sum if output[:color_id] || output[:amount] == fee_provider.fixed_fee
new_sum = sum[0] + output[:amount]
new_outputs = sum[1] << {
txid: output[:txid],
script_pubkey: output[:script_pubkey],
value: output[:amount],
index: output[:vout] ,
finalized: output[:finalized]
}
return [new_sum, new_outputs] if new_sum >= value_to_fill_utxo_pool
[new_sum, new_outputs]
end
end
def current_utxo_pool_size
wallet
.list_unspent(false)
.count { |o| !o[:color_id] && o[:amount] == fee_provider.fixed_fee }
end
def value_to_fill_utxo_pool
fee_provider.fixed_fee * (fee_provider.utxo_pool_size + 1) # +1 is for paying fee
end
def wallet
fee_provider.wallet
end
def delimit(num)
num.to_s.reverse.scan(/.{1,3}/).join('_').reverse
end
end
end
end | 34.496454 | 231 | 0.631373 |
7ac61e632fe8b3a6ab9fb4c6caa7112c6c6d440c | 2,029 | module Vimpack
module Utils
module Vimscripts
def self.included(base)
base.send(:include, Vimpack::Utils::Api)
base.send(:extend, ClassMethods)
end
module ClassMethods
def vimscripts_url
'http://vim-scripts.org/api/scripts_recent.json'
end
def vimscripts
# {"n"=>"test.vim", "t"=>"utility", "s"=>"example utility script file -- used for testing vimonline", "rv"=>"1.0", "rd"=>"2001-05-28", "ra"=>"Scott Johnston", "re"=>"[email protected]"}
@vimscripts ||= Yajl.load(wrap_open(vimscripts_url))
@vimscripts.clone
end
def search_vimscripts(q, types = [], limit = 10, offset = 0)
results = q.nil? ? vimscripts : search_for_string(q, vimscripts)
results = types.empty? ? results : search_for_type(types, results)
normalize_results(limit, offset, results)
end
def normalize_results(limit, offset, results)
results[offset..limit-1].map do |script|
normalize_vimscript(script)
end
end
def search_for_type(types, results)
results.delete_if do |vimscript|
!types.include?(vimscript['t'])
end
end
def search_for_string(q, results)
q = q.downcase
results.delete_if do |vimscript|
!(vimscript['n'].downcase.include?(q) or vimscript['s'].downcase.include?(q))
end
end
def get_vimscript(name)
results = vimscripts.delete_if do |vimscript|
!(vimscript['n'] == name)
end
normalize_vimscript(results.first) rescue nil
end
def normalize_vimscript(script)
{ :name => script['n'], :type => script['t'],
:description => script['s'], :script_version => script['rv'],
:author => script['ra'], :author_email => script['re'],
:repo_owner => 'vim-scripts'
}
end
end
end
end
end
| 30.742424 | 206 | 0.566289 |
187f4a5056caab46a49c754ac6bba9d11f64e89f | 322 | module Elb2Logstalgia
module Types
class Success
attr_reader :parsed
def initialize(*args, &block)
begin
@parsed = String.new(*args[0].to_s)
rescue StandardError => e
raise e
end
end
def to_s
self.parsed.to_s
end
end
end
end
| 15.333333 | 45 | 0.546584 |
91858563d9d7b3e9ff926002d95fbb0c1d106640 | 54 | module FeatureSiteAddressBook
VERSION = "0.0.3"
end
| 13.5 | 29 | 0.759259 |
ed777487b870a8505cdc3c439f460b29424bdb65 | 3,175 | module EE
module LockHelper
def lock_file_link(project = @project, path = @path, html_options: {})
return unless project.feature_available?(:file_locks) && current_user
return if path.blank?
path_lock = project.find_path_lock(path, downstream: true)
if path_lock
locker = path_lock.user.name
if path_lock.exact?(path)
exact_lock_file_link(path_lock, html_options, locker)
elsif path_lock.upstream?(path)
upstream_lock_file_link(path_lock, html_options, locker)
elsif path_lock.downstream?(path)
downstream_lock_file_link(path_lock, html_options, locker)
end
else
_lock_link(current_user, project, html_options: html_options)
end
end
def exact_lock_file_link(path_lock, html_options, locker)
if can_unlock?(path_lock)
html_options[:data] = { state: :unlock }
tooltip = path_lock.user == current_user ? '' : "Locked by #{locker}"
enabled_lock_link("Unlock", tooltip, html_options)
else
disabled_lock_link("Unlock", "Locked by #{locker}. You do not have permission to unlock this", html_options)
end
end
def upstream_lock_file_link(path_lock, html_options, locker)
additional_phrase = can_unlock?(path_lock) ? 'Unlock that directory in order to unlock this' : 'You do not have permission to unlock it'
disabled_lock_link("Unlock", "#{locker} has a lock on \"#{path_lock.path}\". #{additional_phrase}", html_options)
end
def downstream_lock_file_link(path_lock, html_options, locker)
additional_phrase = can_unlock?(path_lock) ? 'Unlock this in order to proceed' : 'You do not have permission to unlock it'
disabled_lock_link("Lock", "This directory cannot be locked while #{locker} has a lock on \"#{path_lock.path}\". #{additional_phrase}", html_options)
end
def _lock_link(user, project, html_options: {})
if can?(current_user, :push_code, project)
html_options[:data] = { state: :lock }
enabled_lock_link("Lock", '', html_options)
else
disabled_lock_link("Lock", "You do not have permission to lock this", html_options)
end
end
def disabled_lock_link(label, title, html_options)
html_options['data-toggle'] = 'tooltip'
html_options[:title] = title
html_options[:class] = "#{html_options[:class]} disabled has-tooltip"
content_tag :span, label, html_options
end
def enabled_lock_link(label, title, html_options)
html_options['data-toggle'] = 'tooltip'
html_options[:title] = title
html_options[:class] = "#{html_options[:class]} has-tooltip"
link_to label, '#', html_options
end
def render_lock_icon(path)
return unless @project.feature_available?(:file_locks)
return unless @project.root_ref?(@ref)
if file_lock = @project.find_path_lock(path, exact_match: true)
content_tag(
:i,
nil,
class: "fa fa-lock prepend-left-5 append-right-5",
title: text_label_for_lock(file_lock, path),
'data-toggle' => 'tooltip'
)
end
end
end
end
| 37.352941 | 155 | 0.669291 |
5de7ec2497fd97ed0abe6af131f01991325d9a77 | 2,546 | class LibgpgError < Formula
desc "Common error values for all GnuPG components"
homepage "https://www.gnupg.org/related_software/libgpg-error/"
url "https://gnupg.org/ftp/gcrypt/libgpg-error/libgpg-error-1.42.tar.bz2"
sha256 "fc07e70f6c615f8c4f590a8e37a9b8dd2e2ca1e9408f8e60459c67452b925e23"
license "LGPL-2.1-or-later"
revision 1
livecheck do
url "https://gnupg.org/ftp/gcrypt/libgpg-error/"
regex(/href=.*?libgpg-error[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
sha256 arm64_monterey: "52651d0013588855c79008c9f643490ccfbe6bb19f424f5e2bf7b6d924e382cd"
sha256 arm64_big_sur: "70e6813ed4afc576346a5fb6aa2670f0004bcc67c63b19bc4d83c9d88451ba0a"
sha256 monterey: "620a34647a3c5bb70427b846792674187a39f58e18688cf29d88cf48bacd28bb"
sha256 big_sur: "6fa4b76fb160c8c75d4d1f932c3c920902a97474741397def5d4000201e85436"
sha256 catalina: "b9b74abe24d72b7ffecc89aba01d370d5f60d232af1c4bbeebe4a8fd3f54b907"
sha256 mojave: "1708cb4a9d2a4ac4e49bc37d9b7bbd259e1c5cfb1ffeb070bc956058e3081f47"
sha256 x86_64_linux: "f81788fbebc232e9d57e82ba29dc9e0387be0190f2e9e1fad802ef97b24b5358"
end
# libgpg-error's libtool.m4 doesn't properly support macOS >= 11.x (see
# libtool.rb formula). This causes the library to be linked with a flat
# namespace which might cause issues when dynamically loading the library with
# dlopen under some modes, see:
#
# https://lists.gnupg.org/pipermail/gcrypt-devel/2021-September/005176.html
#
# We patch `configure` directly so we don't need additional build dependencies
# (e.g. autoconf, automake, libtool)
#
# This patch has been applied upstream so it can be removed in the next
# release.
#
# https://git.gnupg.org/cgi-bin/gitweb.cgi?p=libgpg-error.git;a=commit;h=a3987e44970505a5540f9702c1e41292c22b69cf
patch do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/03cf8088210822aa2c1ab544ed58ea04c897d9c4/libtool/configure-pre-0.4.2.418-big_sur.diff"
sha256 "83af02f2aa2b746bb7225872cab29a253264be49db0ecebb12f841562d9a2923"
end
def install
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}",
"--enable-static"
system "make", "install"
# avoid triggering mandatory rebuilds of software that hard-codes this path
inreplace bin/"gpg-error-config", prefix, opt_prefix
end
test do
system "#{bin}/gpg-error-config", "--libs"
end
end
| 43.896552 | 154 | 0.739984 |
1c550c1335512ee2f6d8b54edf3fa3bf39a4b9d3 | 37 | puts "Hello, this is core image tool" | 37 | 37 | 0.756757 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.