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
|
---|---|---|---|---|---|
e2d00029e63b41088ad5b6660a2bdd3a49c43fcb | 65 | module ActiveStorage
Service::ImgurService = Imgur::Service
end | 21.666667 | 40 | 0.815385 |
b93309cf833f940ef5df694f24b6071ee8fd3abc | 2,886 | # 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::CDN::Mgmt::V2020_09_01
module Models
#
# Result of the request to list endpoints. It contains a list of endpoint
# objects and a URL link to get the next set of results.
#
class EndpointListResult
include MsRestAzure
include MsRest::JSONable
# @return [Array<Endpoint>] List of CDN endpoints within a profile
attr_accessor :value
# @return [String] URL to get the next set of endpoint objects if there
# is any.
attr_accessor :next_link
# return [Proc] with next page method call.
attr_accessor :next_method
#
# Gets the rest of the items for the request, enabling auto-pagination.
#
# @return [Array<Endpoint>] operation results.
#
def get_all_items
items = @value
page = self
while page.next_link != nil && !page.next_link.strip.empty? do
page = page.get_next_page
items.concat(page.value)
end
items
end
#
# Gets the next page of results.
#
# @return [EndpointListResult] with next page content.
#
def get_next_page
response = @next_method.call(@next_link).value! unless @next_method.nil?
unless response.nil?
@next_link = response.body.next_link
@value = response.body.value
self
end
end
#
# Mapper for EndpointListResult class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'EndpointListResult',
type: {
name: 'Composite',
class_name: 'EndpointListResult',
model_properties: {
value: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'value',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'EndpointElementType',
type: {
name: 'Composite',
class_name: 'Endpoint'
}
}
}
},
next_link: {
client_side_validation: true,
required: false,
serialized_name: 'nextLink',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 28.294118 | 80 | 0.524602 |
2642fbd1fdcccd2801c288bca074a3be8cc2f5e9 | 2,428 | require 'helper'
describe "watch expression" do
# Custom eval that will:
# 1) Create an instance of pry that can use for multiple calls
# 2) Exercise the after_eval hook
# 3) Return the output
def eval(expr)
output = @tester.eval expr
@tester.pry.hooks.exec_hook :after_eval, nil, @tester.pry
output
end
before do
@tester = pry_tester
@tester.pry.hooks.clear :after_eval
eval "watch --delete"
end
it "registers the after_eval hook" do
eval 'watch 1+1'
@tester.pry.hooks.hook_exists?(:after_eval, :watch_expression).should == true
end
it "prints no watched expressions" do
eval('watch').should =~ /No watched expressions/
end
it "watches an expression" do
eval "watch 1+1"
eval('watch').should =~ /=> 2/
end
it "watches a local variable" do
eval 'foo = :bar'
eval 'watch foo'
eval('watch').should =~ /=> :bar/
end
it "prints when an expression changes" do
ReplTester.start do
input 'a = 1'
output '=> 1'
input 'watch a'
output "Watching a\nwatch: a => 1"
input "a = 2"
output "watch: a => 2\n=> 2"
end
end
it "prints when an expression is mutated" do
ReplTester.start do
input 'a = "one"'
output '=> "one"'
input 'watch a'
output %(Watching a\nwatch: a => "one")
input "a.sub! 'o', 'p'"
output %(watch: a => "pne"\n=> "pne")
end
end
it "doesn't print when an expresison remains the same" do
ReplTester.start do
input 'a = 1'
output '=> 1'
input 'watch a'
output "Watching a\nwatch: a => 1"
input "a = 1"
output "=> 1"
end
end
it "continues to work if you start a second pry instance" do
ReplTester.start do
input 'a = 1'
output '=> 1'
input 'watch a'
output "Watching a\nwatch: a => 1"
input "a = 2"
output "watch: a => 2\n=> 2"
end
ReplTester.start do
input 'b = 1'
output '=> 1'
input 'watch b'
output "Watching b\nwatch: b => 1"
input "b = 2"
output "watch: b => 2\n=> 2"
end
end
describe "deleting expressions" do
before do
eval 'watch :keeper'
eval 'watch :delete'
eval 'watch -d 2'
end
it "keeps keeper" do
eval('watch').should =~ /keeper/
end
it "deletes delete" do
eval('watch').should.not =~ /delete/
end
end
end
| 20.233333 | 81 | 0.574135 |
91ee2772700264a089400ec1df4de4954b23499a | 5,662 | require_relative '../../models/game'
require_relative '../../models/player'
require_relative '../../models/board'
RSpec.describe Board do
let(:x_marker) { "X" }
let(:o_marker) { "O" }
let(:three_in_a_row_board) { [nil,nil,nil,nil,o_marker,o_marker,x_marker,x_marker,x_marker] }
let(:three_vertical_board) { [nil,nil,x_marker,o_marker,o_marker,x_marker,x_marker,o_marker,x_marker] }
let(:three_diagonal_board){ [x_marker,nil,nil,o_marker,x_marker,o_marker,x_marker,o_marker,x_marker] }
let(:three_other_diagonal_board) { [nil,nil,x_marker,o_marker,x_marker,o_marker,x_marker,o_marker,x_marker] }
let(:no_winners_board) { [o_marker,x_marker,o_marker,x_marker,x_marker,o_marker,x_marker,o_marker,x_marker] }
let(:incomplete_board) { [nil,nil,nil,nil,x_marker,o_marker,x_marker,o_marker,x_marker] }
let(:bottom_row_full_board) { [nil,nil,nil,nil,nil,nil,x_marker,o_marker,x_marker] }
let(:default_board) { Board.new() }
let(:tie_board) { Board.new(no_winners_board) }
let(:x_row_win) { Board.new(three_in_a_row_board) }
let(:x_vertical_win) { Board.new(three_vertical_board) }
let(:x_diagonal_win) { Board.new(three_diagonal_board) }
let(:x_other_diagonal_win) { Board.new(three_other_diagonal_board) }
let(:bottom_row_full) { Board.new(bottom_row_full_board) }
let(:unfinished_board) { Board.new(incomplete_board) }
describe "#initialize" do
context "when board is provided" do
it "sets the grid as provided board" do
expect(tie_board.grid).to eq no_winners_board
end
it "does not set the grid as default board" do
expect(tie_board.grid).not_to eq default_board.grid
end
end
context "when board is not provided" do
it "generates a default grid with nil values" do
expect(default_board.grid.all? {|value| value.nil? }).to eq true
end
end
end
describe "#has_row_match?" do
context "when three in a row" do
it "returns true" do
expect(x_row_win.has_row_match?(x_marker)).to eq true
end
end
context "when three X vertical" do
it "returns false" do
expect(x_vertical_win.has_row_match?(x_marker)).to eq false
end
end
end
describe "#has_vertical_match?" do
context "when three X in a row" do
it "returns false" do
expect(x_row_win.has_vertical_match?(x_marker)).to eq false
end
end
context "when three X vertical" do
it "returns true" do
expect(x_vertical_win.has_vertical_match?(x_marker)).to eq true
end
end
end
describe "#has_three_consecutive_match?" do
context "when three in a row" do
it "returns true" do
expect(x_row_win.has_three_consecutive_match?(x_marker,[0,3,6], 1, 2)).to eq true
end
end
end
describe "#has_diagonal_match?" do
context "when three X in a row" do
it "returns false" do
expect(x_row_win.has_diagonal_match?(x_marker)).to eq false
end
end
context "when three X diagonal" do
it "returns true" do
expect(x_diagonal_win.has_diagonal_match?(x_marker)).to eq true
end
end
end
describe "#has_other_diagonal_match?" do
context "when three X in a row" do
it "returns false" do
expect(x_row_win.has_other_diagonal_match?(x_marker)).to eq false
end
end
context "when three X other diagonal" do
it "returns true" do
expect(x_other_diagonal_win.has_other_diagonal_match?(x_marker)).to eq true
end
end
end
describe "#is_full?" do
context "when board is full" do
it "returns true" do
expect(tie_board.is_full?).to eq true
end
end
context "when board is empty" do
it "returns false" do
expect(default_board.is_full?).to eq false
end
end
context "when board is incomplete" do
it "returns false" do
expect(unfinished_board.is_full?).to eq false
end
end
end
describe "#is_winner?" do
context "when three X in a row" do
it "X returns true" do
expect(x_row_win.is_winner?(x_marker)).to eq true
end
it "O returns false" do
expect(x_row_win.is_winner?(o_marker)).to eq false
end
end
context "when board has no winner" do
it "X returns false" do
expect(tie_board.is_winner?(x_marker)).to eq false
end
it "O returns false" do
expect(tie_board.is_winner?(o_marker)).to eq false
end
end
end
describe "#remaining_options" do
context "when board has spots 0, 1, 2, 3 open" do
it "returns [0, 1, 2, 3]" do
expect(unfinished_board.remaining_options).to eq [0,1,2,3]
end
it "does not return 4, 5, 6, 7 or 8" do
[4,5,6,7,8].each do |invalid_tile|
expect(!unfinished_board.remaining_options.include?(invalid_tile)).to eq true
end
end
end
context "when board is full" do
it "returns empty array" do
expect(tie_board.remaining_options).to eq []
end
end
end
describe "#update" do
context "when board is empty" do
it "should return board grid with marker on indicated position" do
default_board.update(1, x_marker)
expect(default_board.grid).to eq [nil,"X",nil,nil,nil,nil,nil,nil,nil]
end
context "when board is full" do
it "should have same grid as before update" do
tie_board.update(1, o_marker)
expect(tie_board.grid).to eq no_winners_board
end
end
end
context "when board is full" do
it "returns empty array" do
expect(tie_board.remaining_options).to eq []
end
end
end
end
| 31.631285 | 111 | 0.665666 |
d5d0a288755e472415c449fedea67825c57c578b | 5,678 | require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper")
describe MetricFu::Grapher do
describe "require_graphing_gem" do
it "should give a warning if trying to use gchart but gem is not installed" do
MetricFu::Configuration.run {|config| config.graph_engine = :gchart}
MetricFu::Grapher.should_receive(:require).with('gchart').and_raise(LoadError)
MetricFu::Grapher.should_receive(:puts).with(/If you want to use google charts/)
MetricFu::Grapher.require_graphing_gem
end
end
end
describe MetricFu::GchartGrapher do
describe "determine_y_axis_scale" do
it "should set defaults when empty array" do
grapher = Object.new.extend(MetricFu::GchartGrapher)
grapher.determine_y_axis_scale([])
grapher.instance_variable_get(:@max_value).should == 10
grapher.instance_variable_get(:@yaxis).should == [0, 2, 4, 6, 8, 10]
end
it "should set max value of the graph above largest value" do
grapher = Object.new.extend(MetricFu::GchartGrapher)
grapher.determine_y_axis_scale([19])
grapher.instance_variable_get(:@max_value).should == 20
grapher.determine_y_axis_scale([20])
grapher.instance_variable_get(:@max_value).should == 25
end
end
end
describe "Gchart graphers" do
before :each do
MetricFu::Configuration.run {|config| config.graph_engine = :gchart}
end
describe "FlayGchartGrapher graph! method" do
it "should set static values for graph" do
grapher = FlayGchartGrapher.new
expected = {
:size => MetricFu::GchartGrapher::GCHART_GRAPH_SIZE,
:title => URI.escape("Flay: duplication"),
:axis_with_labels => 'x,y',
:format => 'file',
:filename => File.join(MetricFu.output_directory, 'flay.png'),
}
Gchart.should_receive(:line).with(hash_including(expected))
grapher.graph!
end
end
describe "FlogGchartGrapher graph! method" do
it "should set static values for graph" do
grapher = FlogGchartGrapher.new
expected = {
:size => MetricFu::GchartGrapher::GCHART_GRAPH_SIZE,
:title => URI.escape("Flog: code complexity"),
:stacked => false,
:bar_colors => MetricFu::GchartGrapher::COLORS[0..1],
:legend => ['average', 'top 5% average'],
:custom => "chdlp=t",
:axis_with_labels => 'x,y',
:format => 'file',
:filename => File.join(MetricFu.output_directory, 'flog.png'),
}
Gchart.should_receive(:line).with(hash_including(expected))
grapher.graph!
end
end
describe "RcovGchartGrapher graph! method" do
it "should set static values for graph" do
grapher = RcovGchartGrapher.new
expected = {
:size => MetricFu::GchartGrapher::GCHART_GRAPH_SIZE,
:title => URI.escape("Rcov: code coverage"),
:max_value => 101,
:axis_with_labels => 'x,y',
:axis_labels => [grapher.labels.values, [0,20,40,60,80,100]],
:format => 'file',
:filename => File.join(MetricFu.output_directory, 'rcov.png'),
}
Gchart.should_receive(:line).with(hash_including(expected))
grapher.graph!
end
end
describe "ReekGchartGrapher graph! method" do
it "should set static values for graph" do
grapher = ReekGchartGrapher.new
expected = {
:size => MetricFu::GchartGrapher::GCHART_GRAPH_SIZE,
:title => URI.escape("Reek: code smells"),
:stacked => false,
:bar_colors => MetricFu::GchartGrapher::COLORS,
:axis_with_labels => 'x,y',
:format => 'file',
:filename => File.join(MetricFu.output_directory, 'reek.png'),
}
Gchart.should_receive(:line).with(hash_including(expected))
grapher.graph!
end
end
describe "RoodiGchartGrapher graph! method" do
it "should set static values for graph" do
grapher = RoodiGchartGrapher.new
expected = {
:size => MetricFu::GchartGrapher::GCHART_GRAPH_SIZE,
:title => URI.escape("Roodi: potential design problems"),
:axis_with_labels => 'x,y',
:format => 'file',
:filename => File.join(MetricFu.output_directory, 'roodi.png'),
}
Gchart.should_receive(:line).with(hash_including(expected))
grapher.graph!
end
end
describe "StatsGchartGrapher graph! method" do
it "should set static values for graph" do
grapher = StatsGchartGrapher.new
expected = {
:size => MetricFu::GchartGrapher::GCHART_GRAPH_SIZE,
:title => URI.escape("Stats: LOC & LOT"),
:bar_colors => MetricFu::GchartGrapher::COLORS[0..1],
:legend => ['Lines of code', 'Lines of test'],
:custom => "chdlp=t",
:axis_with_labels => 'x,y',
:format => 'file',
:filename => File.join(MetricFu.output_directory, 'stats.png'),
}
Gchart.should_receive(:line).with(hash_including(expected))
grapher.graph!
end
end
describe "RailsBestPracticesGchartGrapher graph! method" do
it "should set static values for graph" do
grapher = RailsBestPracticesGchartGrapher.new
expected = {
:size => MetricFu::GchartGrapher::GCHART_GRAPH_SIZE,
:title => URI.escape("Rails Best Practices: design problems"),
:bar_colors => MetricFu::GchartGrapher::COLORS[0..1],
:legend => ['Problems'],
:custom => "chdlp=t",
:axis_with_labels => 'x,y',
:format => 'file',
:filename => File.join(MetricFu.output_directory, 'rails_best_practices.png'),
}
Gchart.should_receive(:line).with(hash_including(expected))
grapher.graph!
end
end
end
| 36.165605 | 86 | 0.644241 |
d5c96278f1b4ec295db66b30ef1ddd1d70fa7994 | 1,029 | module Arcade
# Arcade::Init.connect environment
# --------------------------------
# initializes the database connection
# and returns the active database handle
#
# The database cannot switched later
#
#
# Arcade::Init.db
# --------------
# returns an instance of the database handle
#
class Init
extend Dry::Core::ClassAttributes
defines :db # database handle
def self.connect e= :development
env = if e.to_s =~ /^p/
:production
elsif e.to_s =~ /^t/
:test
else
:development
end
# set the class attribute
db Database.new(env)
end
end
# Provides method `db` to every Model class
class Base
def self.db
Init.db
end
# expose db to instance methods as well
private define_method :db, &method(:db)
private_class_method :db
end
# Provides method `db` to every Query-Object
class Query
def db
Init.db
end
end
end
| 20.176471 | 47 | 0.558795 |
017b7a0a5fb960b5f2ac6bb681ff4c7766f32797 | 2,549 | class Music::DjEventsController < ApplicationController
include ErrorHelper
before_action :authenticate_user!, except: [:index, :show]
before_action :authenticate_admin!, except: [:index, :show]
# GET /music/dj
# GET /music/dj.json
# GET /music/dj.xml
def index
Project.hit 19
@dj_events = DjEvent.order(@order).paginate(@page)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @dj_events, callback: params[:callback] }
format.xml { render xml: @dj_events }
end
end
# GET /music/dj/1
# GET /music/dj/1.json
# GET /music/dj/1.xml
def show
Project.hit 19
@dj_event = DjEvent.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @dj_event, methods: [:dj_tracks], callback: params[:callback] }
format.xml { render xml: @dj_event }
end
end
# GET /music/dj/new
# GET /music/dj/new.json
# GET /music/dj/new.xml
def new
@dj_event = DjEvent.new
respond_to do |format|
format.html # index.html.erb
format.json { render json: @dj_event, callback: params[:callback] }
format.xml { render xml: @dj_event }
end
end
# GET /music/dj/1/edit
def edit
@dj_event = DjEvent.find(params[:id])
end
# POST /music/dj
# POST /music/dj.json
def create
@dj_event = DjEvent.new(params[:account])
respond_to do |format|
if @dj_event.save
format.html { redirect_to @dj_event, notice: 'DJ Event was successfully created.' }
format.json { render json: @dj_event, status: :created, location: @dj_event }
else
format.html { render action: "new" }
format.json { render json: @dj_event.errors, status: :unprocessable_entity }
end
end
end
# PUT /music/dj/1
# PUT /music/dj/1.json
def update
@dj_event = DjEvent.find(params[:id])
respond_to do |format|
if @dj_event.update(params[:dj_event])
format.html { redirect_to @dj_event, notice: 'Event post was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @dj_event.errors, status: :unprocessable_entity }
end
end
end
# DELETE /music/dj/1
# DELETE /music/dj/1.json
def destroy
@dj_event = DjEvent.find(params[:id])
@dj_event.destroy
respond_to do |format|
format.html { redirect_to music_dj_events_url }
format.json { head :no_content }
end
end
end
| 24.27619 | 96 | 0.641428 |
1a48b62b89996c8406da79b99c32b5c139fa06c9 | 3,054 | class Shape < ActiveRecord::Base
extend IsDateable
include KmapsEngine::IsNotable
include KmapsEngine::IsCitable
belongs_to :feature, foreign_key: 'fid', primary_key: 'fid', touch: true
# after_save { |record| record.feature.touch if !record.feature.nil? }
# after_destroy { |record| record.feature.touch if !record.feature.nil? }
self.primary_key = 'gid'
def lat
# if done with rgeo:
# self.geometry.nil? ? nil : self.geometry.y
# If done directly from db:
self.geometry.nil? ? nil : Shape.select('ST_Y(geometry) as st_y').find(self.id).st_y
end
def lng
# if done with rgeo:
# self.geometry.nil? ? nil : self.geometry.x
# If done directly from db:
self.geometry.nil? ? nil : Shape.select('ST_X(geometry) as st_x').find(self.id).st_x
end
def to_s
if self.is_point?
self.as_text
else
self.geo_type
end
end
def is_point?
# if done with rgeo:
# self.geo_type == RGeo::Feature::Point # if done through db: 'ST_Point'
# if done through db: 'ST_Point'
self.geo_type == 'ST_Point'
end
def geo_type
# if done with rgeo:
# self.geometry.geometry_type
# If done directly from db:
Shape.select('ST_GeometryType(geometry) as geometry_type').find(self.id).geometry_type
end
def geo_type_text
# if done with rgeo:
# self.geometry.geometry_type
# If done directly from db:
Shape.select('GeometryType(geometry) as geometry_type').find(self.id).geometry_type
end
def as_text
# if done with rgeo:
# self.geometry.as_text
# If done directly from db:
Shape.select('ST_AsText(geometry) as astext').find(self.id).astext
end
def as_geojson
# if done with rgeo:
# self.geometry.as_text
# If done directly from db:
Shape.select('ST_AsGeoJSON(geometry) as geojson').find(self.id).geojson
end
def as_ewkt
Shape.select('ST_AsEWKT(geometry) as astext').find(self.id).astext
end
#= Feature ==============================
# A Shape belongs_to (a) Feature
# A Feature has_many Shapes
def self.find_all_by_feature(feature)
Shape.where(fid: feature.fid).order('position, gid')
end
def self.shapes_centroid_by_feature(feature)
centroid = Shape.where(fid: feature.fid).pluck('ST_AsGeoJSON(ST_centroid(ST_collect(geometry))) as asgeojson').first
centroid.nil? ? nil : {type: 'FeatureCollection', features: [ type: 'Feature', geometry: JSON.parse(centroid) ]}.to_json
end
def self.find_all_by_feature_id(feature_id)
self.where(feature_id: Feature.find(feature_id).id)
end
def after_save
self.feature.update_shape_positions
end
end
# == Schema Information
#
# Table name: shapes
#
# gid :integer not null, primary key
# geometry :geometry
# fid :integer
# position :integer default(0), not null
# area :float
# altitude :integer
# is_public :boolean default(TRUE), not null
# created_at :datetime
# updated_at :datetime
#
# updated_at :timestamp
| 26.789474 | 124 | 0.666667 |
7aea89cb8d7da75f68a0d348d3ff3b20fca06715 | 1,175 | require 'spec_helper_acceptance'
# Ensure Password expiration is 365 days or less - Section 5.4.1.1
# Ensure minimum days between password changes is 7 or more - Section 5.4.1.2
# Ensure Pasword Expiration warning days is 7 or more - Section 5.4.1.3
describe file('/etc/login.defs') do
it { is_expected.to be_file }
its(:content) { should match /PASS_MAX_DAYS 365/ }
its(:content) { should match /PASS_MIN_DAYS 7/ }
its(:content) { should match /PASS_WARN_AGE 7/ }
end
# Ensure default group for the root account is GID 0 - Section 5.4.3
describe user('root') do
it { is_expected.to exist }
it { is_expected.to belong_to_group 'root' }
end
# Ensure default user umask is 027 or more restrictive - Section 5.4.4
# Ensure default user shell tieout is 900 seconds or less - Section 5.4.5
describe file('/etc/profile.d/') do
it { is_expected.to be_file }
its(:content) { should match /umask 027/ }
its(:content) { should match /TMOUT=600/ }
end
describe file('/etc/bashrc') do
it { is_expected.to be_file }
its(:content) { should match /umask 027/ }
its(:content) { should match /TMOUT=600/ }
end
| 34.558824 | 79 | 0.680851 |
1cf074e9f3e5bd641047274027d643f7bfef1fd2 | 96 | class TrustedMachineSerializer < ActiveModel::Serializer
attributes :id, :checksum, :info
end
| 24 | 56 | 0.802083 |
aca7bb7bffd3a15d54ca5bfd62e61524f5d5ef7f | 974 | =begin
#Xero Projects API
#This is the Xero Projects API
The version of the OpenAPI document: 2.3.2
Contact: [email protected]
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.3.1
=end
require 'time'
require 'date'
module XeroRuby::Projects
class ChargeType
TIME = "TIME".freeze
FIXED = "FIXED".freeze
NON_CHARGEABLE = "NON_CHARGEABLE".freeze
# Builds the enum from string
# @param [String] The enum value in the form of the string
# @return [String] The enum value
def self.build_from_hash(value)
new.build_from_hash(value)
end
# Builds the enum from string
# @param [String] The enum value in the form of the string
# @return [String] The enum value
def build_from_hash(value)
constantValues = ChargeType.constants.select { |c| ChargeType::const_get(c) == value }
raise "Invalid ENUM value #{value} for class #ChargeType" if constantValues.empty?
value
end
end
end
| 24.974359 | 92 | 0.700205 |
1a12b4dffd73f2b40d50fa06ff009983ac25782e | 3,076 | # frozen_string_literal: true
module Reporting
class Kpi
def student_funnel_goal
@student_funnel_goal ||= {
total: Users::Student.count,
confirmed: Users::Student.where.not(confirmed_at: nil).count
}
end
def school_manager_funnel_goal
@school_manager_funnel_goal ||= {
total: School.count,
with_school_manager: School.joins(:users).where(users: { type: Users::SchoolManagement.name }).count
}
end
def last_week_kpis(last_monday: , last_sunday:)
subscriptions = recent_subscriptions(
last_monday: last_monday,
last_sunday: last_sunday
)
applications_count, student_applyers_count = recent_applications(
last_monday: last_monday,
last_sunday: last_sunday
)
offers = internship_offers_count
{
subscriptions: subscriptions,
applications_count: applications_count,
student_applyers_count: student_applyers_count,
offers_count: offers[:offers_count],
public_offers_count: offers[:public_offers_count],
seats_count: offers[:seats_count],
public_seats_count: offers[:public_seats_count]
}
end
private
def recent_subscriptions(last_monday: , last_sunday:)
translator = Presenters::UserManagementRole
subscriptions = User.select('type, count(type)')
.where('created_at >= ? ',last_monday)
.where('created_at <= ?', last_sunday)
.where.not(type: 'Users::SchoolManagement')
.group(:type)
.inject({}) { |hash, rec| hash[translator.human_types_and_roles(rec.type.to_sym)]= rec.count; hash}
Users::SchoolManagement.select('role, count(role)')
.where('created_at >= ? ', last_monday)
.where('created_at <= ?', last_sunday)
.group(:role)
.inject(subscriptions) do |hash, rec|
hash[translator.human_types_and_roles(rec.role.to_sym)]= rec.count; hash
end
end
def recent_applications(last_monday: , last_sunday:)
applications = InternshipApplication.where('created_at >= ? ', last_monday)
.where('created_at <= ?', last_sunday)
applications_students = applications.select('user_id, count(user_id)')
.group(:user_id)
[applications.count, applications_students.pluck(:user_id).count]
end
def internship_offers_count
offers = ::InternshipOffer.kept.in_the_future
public_offers = ::InternshipOffer.kept.in_the_future.where(is_public: true)
{
offers_count: offers.count,
public_offers_count: public_offers.count,
seats_count: offers.pluck(:max_candidates).sum,
public_seats_count: public_offers.pluck(:max_candidates).sum
}
end
def initialize; end
end
end
| 36.619048 | 125 | 0.606632 |
3929bf9e92ada15e7487d67cf587923e4417edca | 2,724 | # frozen_string_literal: true
describe "POST /v1/me/reviews" do
describe do
let(:user) { create(:user, :with_profile, :with_setting) }
let(:application) { create(:oauth_application, owner: user) }
let(:access_token) { create(:oauth_access_token, application: application) }
let(:work) { create(:work, :with_current_season) }
it "creates work record" do
expect(Record.count).to eq 0
expect(WorkRecord.count).to eq 0
expect(ActivityGroup.count).to eq 0
expect(Activity.count).to eq 0
data = {
work_id: work.id,
title: "γγ^ο½εΏγγ΄γγγ΄γγγγγγγγ^ο½",
body: "εγ―γγͺγΌγ‘γγοΌβ―οΌ Β΄βο½ οΌβ―",
rating_overall_state: "great",
access_token: access_token.token
}
post api("/v1/me/reviews", data)
expect(response.status).to eq(200)
expect(Record.count).to eq 1
expect(WorkRecord.count).to eq 1
expect(ActivityGroup.count).to eq 1
expect(Activity.count).to eq 1
record = user.records.first
work_record = user.work_records.first
activity_group = user.activity_groups.first
activity = user.activities.first
expect(record.work_id).to eq work.id
expect(work_record.body).to eq "#{data[:title]}\n\n#{data[:body]}"
expect(work_record.locale).to eq "ja"
expect(work_record.rating_overall_state).to eq data[:rating_overall_state]
expect(work_record.record_id).to eq record.id
expect(work_record.work_id).to eq work.id
expect(activity_group.itemable_type).to eq "WorkRecord"
expect(activity_group.single).to eq true
expect(activity.activity_group_id).to eq activity_group.id
expect(activity.itemable).to eq work_record
expect(json["id"]).to eq work_record.id
expect(json["body"]).to eq "#{data[:title]}\n\n#{data[:body]}"
expect(json["rating_overall_state"]).to eq data[:rating_overall_state]
end
end
context "when input data is invalid" do
let(:user) { create(:user, :with_profile, :with_setting) }
let(:application) { create(:oauth_application, owner: user) }
let(:access_token) { create(:oauth_access_token, application: application) }
let(:work) { create(:work, :with_current_season) }
it "returns error" do
data = {
work_id: work.id,
body: "γγ^ο½εΏγγ΄γγγ΄γγγγγγγγ^ο½" * 52_430, # too long body
access_token: access_token.token
}
post api("/v1/me/reviews", data)
expect(response.status).to eq(400)
expected = {
errors: [
{
type: "invalid_params",
message: "ζ¬ζγ―1048596ζεδ»₯ε
γ§ε
₯εγγ¦γγ γγ"
}
]
}
expect(json).to include(expected.deep_stringify_keys)
end
end
end
| 32.047059 | 80 | 0.64464 |
390085afdf6335b8ff2075633b4093b3ab8eb6ad | 4,552 | class Khal < Formula
include Language::Python::Virtualenv
desc "CLI calendar application"
homepage "https://lostpackets.de/khal/"
url "https://files.pythonhosted.org/packages/f2/7d/c7d88bf11e6e62c5671d7b89fbc6dd7ce67d09a79ab8951ed6726791cc48/khal-0.10.3.tar.gz"
sha256 "2fdd8fc14fe597e5a7d6e9c63c7868d960b4ed021b563c684a71f07090eda432"
license "MIT"
head "https://github.com/pimutils/khal.git"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "3cced9430aa43b2bf09eabd48f715eba96fc440183a99ca653cf6bf2909a0f16"
sha256 cellar: :any_skip_relocation, big_sur: "3e90a57da163a0233afe9086d19b20992065b2166905b43971fdd9beda727846"
sha256 cellar: :any_skip_relocation, catalina: "91685e0cb8aee14a698634d66032ca208493c4da59a0871e1275f3edea293048"
sha256 cellar: :any_skip_relocation, mojave: "5eb78b53541dbc953a60345ff433ee5e4a5f1f0c16699cafbf71d5a49f28b509"
end
depends_on "[email protected]"
resource "atomicwrites" do
url "https://files.pythonhosted.org/packages/55/8d/74a75635f2c3c914ab5b3850112fd4b0c8039975ecb320e4449aa363ba54/atomicwrites-1.4.0.tar.gz"
sha256 "ae70396ad1a434f9c7046fd2dd196fc04b12f9e91ffb859164193be8b6168a7a"
end
resource "click" do
url "https://files.pythonhosted.org/packages/27/6f/be940c8b1f1d69daceeb0032fee6c34d7bd70e3e649ccac0951500b4720e/click-7.1.2.tar.gz"
sha256 "d2b5255c7c6349bc1bd1e59e08cd12acbbd63ce649f2588755783aa94dfb6b1a"
end
resource "click-log" do
url "https://files.pythonhosted.org/packages/22/44/3d73579b547f0790a2723728088c96189c8b52bd2ee3c3de8040efc3c1b8/click-log-0.3.2.tar.gz"
sha256 "16fd1ca3fc6b16c98cea63acf1ab474ea8e676849dc669d86afafb0ed7003124"
end
resource "configobj" do
url "https://files.pythonhosted.org/packages/64/61/079eb60459c44929e684fa7d9e2fdca403f67d64dd9dbac27296be2e0fab/configobj-5.0.6.tar.gz"
sha256 "a2f5650770e1c87fb335af19a9b7eb73fc05ccf22144eb68db7d00cd2bcb0902"
end
resource "icalendar" do
url "https://files.pythonhosted.org/packages/58/b8/9aa7963f442b2a8bfdfc40eab8bc399c5eaac5711b8919c52122e4903544/icalendar-4.0.7.tar.gz"
sha256 "0fc18d87f66e0b5da84fa731389496cfe18e4c21304e8f6713556b2e8724a7a4"
end
resource "python-dateutil" do
url "https://files.pythonhosted.org/packages/be/ed/5bbc91f03fa4c839c4c7360375da77f9659af5f7086b7a7bdda65771c8e0/python-dateutil-2.8.1.tar.gz"
sha256 "73ebfe9dbf22e832286dafa60473e4cd239f8592f699aa5adaf10050e6e1823c"
end
resource "pytz" do
url "https://files.pythonhosted.org/packages/b0/61/eddc6eb2c682ea6fd97a7e1018a6294be80dba08fa28e7a3570148b4612d/pytz-2021.1.tar.gz"
sha256 "83a4a90894bf38e243cf052c8b58f381bfe9a7a483f6a9cab140bc7f702ac4da"
end
resource "pyxdg" do
url "https://files.pythonhosted.org/packages/6f/2e/2251b5ae2f003d865beef79c8fcd517e907ed6a69f58c32403cec3eba9b2/pyxdg-0.27.tar.gz"
sha256 "80bd93aae5ed82435f20462ea0208fb198d8eec262e831ee06ce9ddb6b91c5a5"
end
resource "six" do
url "https://files.pythonhosted.org/packages/6b/34/415834bfdafca3c5f451532e8a8d9ba89a21c9743a0c59fbd0205c7f9426/six-1.15.0.tar.gz"
sha256 "30639c035cdb23534cd4aa2dd52c3bf48f06e5f4a941509c8bafd8ce11080259"
end
resource "tzlocal" do
url "https://files.pythonhosted.org/packages/ce/73/99e4cc30db6b21cba6c3b3b80cffc472cc5a0feaf79c290f01f1ac460710/tzlocal-2.1.tar.gz"
sha256 "643c97c5294aedc737780a49d9df30889321cbe1204eac2c2ec6134035a92e44"
end
resource "urwid" do
url "https://files.pythonhosted.org/packages/94/3f/e3010f4a11c08a5690540f7ebd0b0d251cc8a456895b7e49be201f73540c/urwid-2.1.2.tar.gz"
sha256 "588bee9c1cb208d0906a9f73c613d2bd32c3ed3702012f51efe318a3f2127eae"
end
def install
virtualenv_install_with_resources
end
test do
ENV["LC_ALL"] = "en_US.UTF-8"
ENV["LANG"] = "en_US.UTF-8"
(testpath/".calendar/test/01ef8547.ics").write <<~EOS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
DTSTART;VALUE=DATE:20130726
SUMMARY:testevent
DTEND;VALUE=DATE:20130727
LAST-MODIFIED:20130725T142824Z
DTSTAMP:20130725T142824Z
CREATED:20130725T142824Z
UID:01ef8547
END:VEVENT
END:VCALENDAR
EOS
(testpath/".config/khal/config").write <<~EOS
[calendars]
[[test]]
path = #{testpath}/.calendar/test/
color = light gray
[sqlite]
path = #{testpath}/.calendar/khal.db
[locale]
firstweekday = 0
[default]
default_calendar = test
EOS
system "#{bin}/khal", "--no-color", "search", "testevent"
end
end
| 41.009009 | 145 | 0.78471 |
283bb77d745b9f7c717b5c331fa8d0cca54951ce | 12,439 | Given(/^the admin user is logged in$/) do
LoginPage.new.visit_page(new_user_session_path).and.login_with_credentials User.all.third.username, UserTestHelper::DEFAULT_PASSWORD
end
Given(/^the user is a player of the first game$/) do
user = UserTestHelper.create_or_find_user
character = CharacterTestHelper.create_character(user)
CharacterTestHelper.approve_character(user)
GameTestHelper.add_player user, character, to: Game.first
end
Given(/^the other user is a monster of the first game$/) do
user = UserTestHelper.create_or_find_another_user
GameTestHelper.add_monster user, to: Game.first
end
Given(/^the other user is a player of the second game$/) do
user = UserTestHelper.create_or_find_another_user
character = CharacterTestHelper.create_character(user, name: "Nijel the Destroyer")
CharacterTestHelper.approve_character(user)
GameTestHelper.add_player user, character, to: Game.all.second
end
Given(/^the user is a GM for the first game$/) do
GameTestHelper.add_gamesmaster User.first, to: Game.first
end
Given(/^the other user is a GM for the first game$/) do
GameTestHelper.add_gamesmaster User.all.second, to: Game.first
end
Given(/^the other user is a GM for the second game$/) do
GameTestHelper.add_gamesmaster User.all.second, to: Game.all.second
end
# Actions
When(/^the user suspends the other user$/) do
MembersPage.new.suspend_user
end
When(/^the user unsuspends the other user$/) do
MembersPage.new.unsuspend_user
end
When(/^the user deletes the other user$/) do
MembersPage.new.delete_user
end
When(/^the user undeletes the other user$/) do
MembersPage.new.undelete_user
end
When(/^the user purges the other user$/) do
MembersPage.new.purge_user
end
When(/^the user approves the other user$/) do
MembersPage.new.approve_user
end
When(/^the user rejects the other user$/) do
MembersPage.new.reject_user
end
When(/^the user resends the activation email for the other user$/) do
MembersPage.new.resend_activation
end
When(/^the user grants the committee role to the other user$/) do
MembersPage.new.grant_role("committee")
end
When(/^the user revokes the committee role from the other user$/) do
MembersPage.new.revoke_role("committee")
end
When(/^the user grants the web-only role to the other user$/) do
MembersPage.new.grant_role("webonly")
end
When(/^the user revokes the web-only role from the other user$/) do
MembersPage.new.revoke_role("webonly")
end
When(/^the user opens the role dialog$/) do
MembersPage.new.open_role_dialog
end
When(/^the admin user merges the second user into the first user$/) do
MembersPage.new.visit_page(users_path).and.merge_users
end
# Validations
Then(/^the user should be in the Active Members table$/) do
MembersPage.new.check_for_active_user(User.first)
end
Then(/^the other user should be in the Active Members table$/) do
MembersPage.new.check_for_active_user(User.all.second)
end
Then(/^the other user should be in the Web\-only Members table$/) do
MembersPage.new.check_for_webonly_user(User.all.second)
end
Then(/^the other user should be in the Suspended table$/) do
MembersPage.new.check_for_suspended_user(User.all.second)
end
Then(/^the other user should be in the Deleted table$/) do
MembersPage.new.check_for_deleted_user(User.all.second)
end
Then(/^the user should not see any other tables$/) do
MembersPage.new.check_for_table(table: "pending", display: false)
MembersPage.new.check_for_table(table: "suspended", display: false)
MembersPage.new.check_for_table(table: "deleted", display: false)
MembersPage.new.check_for_table(table: "gm-created", display: false)
end
Then(/^the user should not see any user management links$/) do
MembersPage.new.check_for_links(text: "Delete", display: false)
MembersPage.new.check_for_links(text: "Suspend", display: false)
MembersPage.new.check_for_links(text: "Edit roles", display: false)
MembersPage.new.check_for_links(text: "Unsuspend", display: false)
MembersPage.new.check_for_links(text: "Undelete", display: false)
MembersPage.new.check_for_links(text: "Purge", display: false)
MembersPage.new.check_for_links(text: "Approve", display: false)
MembersPage.new.check_for_links(text: "Reject", display: false)
MembersPage.new.check_for_links(text: "Resend activation", display: false)
end
Then(/^the user should not see a merge users link$/) do
MembersPage.new.check_for_links(text: "Merge users", display: false)
end
Then(/^the user should see all other tables$/) do
MembersPage.new.check_for_table(table: "pending")
MembersPage.new.check_for_table(table: "suspended")
MembersPage.new.check_for_table(table: "deleted")
MembersPage.new.check_for_table(table: "gm-created")
end
Then(/^the user should see all user management links$/) do
MembersPage.new.check_for_links(text: "Delete")
MembersPage.new.check_for_links(text: "Suspend")
MembersPage.new.check_for_links(text: "Edit roles")
MembersPage.new.check_for_links(text: "Undelete")
MembersPage.new.check_for_links(text: "Unsuspend")
MembersPage.new.check_for_links(text: "Purge")
MembersPage.new.check_for_links(text: "Approve")
MembersPage.new.check_for_links(text: "Reject")
MembersPage.new.check_for_links(text: "Resend activation")
end
Then(/^the user should see committee user management links$/) do
MembersPage.new.check_for_links(text: "Delete")
MembersPage.new.check_for_links(text: "Suspend")
MembersPage.new.check_for_links(text: "Edit roles")
MembersPage.new.check_for_links(text: "Undelete")
MembersPage.new.check_for_links(text: "Unsuspend")
MembersPage.new.check_for_links(text: "Resend activation")
end
Then(/^the user should not see admin user management links$/) do
MembersPage.new.check_for_links(text: "Approve", display: false)
MembersPage.new.check_for_links(text: "Reject", display: false)
MembersPage.new.check_for_links(text: "Purge", display: false)
end
Then(/^the user should see a merge users link$/) do
MembersPage.new.check_for_links(text: "Merge users")
end
Then(/^the user should see an unsuspend link$/) do
MembersPage.new.check_for_links(text: "Unsuspend")
end
Then(/^the user should see an undelete link$/) do
MembersPage.new.check_for_links(text: "Undelete")
end
Then(/^the user should see a purge link$/) do
MembersPage.new.check_for_links(text: "Purge")
end
Then(/^the user should not see a purge link$/) do
MembersPage.new.check_for_links(text: "Purge", display: false)
end
Then(/^the other user should no longer exist$/) do
MembersPage.new.check_for_links(text: "Ann Other", display: false)
end
Then(/^the second user should no longer exist$/) do
MembersPage.new.check_for_links(text: "Ann Other", display: false)
end
Then(/^an activation email should be sent to the other user$/) do
EmailTestHelper.count_emails_with_subject(User.all.second.email, I18n.t("devise.mailer.confirmation_instructions.subject")).should == 2
end
Then(/^an approval email should be sent to the other user$/) do
EmailTestHelper.count_emails_with_subject(User.all.second.email, I18n.t("email_subjects.approved")).should == 1
end
Then(/^the other user should have the committee role marker$/) do
MembersPage.new.check_for_role(rolename: "committee", user: User.all.second)
end
Then(/^the other user should not have the committee role marker$/) do
MembersPage.new.check_for_role(rolename: "committee", user: User.all.second, display: false)
end
Then(/^the user cannot grant the administrator role$/) do
MembersPage.new.check_role_permission(rolename: "administrator")
end
Then(/^the user cannot grant the committee role$/) do
MembersPage.new.check_role_permission(rolename: "committee")
end
Then(/^the user cannot grant the characterref role$/) do
MembersPage.new.check_role_permission(rolename: "characterref")
end
Then(/^the first user should still have their character$/) do
CharactersPage.new.visit_page(characters_path).and.check_for_character(User.first, Character.first)
end
Then(/^the first user should have the second user's character$/) do
CharactersPage.new.visit_page(characters_path).and.check_for_character(User.first, Character.all.second)
end
Then(/^the first user should still have their message board post$/) do
BoardPage.new.visit_page(board_path(Board.first)).and.check_for_message(from: User.first, containing_text: "First!")
end
Then(/^the first user should have the second user's message board post$/) do
BoardPage.new.visit_page(board_path(Board.first)).and.check_for_message(from: User.first, id: 2, containing_text: "Second!")
end
Then(/^the first user should still have their game application$/) do
GamePage.new.visit_page(game_path(Game.first)).and.check_for_application(from: User.first, containing_text: "First!")
end
Then(/^the first user should have the second user's game application$/) do
GamePage.new.visit_page(game_path(Game.first)).and.check_for_application(from: User.first, containing_text: "Second!")
end
Then(/^the first user should be able to log in as themselves$/) do
HomePage.new.visit_page(root_path).and.log_out
LoginPage.new.visit_page(new_user_session_path).and.login_with_credentials "normaluser", UserTestHelper::DEFAULT_PASSWORD
HomePage.new.check_is_displaying_message I18n.t("devise.sessions.signed_in")
end
Then(/^the first user should not be able to log in as the second user$/) do
HomePage.new.visit_page(root_path).and.log_out
LoginPage.new.visit_page(new_user_session_path).and.login_with_credentials "anotheruser", UserTestHelper::DEFAULT_PASSWORD
HomePage.new.check_is_displaying_message I18n.t("devise.failure.not_found_in_database")
end
Then(/^the first user should not be a first aider$/) do
MembersPage.new.visit_page(users_path).and.check_for_role(rolename: "firstaider", user: User.first, display: false)
end
Then(/^the first user should still be a player on the first game$/) do
GamePage.new.visit_page(game_path(Game.first)).and.check_for_player(User.first, User.first.characters.first)
end
Then(/^the first user should be a player on the second game$/) do
GamePage.new.visit_page(game_path(Game.all.second)).and.check_for_player(User.first, User.first.characters.second)
end
Then(/^the first user should still be on the debrief of the first game$/) do
DebriefPage.new.visit_page(game_path(Game.first)).and.check_for_player(Game.first, User.first, Character.first)
end
Then(/^the first user should be on the debrief of the second game$/) do
DebriefPage.new.visit_page(game_path(Game.all.second)).and.check_for_player(Game.all.second, User.first, Character.all.second)
end
Then(/^the first user should still be a gm on the first game$/) do
GamePage.new.visit_page(game_path(Game.first)).and.check_for_gm(User.first)
end
Then(/^the first user should be a gm on the second game$/) do
GamePage.new.visit_page(game_path(Game.all.second)).and.check_for_gm(User.first)
end
Then(/^the first user should still have their monster point declaration$/) do
MonsterPointsPage.new.visit_page(monster_points_user_path(User.first)).and.check_for_declaration(20)
end
Then(/^the first user should not have the second user's monster point declaration$/) do
MonsterPointsPage.new.visit_page(monster_points_user_path(User.first)).and.check_for_declaration(15, display: false)
end
Then(/^the first user should have the second user's monster point declaration$/) do
MonsterPointsPage.new.visit_page(monster_points_user_path(User.first)).and.check_for_declaration(15)
end
Then(/^the first user should still have their monster point adjustment$/) do
MonsterPointsPage.new.visit_page(monster_points_user_path(User.first)).and.check_for_adjustment(20)
end
Then(/^the first user should not have the second user's monster point adjustment$/) do
MonsterPointsPage.new.visit_page(monster_points_user_path(User.first)).and.check_for_adjustment(15, display: false)
end
Then(/^the first user should have the second user's monster point adjustment$/) do
MonsterPointsPage.new.visit_page(monster_points_user_path(User.first)).and.check_for_adjustment(15)
end
Then(/^the first user should be on the debrief of the game$/) do
DebriefPage.new.visit_page(game_path(Game.first)).and.check_for_player(Game.first, User.first, Character.first)
end
Then(/^the first user should have the second user's GM\-created character$/) do
CharactersPage.new.visit_page(characters_path).and.check_for_undeclared_character(User.first, Character.first)
end
| 38.273846 | 137 | 0.780609 |
032c2e7861391d8c481b63c4f55fb6051ef1beab | 204 | require "spec_helper"
RSpec.describe Unleash do
it "has a version number" do
expect(Unleash::VERSION).not_to be nil
end
it "does something useful" do
expect(false).to eq(false)
end
end
| 15.692308 | 42 | 0.705882 |
bf19cdb748de054a5a968dbffc2f0143f2809580 | 882 | module Releasecop
class Checker
attr_accessor :name, :envs
def initialize(name, envs)
self.name = name
self.envs = envs
end
def check
Dir.chdir(CONFIG_DIR) do
`git clone #{envs.first['git']} --bare #{name} > /dev/null 2>&1`
Dir.chdir(name) do
envs.each do |env|
`git remote add #{env['name']} #{env['git']} > /dev/null 2>&1`
`git fetch #{env['name']} > /dev/null 2>&1`
end
comparisons = []
envs.each_cons(2) do |ahead, behind|
comparisons << Comparison.new(ahead, behind)
end
comparisons.each &:check
@result = Result.new(name, comparisons)
end
end
end
def puts_message(verbose_flag)
@result.puts_message(verbose_flag)
end
def unreleased
@result.unreleased
end
end
end
| 22.05 | 74 | 0.547619 |
bf699ce347c1a4bbae946b02ab60deb974e74cea | 1,864 | #
# Be sure to run `pod lib lint OnebyteSwiftNetworkCycle.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'OnebyteSwiftNetworkCycle'
s.version = '0.2.0'
s.summary = 'Onebyte pod for integrating and performing Network operations for Swift based projects.'
# 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 = 'It contains Managers, Operations and Operation queues to perform RESTful APIs operations used in Swift based applications developed in Onebyte LLC. All the operations are executed using Alamofire SDK.'
s.homepage = 'https://github.com/hammy-dev-world/OnebyteSwiftNetwork'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Humayun Sohail' => '[email protected]' }
s.source = { :git => 'https://github.com/hammy-dev-world/OnebyteSwiftNetwork.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0'
s.source_files = 'OnebyteSwiftNetworkCycle/Classes/**/*'
#s.resource_bundles = {
# 'OnebyteSwiftNetworkCycle' => ['OnebyteSwiftNetworkCycle/DevelopmentPods/*']
# }
#s.public_header_files = 'Pod/Classes/**/*.h'
#s.frameworks = 'Alamofire'
s.dependency 'Alamofire', '~> 4.0'
end
| 45.463415 | 225 | 0.694206 |
6155c2b9ee6744ed86bbd658cda9cc920321ecfd | 13,458 | require_relative "analyzer"
class CellSeg
include MongoMapper::Document
include DataUtilities
safe
timestamps!
after_create :hpf_id_create, :case_id_create
belongs_to :case_data
key :hpf_id, String
key :case_id, String
#matches in table
key :category_region_id, Integer
key :cell_density_per_megapixel, String
key :cell_id, Integer
key :cell_x_position, Integer
key :cell_y_position, Integer
key :phenotype, String
key :tissue_category, String
key :confidence, String
key :cytoplasm_alexa_514_max_normalized_counts_total_weighting, Float
key :cytoplasm_alexa_514_mean_normalized_counts_total_weighting, Float
key :cytoplasm_alexa_514_min_normalized_counts_total_weighting, Float
key :cytoplasm_alexa_514_std_dev_normalized_counts_total_weighting, Float
key :cytoplasm_alexa_514_total_normalized_counts_total_weighting, Float
key :cytoplasm_alexa_594_max_normalized_counts_total_weighting, Float
key :cytoplasm_alexa_594_mean_normalized_counts_total_weighting, Float
key :cytoplasm_alexa_594_min_normalized_counts_total_weighting, Float
key :cytoplasm_alexa_594_std_dev_normalized_counts_total_weighting, Float
key :cytoplasm_alexa_594_total_normalized_counts_total_weighting, Float
key :cytoplasm_area_percent, String
key :cytoplasm_area_pixels, Integer
key :cytoplasm_autofluorescence_max_normalized_counts_total_weighting, Float
key :cytoplasm_autofluorescence_mean_normalized_counts_total_weighting, Float
key :cytoplasm_autofluorescence_min_normalized_counts_total_weighting, Float
key :cytoplasm_autofluorescence_std_dev_normalized_counts_total_weighting, Float
key :cytoplasm_autofluorescence_total_normalized_counts_total_weighting, Float
key :cytoplasm_axis_ratio, Float
key :cytoplasm_compactness, Float
key :cytoplasm_coumarin_max_normalized_counts_total_weighting, Float
key :cytoplasm_coumarin_mean_normalized_counts_total_weighting, Float
key :cytoplasm_coumarin_min_normalized_counts_total_weighting, Float
key :cytoplasm_coumarin_std_dev_normalized_counts_total_weighting, Float
key :cytoplasm_coumarin_total_normalized_counts_total_weighting, Float
key :cytoplasm_cy3_max_normalized_counts_total_weighting, Float
key :cytoplasm_cy3_mean_normalized_counts_total_weighting, Float
key :cytoplasm_cy3_min_normalized_counts_total_weighting, Float
key :cytoplasm_cy3_std_dev_normalized_counts_total_weighting, Float
key :cytoplasm_cy3_total_normalized_counts_total_weighting, Float
key :cytoplasm_cy5_max_normalized_counts_total_weighting, Float
key :cytoplasm_cy5_mean_normalized_counts_total_weighting, Float
key :cytoplasm_cy5_min_normalized_counts_total_weighting, Float
key :cytoplasm_cy5_std_dev_normalized_counts_total_weighting, Float
key :cytoplasm_cy5_total_normalized_counts_total_weighting, Float
key :cytoplasm_dapi_max_normalized_counts_total_weighting, Float
key :cytoplasm_dapi_mean_normalized_counts_total_weighting, Float
key :cytoplasm_dapi_min_normalized_counts_total_weighting, Float
key :cytoplasm_dapi_std_dev_normalized_counts_total_weighting, Float
key :cytoplasm_dapi_total_normalized_counts_total_weighting, Float
key :cytoplasm_fitc_max_normalized_counts_total_weighting, Float
key :cytoplasm_fitc_mean_normalized_counts_total_weighting, Float
key :cytoplasm_fitc_min_normalized_counts_total_weighting, Float
key :cytoplasm_fitc_std_dev_normalized_counts_total_weighting, Float
key :cytoplasm_fitc_total_normalized_counts_total_weighting, Float
key :cytoplasm_major_axis, Float
key :cytoplasm_minor_axis, Float
key :distance_from_process_region_edge_pixels, String
key :distance_from_tissue_category_edge_pixels, String
key :entire_cell_alexa_514_max_normalized_counts_total_weighting, Float
key :entire_cell_alexa_514_mean_normalized_counts_total_weighting, Float
key :entire_cell_alexa_514_min_normalized_counts_total_weighting, Float
key :entire_cell_alexa_514_std_dev_normalized_counts_total_weighting, Float
key :entire_cell_alexa_514_total_normalized_counts_total_weighting, Float
key :entire_cell_alexa_594_max_normalized_counts_total_weighting, Float
key :entire_cell_alexa_594_mean_normalized_counts_total_weighting, Float
key :entire_cell_alexa_594_min_normalized_counts_total_weighting, Float
key :entire_cell_alexa_594_std_dev_normalized_counts_total_weighting, Float
key :entire_cell_alexa_594_total_normalized_counts_total_weighting, Float
key :entire_cell_area_percent, String
key :entire_cell_area_pixels, Integer
key :entire_cell_autofluorescence_max_normalized_counts_total_weighting, Float
key :entire_cell_autofluorescence_mean_normalized_counts_total_weighting, Float
key :entire_cell_autofluorescence_min_normalized_counts_total_weighting, Float
key :entire_cell_autofluorescence_std_dev_normalized_counts_total_weighting, Float
key :entire_cell_autofluorescence_total_normalized_counts_total_weighting, Float
key :entire_cell_axis_ratio, Float
key :entire_cell_compactness, Float
key :entire_cell_coumarin_max_normalized_counts_total_weighting, Float
key :entire_cell_coumarin_mean_normalized_counts_total_weighting, Float
key :entire_cell_coumarin_min_normalized_counts_total_weighting, Float
key :entire_cell_coumarin_std_dev_normalized_counts_total_weighting, Float
key :entire_cell_coumarin_total_normalized_counts_total_weighting, Float
key :entire_cell_cy3_max_normalized_counts_total_weighting, Float
key :entire_cell_cy3_mean_normalized_counts_total_weighting, Float
key :entire_cell_cy3_min_normalized_counts_total_weighting, Float
key :entire_cell_cy3_std_dev_normalized_counts_total_weighting, Float
key :entire_cell_cy3_total_normalized_counts_total_weighting, Float
key :entire_cell_cy5_max_normalized_counts_total_weighting, Float
key :entire_cell_cy5_mean_normalized_counts_total_weighting, Float
key :entire_cell_cy5_min_normalized_counts_total_weighting, Float
key :entire_cell_cy5_std_dev_normalized_counts_total_weighting, Float
key :entire_cell_cy5_total_normalized_counts_total_weighting, Float
key :entire_cell_dapi_max_normalized_counts_total_weighting, Float
key :entire_cell_dapi_mean_normalized_counts_total_weighting, Float
key :entire_cell_dapi_min_normalized_counts_total_weighting, Float
key :entire_cell_dapi_std_dev_normalized_counts_total_weighting, Float
key :entire_cell_dapi_total_normalized_counts_total_weighting, Float
key :entire_cell_fitc_max_normalized_counts_total_weighting, Float
key :entire_cell_fitc_mean_normalized_counts_total_weighting, Float
key :entire_cell_fitc_min_normalized_counts_total_weighting, Float
key :entire_cell_fitc_std_dev_normalized_counts_total_weighting, Float
key :entire_cell_fitc_total_normalized_counts_total_weighting, Float
key :entire_cell_major_axis, Float
key :entire_cell_minor_axis, Float
key :inform_21543024864, String
key :lab_id, String
key :membrane_alexa_514_max_normalized_counts_total_weighting, Float
key :membrane_alexa_514_mean_normalized_counts_total_weighting, Float
key :membrane_alexa_514_min_normalized_counts_total_weighting, Float
key :membrane_alexa_514_std_dev_normalized_counts_total_weighting, Float
key :membrane_alexa_514_total_normalized_counts_total_weighting, Float
key :membrane_alexa_594_max_normalized_counts_total_weighting, Float
key :membrane_alexa_594_mean_normalized_counts_total_weighting, Float
key :membrane_alexa_594_min_normalized_counts_total_weighting, Float
key :membrane_alexa_594_std_dev_normalized_counts_total_weighting, Float
key :membrane_alexa_594_total_normalized_counts_total_weighting, Float
key :membrane_area_percent, String
key :membrane_area_pixels, Integer
key :membrane_autofluorescence_max_normalized_counts_total_weighting, Float
key :membrane_autofluorescence_mean_normalized_counts_total_weighting, Float
key :membrane_autofluorescence_min_normalized_counts_total_weighting, Float
key :membrane_autofluorescence_std_dev_normalized_counts_total_weighting, Float
key :membrane_autofluorescence_total_normalized_counts_total_weighting, Float
key :membrane_axis_ratio, Float
key :membrane_compactness, Float
key :membrane_coumarin_max_normalized_counts_total_weighting, Float
key :membrane_coumarin_mean_normalized_counts_total_weighting, Float
key :membrane_coumarin_min_normalized_counts_total_weighting, Float
key :membrane_coumarin_std_dev_normalized_counts_total_weighting, Float
key :membrane_coumarin_total_normalized_counts_total_weighting, Float
key :membrane_cy3_max_normalized_counts_total_weighting, Float
key :membrane_cy3_mean_normalized_counts_total_weighting, Float
key :membrane_cy3_min_normalized_counts_total_weighting, Float
key :membrane_cy3_std_dev_normalized_counts_total_weighting, Float
key :membrane_cy3_total_normalized_counts_total_weighting, Float
key :membrane_cy5_max_normalized_counts_total_weighting, Float
key :membrane_cy5_mean_normalized_counts_total_weighting, Float
key :membrane_cy5_min_normalized_counts_total_weighting, Float
key :membrane_cy5_std_dev_normalized_counts_total_weighting, Float
key :membrane_cy5_total_normalized_counts_total_weighting, Float
key :membrane_dapi_max_normalized_counts_total_weighting, Float
key :membrane_dapi_mean_normalized_counts_total_weighting, Float
key :membrane_dapi_min_normalized_counts_total_weighting, Float
key :membrane_dapi_std_dev_normalized_counts_total_weighting, Float
key :membrane_dapi_total_normalized_counts_total_weighting, Float
key :membrane_fitc_max_normalized_counts_total_weighting, Float
key :membrane_fitc_mean_normalized_counts_total_weighting, Float
key :membrane_fitc_min_normalized_counts_total_weighting, Float
key :membrane_fitc_std_dev_normalized_counts_total_weighting, Float
key :membrane_fitc_total_normalized_counts_total_weighting, Float
key :membrane_major_axis, Float
key :membrane_minor_axis, Float
key :nucleus_alexa_514_max_normalized_counts_total_weighting, Float
key :nucleus_alexa_514_mean_normalized_counts_total_weighting, Float
key :nucleus_alexa_514_min_normalized_counts_total_weighting, Float
key :nucleus_alexa_514_std_dev_normalized_counts_total_weighting, Float
key :nucleus_alexa_514_total_normalized_counts_total_weighting, Float
key :nucleus_alexa_594_max_normalized_counts_total_weighting, Float
key :nucleus_alexa_594_mean_normalized_counts_total_weighting, Float
key :nucleus_alexa_594_min_normalized_counts_total_weighting, Float
key :nucleus_alexa_594_std_dev_normalized_counts_total_weighting, Float
key :nucleus_alexa_594_total_normalized_counts_total_weighting, Float
key :nucleus_area_percent, String
key :nucleus_area_pixels, Integer
key :nucleus_autofluorescence_max_normalized_counts_total_weighting, Float
key :nucleus_autofluorescence_mean_normalized_counts_total_weighting, Float
key :nucleus_autofluorescence_min_normalized_counts_total_weighting, Float
key :nucleus_autofluorescence_std_dev_normalized_counts_total_weighting, Float
key :nucleus_autofluorescence_total_normalized_counts_total_weighting, Float
key :nucleus_axis_ratio, Float
key :nucleus_compactness, Float
key :nucleus_coumarin_max_normalized_counts_total_weighting, Float
key :nucleus_coumarin_mean_normalized_counts_total_weighting, Float
key :nucleus_coumarin_min_normalized_counts_total_weighting, Float
key :nucleus_coumarin_std_dev_normalized_counts_total_weighting, Float
key :nucleus_coumarin_total_normalized_counts_total_weighting, Float
key :nucleus_cy3_max_normalized_counts_total_weighting, Float
key :nucleus_cy3_mean_normalized_counts_total_weighting, Float
key :nucleus_cy3_min_normalized_counts_total_weighting, Float
key :nucleus_cy3_std_dev_normalized_counts_total_weighting, Float
key :nucleus_cy3_total_normalized_counts_total_weighting, Float
key :nucleus_cy5_max_normalized_counts_total_weighting, Float
key :nucleus_cy5_mean_normalized_counts_total_weighting, Float
key :nucleus_cy5_min_normalized_counts_total_weighting, Float
key :nucleus_cy5_std_dev_normalized_counts_total_weighting, Float
key :nucleus_cy5_total_normalized_counts_total_weighting, Float
key :nucleus_dapi_max_normalized_counts_total_weighting, Float
key :nucleus_dapi_mean_normalized_counts_total_weighting, Float
key :nucleus_dapi_min_normalized_counts_total_weighting, Float
key :nucleus_dapi_std_dev_normalized_counts_total_weighting, Float
key :nucleus_dapi_total_normalized_counts_total_weighting, Float
key :nucleus_fitc_max_normalized_counts_total_weighting, Float
key :nucleus_fitc_mean_normalized_counts_total_weighting, Float
key :nucleus_fitc_min_normalized_counts_total_weighting, Float
key :nucleus_fitc_std_dev_normalized_counts_total_weighting, Float
key :nucleus_fitc_total_normalized_counts_total_weighting, Float
key :nucleus_major_axis, Float
key :nucleus_minor_axis, Float
key :path, String
key :process_region_id, String
key :sample_name, String
key :slide_id, String
key :tissue_category_area_pixels, String
key :tma_column, Integer
key :tma_field, Integer
key :tma_row, Integer
key :tma_sector, Integer
key :total_cells, String
def hpf_id_create
self.hpf_id=/.*\]/.match(self.sample_name).to_s.gsub(" ","_")
end
def case_id_create
m=/(.*)_HP.*/.match(self.hpf_id)
self.case_id=m[1].to_s if m
end
end
CellSeg.ensure_index(:hpf_id)
CellSeg.ensure_index(:case_id)
| 56.546218 | 84 | 0.881855 |
0330442b91774d108e0a4441f8729ea9fe34df78 | 780 | module FbApi::AccountLink
def account_link
@message.merge!(
message: {
attachment: {
type: 'template',
payload: {
template_type: 'generic',
elements: [{
title: 'ΠΡΠΈΠ²ΡΡ, ΠΌΠ΅Π½Π΅ Π·Π²Π°ΡΠΈ ΠΡΠ°ΠΉΠ΄Π΅Ρ, Π° Π²Π°Ρ ΡΠΊ ?',
image_url: 'http://drider.io/assets/landing/car-bfd8fa3ca5ec5db3757ba8f6a3ec576741d5cc7aee58a0d43a9948338fbe8404.jpg',
buttons: [
{
type: "account_link",
url: Rails.application.routes.url_helpers.new_users_login_url,
}
]
}]
}
}
}
)
self
end
end
| 30 | 143 | 0.433333 |
016761620c018aad000f4403d7dbf8bb790137b6 | 479 | class MavenShell < Formula
desc "Shell for Maven"
homepage "http://shell.sonatype.org/"
url "https://search.maven.org/remotecontent?filepath=org/sonatype/maven/shell/dist/mvnsh-assembly/1.1.0/mvnsh-assembly-1.1.0-bin.tar.gz"
sha256 "584008d726bf6f90271f4ccd03b549773cbbe62ba7e92bf131e67df3ac5a41ac"
bottle :unneeded
def install
# Remove windows files.
rm_f Dir["bin/*.bat"]
libexec.install Dir["*"]
bin.install_symlink libexec/"bin/mvnsh"
end
end
| 29.9375 | 138 | 0.743215 |
6a46e1dc05e03026ea7a505ee6772dc0ae894606 | 101 | require "amaretti/version"
require "amaretti/engine"
module Amaretti
# Your code goes here...
end
| 14.428571 | 26 | 0.752475 |
289caa753a5743d7e3e1b82228660c6f75eb7906 | 2,528 | module Fog
module Parsers
module Storage
module Google
class GetBucketObjectVersions < Fog::Parsers::Base
def reset
@delete_marker = { 'Owner' => {} }
@version = { 'Owner' => {} }
@in_delete_marke = false
@in_version = false
@response = { 'Versions' => [] }
end
def start_element(name, attrs = [])
super
case name
when 'DeleteMarker'
@in_delete_marker = true
when 'Version'
@in_version = true
end
end
def end_element(name)
case name
when 'DeleteMarker'
@response['Versions'] << {'DeleteMarker' => @delete_marker }
@delete_marker = { 'Owner' => {} }
@in_delete_marker = false
when 'Version'
@response['Versions'] << {'Version' => @version }
@version = { 'Owner' => {} }
@in_version = false
when 'DisplayName', 'ID'
if @in_delete_marker
@delete_marker
elsif @in_version
@version
end['Owner'][name] = value
when 'ETag'
@version[name] = value.gsub('"', '')
when 'IsLatest'
if @in_delete_marker
@delete_marker
elsif @in_version
@version
end['IsLatest'] = if value == 'true'
true
else
false
end
when 'IsTruncated'
if value == 'true'
@response['IsTruncated'] = true
else
@response['IsTruncated'] = false
end
when 'LastModified'
if @in_delete_marker
@delete_marker
elsif @in_version
@version
end['LastModified'] = Time.parse(value)
when 'KeyMarker', 'Name', 'Prefix', 'VersionIdMarker'
@response[name] = value
when 'MaxKeys'
@response['MaxKeys'] = value.to_i
when 'Size'
@version['Size'] = value.to_i
when 'Key', 'Name', 'StorageClass', 'VersionId'
if @in_delete_marker
@delete_marker
elsif @in_version
@version
end[name] = value
end
end
end
end
end
end
end
| 29.741176 | 74 | 0.438291 |
03e7eef7d8623582473d31f3d975bc0ff96de874 | 47 | class ReportedUserList < ApplicationRecord
end
| 15.666667 | 42 | 0.87234 |
e2b1e9b12eb78f32d921329ca1727d9ef08094bf | 3,135 | # frozen_string_literal: true
require "rails_helper"
module Renalware
module Feeds
module Files
module PracticeMemberships
describe ImportCSV do
let(:uk) { create(:united_kingdom) }
def with_tmpfile(content)
tmpfile = Tempfile.new("test_csv", Rails.root.join("tmp"))
tmpfile.write(content)
tmpfile.rewind
::File.chmod(0604, tmpfile)
yield Pathname(tmpfile)
ensure
tmpfile.close
tmpfile.unlink
end
context "when there are new memberships" do
it "imports the GP memberships" do
create(:practice, code: "PRAC_1")
create(:practice, code: "PRAC_2")
gp1 = create(:primary_care_physician, code: "GP111111")
gp2 = create(:primary_care_physician, code: "GP222222")
csv_content = <<-CSV.strip_heredoc
"GP111111","PRAC_1","P","19740401","19910401","0"
"GP222222","PRAC_2","P","19940401","","0"
CSV
with_tmpfile(csv_content) do |tmpfile|
expect {
described_class.new(tmpfile).call
}
.to change { Patients::PracticeMembership.count }.by(2)
end
expect(gp1.reload.practice_memberships.first).to have_attributes(
joined_on: Date.parse("1974-04-01"),
left_on: Date.parse("1991-04-01"),
active: false
)
expect(gp2.reload.practice_memberships.first).to have_attributes(
joined_on: Date.parse("1994-04-01"),
left_on: nil,
active: true
)
end
end
context "when a gp is no longer in a practice" do
it "they are soft deleted" do
practice = create(:practice, code: "PRAC1")
gp1 = create(:primary_care_physician, code: "GP1")
gp2 = create(:primary_care_physician, code: "GP2")
membership1 = create(
:practice_membership,
practice: practice,
primary_care_physician: gp1
)
membership2 = create(
:practice_membership,
practice: practice,
primary_care_physician: gp2
)
# Because GP2 is omitted from the CSV they should be marked as deleted
csv_content = <<-CSV.strip_heredoc
"GP1","PRAC1","P","19740401","19910401","0"
CSV
with_tmpfile(csv_content) do |tmpfile|
expect {
described_class.new(tmpfile).call
}
.to change { Patients::PracticeMembership.count }.by(-1)
.and change { Patients::PracticeMembership.deleted.count }.by(1)
end
expect(membership1.reload).not_to be_deleted
expect(membership2.reload).to be_deleted
end
end
end
end
end
end
end
| 32.65625 | 84 | 0.519936 |
f7a6943d0f2bc01cf2f6a7aa37fabcc7f7007e8c | 1,823 | require "spec_helper"
RSpec.describe "Person" do
describe %q(
Object-Oriented Programming
===========================
Object-Oriented Programming, or OOP for short, allows us
to model the world around us in terms of objects.
Everything is an object. Pizza, statue, cup, window,
person, dog, cat, final exam, etc; these are all objects.
Objects have state. A slice of pizza that came straight
out of the oven is hot. One that has been sitting on the
table for a few hours is most definitely cold. A cup can
be full, or empty. An exam has a due date and a grade.
Think of object state as the adjectives that describe the
object.
Objects have behaviors. A dog can bark, run, eat, and
sleep. A person can do these things to, but instead of
barking, they would probably speak. You can open a
window. You can complete an exam. Think of object
behavior as the verbs which that object can do.
We model our world using objects by considering the
**states** we want to store on our objects, and the
**behaviors** we want to define for our objects.
In the following exercises, we will explore the programming
paradigm that is OOP.
First, we start with **Classes**
Ruby Classes
============
Think of a class as the "schematics" for building
an object. In this case, we are defining the set of
instructions which will create a new "Person".
Calling `Person.new` will construct a new and unique
instance of that class.
Instructions
------------
Define the Person class in `lib/person.rb`.
) do
describe "Person.new" do
it "should create a new Person object" do
jean_luc_picard = Person.new
expect(jean_luc_picard).to be_a(Person)
end
end
end
end
| 28.936508 | 63 | 0.671421 |
bb6b9a013b1421740ea62d9543c352e7016931f2 | 849 | require 'test_helper'
class MicropostsControllerTest < ActionDispatch::IntegrationTest
# test "the truth" do
# assert true
# end
def setup
@micropost = microposts(:orange)
end
test "should redirect create when not logged in" do
assert_no_difference 'Micropost.count' do
post microposts_path, params:{ micropost: {content: " Lorem ipsum"}}
end
assert_redirected_to login_url
end
test "should redirect destroy when not logged in" do
assert_no_difference 'Micropost.count' do
delete micropost_path(@micropost)
end
assert_redirected_to login_url
end
test "should redirect destroy for wrong micropost" do
log_in_as(users(:michael))
micropost = microposts(:ants)
assert_no_difference 'Micropost.count' do
delete micropost_path(micropost)
end
assert_redirected_to root_url
end
end | 25.727273 | 72 | 0.746761 |
f8dc5775463c320b12c23d13c70d5a5b8eb81bd6 | 1,941 | module LolSoap
# Represents a HTTP request containing a SOAP Envelope
class Request
attr_reader :envelope
attr_accessor :xml_options
def initialize(envelope)
@envelope = envelope
@xml_options = default_xml_options
end
# @see Envelope#body
def body(&block)
envelope.body(&block)
end
# @see Envelope#header
def header(&block)
envelope.header(&block)
end
# Namespace used for SOAP envelope tags
def soap_namespace
envelope.soap_namespace
end
# The SOAP version in use
def soap_version
envelope.soap_version
end
# URL to be POSTed to
def url
envelope.endpoint
end
# The type of the element sent in the request body
def input_type
envelope.input_body_content_type
end
# The type of the element that will be received in the response body
def output_type
envelope.output_body_content_type
end
# The MIME type of the request. This is always application/soap+xml,
# but it could be overridden in a subclass.
def mime
if soap_version == '1.1'
'text/xml'
else
'application/soap+xml'
end
end
# The charset of the request. This is always UTF-8, but it could be
# overridden in a subclass.
def charset
'UTF-8'
end
# The full content type of the request, assembled from the #mime and
# #charset.
def content_type
"#{mime};charset=#{charset}"
end
# Headers that must be set when making the request
def headers
{
'Content-Type' => content_type,
'Content-Length' => content.bytesize.to_s,
'SOAPAction' => envelope.action
}
end
# The content to be sent in the HTTP request
def content
@content ||= envelope.to_xml(xml_options)
end
private
def default_xml_options
{ encoding: charset }
end
end
end
| 21.566667 | 72 | 0.63627 |
0123a754f0f039e8a56e0ea4e3bea63c0926b3df | 679 | module PostSetPresenters
class PoolGallery < Base
attr_accessor :post_set
delegate :pools, :to => :post_set
def initialize(post_set)
@post_set = post_set
end
def post_previews_html(template, options = {})
html = ""
if pools.empty?
return template.render("post_sets/blank")
end
pools.each do |pool|
if pool.cover_post_id
post = ::Post.find(pool.cover_post_id)
html << PostPresenter.preview(post, options.merge(:tags => @post_set.tag_string, :raw => @post_set.raw, :pool => pool, :show_deleted => true))
html << "\n"
end
end
html.html_safe
end
end
end
| 23.413793 | 152 | 0.606775 |
ac678541eb10ef422565a87a1c6616bbc74a13a0 | 1,671 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v7/errors/operation_access_denied_error.proto
require 'google/protobuf'
require 'google/api/annotations_pb'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/ads/googleads/v7/errors/operation_access_denied_error.proto", :syntax => :proto3) do
add_message "google.ads.googleads.v7.errors.OperationAccessDeniedErrorEnum" do
end
add_enum "google.ads.googleads.v7.errors.OperationAccessDeniedErrorEnum.OperationAccessDeniedError" do
value :UNSPECIFIED, 0
value :UNKNOWN, 1
value :ACTION_NOT_PERMITTED, 2
value :CREATE_OPERATION_NOT_PERMITTED, 3
value :REMOVE_OPERATION_NOT_PERMITTED, 4
value :UPDATE_OPERATION_NOT_PERMITTED, 5
value :MUTATE_ACTION_NOT_PERMITTED_FOR_CLIENT, 6
value :OPERATION_NOT_PERMITTED_FOR_CAMPAIGN_TYPE, 7
value :CREATE_AS_REMOVED_NOT_PERMITTED, 8
value :OPERATION_NOT_PERMITTED_FOR_REMOVED_RESOURCE, 9
value :OPERATION_NOT_PERMITTED_FOR_AD_GROUP_TYPE, 10
value :MUTATE_NOT_PERMITTED_FOR_CUSTOMER, 11
end
end
end
module Google
module Ads
module GoogleAds
module V7
module Errors
OperationAccessDeniedErrorEnum = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v7.errors.OperationAccessDeniedErrorEnum").msgclass
OperationAccessDeniedErrorEnum::OperationAccessDeniedError = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v7.errors.OperationAccessDeniedErrorEnum.OperationAccessDeniedError").enummodule
end
end
end
end
end
| 41.775 | 230 | 0.780969 |
acb199214b0ae86defafdf61850471919a95f107 | 5,148 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::ServiceFabric::V6_2_0_9
module Models
#
# Describes an update for a stateless service.
#
class StatelessServiceUpdateDescription < ServiceUpdateDescription
include MsRestAzure
def initialize
@ServiceKind = "Stateless"
end
attr_accessor :ServiceKind
# @return [Integer] The instance count.
attr_accessor :instance_count
#
# Mapper for StatelessServiceUpdateDescription class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'Stateless',
type: {
name: 'Composite',
class_name: 'StatelessServiceUpdateDescription',
model_properties: {
flags: {
client_side_validation: true,
required: false,
serialized_name: 'Flags',
type: {
name: 'String'
}
},
placement_constraints: {
client_side_validation: true,
required: false,
serialized_name: 'PlacementConstraints',
type: {
name: 'String'
}
},
correlation_scheme: {
client_side_validation: true,
required: false,
serialized_name: 'CorrelationScheme',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ServiceCorrelationDescriptionElementType',
type: {
name: 'Composite',
class_name: 'ServiceCorrelationDescription'
}
}
}
},
load_metrics: {
client_side_validation: true,
required: false,
serialized_name: 'LoadMetrics',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ServiceLoadMetricDescriptionElementType',
type: {
name: 'Composite',
class_name: 'ServiceLoadMetricDescription'
}
}
}
},
service_placement_policies: {
client_side_validation: true,
required: false,
serialized_name: 'ServicePlacementPolicies',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ServicePlacementPolicyDescriptionElementType',
type: {
name: 'Composite',
polymorphic_discriminator: 'Type',
uber_parent: 'ServicePlacementPolicyDescription',
class_name: 'ServicePlacementPolicyDescription'
}
}
}
},
default_move_cost: {
client_side_validation: true,
required: false,
serialized_name: 'DefaultMoveCost',
type: {
name: 'String'
}
},
scaling_policies: {
client_side_validation: true,
required: false,
serialized_name: 'ScalingPolicies',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ScalingPolicyDescriptionElementType',
type: {
name: 'Composite',
class_name: 'ScalingPolicyDescription'
}
}
}
},
ServiceKind: {
client_side_validation: true,
required: true,
serialized_name: 'ServiceKind',
type: {
name: 'String'
}
},
instance_count: {
client_side_validation: true,
required: false,
serialized_name: 'InstanceCount',
constraints: {
InclusiveMinimum: -1
},
type: {
name: 'Number'
}
}
}
}
}
end
end
end
end
| 32.377358 | 86 | 0.443473 |
ab34124db61178df75af904ea9afc3e524980493 | 1,786 | require_relative '../fixtures/user_provisioning_fixtures'
require_relative 'support/user_provisioning_helper'
require_relative '../integration/support/configuration_helper'
require_relative '../integration/support/s3_helper'
require_relative '../../../lib/gooddata/models/user_filters/user_filter_builder'
require_relative '../../../lib/gooddata/lcm/lcm2'
describe 'the extended user provisioning functionality' do
before(:all) do
@fixtures = Fixtures::UserProvisioningFixtures.new projects_amount: 2,
user_amount: 2
end
after(:all) do
@fixtures.teardown
end
describe 'when provisioning in the declarative mode' do
it 'removes MUFs from projects not mentioned in the input' do
Support::UserProvisioningHelper.test_users_brick(projects: @fixtures[:projects],
test_context: @fixtures[:brick_params],
user_data: @fixtures[:user_data])
Support::UserProvisioningHelper.test_user_filters_brick(projects: @fixtures[:projects],
test_context: @fixtures[:brick_params],
mufs: @fixtures[:mufs])
extra_project = @fixtures[:projects].first
mufs = @fixtures[:mufs].reject { |m| m[:project_id] == extra_project.pid }
Support::UserProvisioningHelper.upload_mufs(mufs)
Support::UserProvisioningHelper.test_user_filters_brick(projects: @fixtures[:projects],
test_context: @fixtures[:brick_params],
mufs: mufs)
end
end
end
| 48.27027 | 101 | 0.590705 |
181a3a00b358ab8153a02cc4822022a79a0266c0 | 3,351 | # -*- encoding: utf-8 -*-
# stub: jekyll-algolia 1.7.0 ruby lib
Gem::Specification.new do |s|
s.name = "jekyll-algolia".freeze
s.version = "1.7.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["Tim Carry".freeze, "Sylvain Utard".freeze]
s.date = "2021-05-06"
s.description = "Index all your content into Algolia by running `jekyll algolia`".freeze
s.email = "[email protected]".freeze
s.homepage = "https://github.com/algolia/jekyll-algolia".freeze
s.licenses = ["MIT".freeze]
s.required_ruby_version = Gem::Requirement.new(">= 2.3.0".freeze)
s.rubygems_version = "3.1.6".freeze
s.summary = "Index your Jekyll content into Algolia".freeze
s.installed_by_version = "3.1.6" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
end
if s.respond_to? :add_runtime_dependency then
s.add_runtime_dependency(%q<algolia_html_extractor>.freeze, ["~> 2.6"])
s.add_runtime_dependency(%q<algoliasearch>.freeze, ["~> 1.26"])
s.add_runtime_dependency(%q<filesize>.freeze, ["~> 0.1"])
s.add_runtime_dependency(%q<jekyll>.freeze, [">= 3.6", "< 5.0"])
s.add_runtime_dependency(%q<json>.freeze, ["~> 2.0"])
s.add_runtime_dependency(%q<nokogiri>.freeze, ["~> 1.6"])
s.add_runtime_dependency(%q<progressbar>.freeze, ["~> 1.9"])
s.add_runtime_dependency(%q<verbal_expressions>.freeze, ["~> 0.1.5"])
s.add_development_dependency(%q<awesome_print>.freeze, ["~> 1.8"])
s.add_development_dependency(%q<coveralls>.freeze, ["~> 0.8"])
s.add_development_dependency(%q<flay>.freeze, ["~> 2.6"])
s.add_development_dependency(%q<flog>.freeze, ["~> 4.3"])
s.add_development_dependency(%q<guard>.freeze, ["~> 2.14"])
s.add_development_dependency(%q<guard-rspec>.freeze, ["~> 4.6"])
s.add_development_dependency(%q<rake>.freeze, ["~> 12.3"])
s.add_development_dependency(%q<rspec>.freeze, ["~> 3.0"])
s.add_development_dependency(%q<rubocop>.freeze, ["~> 0.51"])
s.add_development_dependency(%q<rubocop-rspec-focused>.freeze, ["~> 0.1.0"])
s.add_development_dependency(%q<simplecov>.freeze, ["~> 0.10"])
else
s.add_dependency(%q<algolia_html_extractor>.freeze, ["~> 2.6"])
s.add_dependency(%q<algoliasearch>.freeze, ["~> 1.26"])
s.add_dependency(%q<filesize>.freeze, ["~> 0.1"])
s.add_dependency(%q<jekyll>.freeze, [">= 3.6", "< 5.0"])
s.add_dependency(%q<json>.freeze, ["~> 2.0"])
s.add_dependency(%q<nokogiri>.freeze, ["~> 1.6"])
s.add_dependency(%q<progressbar>.freeze, ["~> 1.9"])
s.add_dependency(%q<verbal_expressions>.freeze, ["~> 0.1.5"])
s.add_dependency(%q<awesome_print>.freeze, ["~> 1.8"])
s.add_dependency(%q<coveralls>.freeze, ["~> 0.8"])
s.add_dependency(%q<flay>.freeze, ["~> 2.6"])
s.add_dependency(%q<flog>.freeze, ["~> 4.3"])
s.add_dependency(%q<guard>.freeze, ["~> 2.14"])
s.add_dependency(%q<guard-rspec>.freeze, ["~> 4.6"])
s.add_dependency(%q<rake>.freeze, ["~> 12.3"])
s.add_dependency(%q<rspec>.freeze, ["~> 3.0"])
s.add_dependency(%q<rubocop>.freeze, ["~> 0.51"])
s.add_dependency(%q<rubocop-rspec-focused>.freeze, ["~> 0.1.0"])
s.add_dependency(%q<simplecov>.freeze, ["~> 0.10"])
end
end
| 49.279412 | 112 | 0.656819 |
e27a301c4137abfedb8b93b0eefe885f538862ae | 1,316 | require_relative 'boot'
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "active_storage/engine"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_mailbox/engine"
require "action_text/engine"
require "action_view/railtie"
require "action_cable/engine"
# require "sprockets/railtie"
require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module JsProjectBackend
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
# Only loads a smaller set of middleware suitable for API only apps.
# Middleware like session, flash, cookies can be added back manually.
# Skip views, helpers and assets when generating a new resource.
config.api_only = true
end
end
| 34.631579 | 82 | 0.778875 |
1a6eaa51d63d7e629800bedd0a4388440b8350e0 | 1,274 | class Texinfo < Formula
desc "Official documentation format of the GNU project"
homepage "https://www.gnu.org/software/texinfo/"
url "http://ftpmirror.gnu.org/texinfo/texinfo-5.2.tar.gz"
mirror "https://ftp.gnu.org/gnu/texinfo/texinfo-5.2.tar.gz"
sha256 "6b8ca30e9b6f093b54fe04439e5545e564c63698a806a48065c0bba16994cf74"
bottle do
revision 1
sha256 "c32217fe9d506df49481730dd580a9207931a13c4e0ade3e9caaf83feeaeaba7" => :yosemite
sha256 "84d4e2ff689f10d2a68bdd42ccf0726306e74314378d2dd2c78e52fe58945dd3" => :mavericks
sha256 "73e86c31e3ae5a971e8bc4f5a5f2823a2f3858ee166f5cdd2cf11a4ac7036728" => :mountain_lion
end
keg_only :provided_by_osx, <<-EOS.undent
Software that uses TeX, such as lilypond and octave, require a newer version
of these files.
EOS
def install
system "./configure", "--disable-dependency-tracking",
"--disable-install-warnings",
"--prefix=#{prefix}"
system "make", "install"
end
test do
(testpath/"test.texinfo").write <<-EOS.undent
@ifnottex
@node Top
@top Hello World!
@end ifnottex
@bye
EOS
system "#{bin}/makeinfo", "test.texinfo"
assert_match /Hello World!/, File.read("test.info")
end
end
| 32.666667 | 95 | 0.697017 |
e8f1730b264f8ed843f65ee3759ffda3ef9019cd | 5,456 | #
# Cookbook Name:: apache2
# Recipe:: default
#
# Copyright 2008-2013, Opscode, 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.
#
package 'apache2' do
package_name node['apache']['package']
end
service 'apache2' do
service_name node['apache']['package']
case node['platform_family']
when 'rhel'
reload_command '/sbin/service httpd graceful'
when 'debian'
provider Chef::Provider::Service::Debian
when 'arch'
service_name 'httpd'
end
supports [:start, :restart, :reload, :status]
action [:enable, :start]
only_if "#{node['apache']['binary']} -t", :environment => { 'APACHE_LOG_DIR' => node['apache']['log_dir'] }, :timeout => 10
end
%w(sites-available sites-enabled mods-available mods-enabled conf-available conf-enabled).each do |dir|
directory "#{node['apache']['dir']}/#{dir}" do
mode '0755'
owner 'root'
group node['apache']['root_group']
end
end
%w(default 000-default).each do |site|
link "#{node['apache']['dir']}/sites-enabled/#{site}" do
action :delete
end
file "#{node['apache']['dir']}/sites-available/#{site}" do
action :delete
backup false
end
end
directory "#{node['apache']['dir']}/conf.d" do
action :delete
recursive true
end
directory node['apache']['log_dir'] do
mode '0755'
end
# perl is needed for the a2* scripts
package node['apache']['perl_pkg']
%w(a2ensite a2dissite a2enmod a2dismod a2enconf a2disconf).each do |modscript|
link "/usr/sbin/#{modscript}" do
action :delete
only_if { ::File.symlink?("/usr/sbin/#{modscript}") }
end
template "/usr/sbin/#{modscript}" do
source "#{modscript}.erb"
mode '0700'
owner 'root'
group node['apache']['root_group']
action :create
end
end
unless platform_family?('debian')
cookbook_file '/usr/local/bin/apache2_module_conf_generate.pl' do
source 'apache2_module_conf_generate.pl'
mode '0755'
owner 'root'
group node['apache']['root_group']
end
execute 'generate-module-list' do
command "/usr/local/bin/apache2_module_conf_generate.pl #{node['apache']['lib_dir']} #{node['apache']['dir']}/mods-available"
action :nothing
end
# enable mod_deflate for consistency across distributions
include_recipe 'apache2::mod_deflate'
end
if platform_family?('freebsd')
directory "#{node['apache']['dir']}/Includes" do
action :delete
recursive true
end
directory "#{node['apache']['dir']}/extra" do
action :delete
recursive true
end
end
if platform_family?('suse')
directory "#{node['apache']['dir']}/vhosts.d" do
action :delete
recursive true
end
%w(charset.conv default-vhost.conf default-server.conf default-vhost-ssl.conf errors.conf listen.conf mime.types mod_autoindex-defaults.conf mod_info.conf mod_log_config.conf mod_status.conf mod_userdir.conf mod_usertrack.conf uid.conf).each do |file|
file "#{node['apache']['dir']}/#{file}" do
action :delete
backup false
end
end
end
%W(
#{node['apache']['dir']}/ssl
#{node['apache']['cache_dir']}
).each do |path|
directory path do
mode '0755'
owner 'root'
group node['apache']['root_group']
end
end
# Set the preferred execution binary - prefork or worker
template "/etc/sysconfig/#{node['apache']['package']}" do
source 'etc-sysconfig-httpd.erb'
owner 'root'
group node['apache']['root_group']
mode '0644'
notifies :restart, 'service[apache2]', :delayed
only_if { platform_family?('rhel', 'fedora', 'suse') }
end
template "#{node['apache']['dir']}/envvars" do
source 'envvars.erb'
owner 'root'
group node['apache']['root_group']
mode '0644'
notifies :reload, 'service[apache2]', :delayed
only_if { platform_family?('debian') }
end
template 'apache2.conf' do
if platform_family?('rhel', 'fedora', 'arch', 'freebsd')
path "#{node['apache']['conf_dir']}/httpd.conf"
elsif platform_family?('debian')
path "#{node['apache']['conf_dir']}/apache2.conf"
elsif platform_family?('suse')
path "#{node['apache']['conf_dir']}/httpd.conf"
end
action :create
source 'apache2.conf.erb'
owner 'root'
group node['apache']['root_group']
mode '0644'
notifies :reload, 'service[apache2]', :delayed
end
%w(security charset).each do |conf|
apache_conf conf do
enable true
end
end
apache_conf 'ports' do
enable false
conf_path node['apache']['dir']
end
if node['apache']['version'] == '2.4' && !platform_family?('freebsd')
# on freebsd the prefork mpm is staticly compiled in
include_recipe "apache2::mpm_#{node['apache']['mpm']}"
end
node['apache']['default_modules'].each do |mod|
module_recipe_name = mod =~ /^mod_/ ? mod : "mod_#{mod}"
include_recipe "apache2::#{module_recipe_name}"
end
web_app 'default' do
template 'default-site.conf.erb'
path "#{node['apache']['dir']}/sites-available/default.conf"
enable node['apache']['default_site_enabled']
end
apache_site '000-default' do
enable node['apache']['default_site_enabled']
end
| 26.357488 | 253 | 0.686034 |
62b3e17029d6ee9fed337a50954fbc08cb7c7277 | 2,508 | require 'sexp_processor'
require 'i18nliner/errors'
require 'i18nliner/extractors/translate_call'
require 'i18nliner/extractors/sexp_helper'
module I18nliner
module Extractors
class RubyExtractor < ::SexpProcessor
include SexpHelper
TRANSLATE_CALLS = [:t, :translate]
attr_reader :current_line
def self.pattern
/(^|\W)(t|translate)(\W|$)/
end
def initialize(sexps, scope)
@sexps = sexps
@scope = scope
super()
end
def each_translation(&block)
@block = block
process(@sexps)
end
attr_reader :current_defn
def process_defn(exp)
exp.shift
@current_defn = exp.shift
process exp.shift until exp.empty?
@current_defn = nil
s()
end
def process_call(exp)
exp.shift
receiver_exp = exp.shift
receiver = nil
if receiver_exp
receiver = receiver_exp[0] == :const ? receiver_exp.last : UnsupportedExpression
process(receiver_exp)
end
method = exp.shift
if extractable_call?(receiver, method)
@current_line = exp.line
# convert s-exps into literals where possible
args = process_arguments(exp)
process_translate_call(receiver, method, args)
else
# even if this isn't a translate call, its arguments might contain
# one
process exp.shift until exp.empty?
end
s
end
protected
def extractable_call?(receiver, method)
TRANSLATE_CALLS.include?(method) && (receiver.nil? || receiver == :I18n)
end
def process_translate_call(receiver, method, args)
scope = receiver ? Scope.root : @scope
call = TranslateCall.new(scope, @current_line, method, args, :explicit_receiver => !receiver.nil?)
call.translations.each &@block
end
private
def process_arguments(args)
values = []
while arg = args.shift
values << evaluate_expression(arg)
end
values
end
def evaluate_expression(exp)
return raw(exp) if exp.sexp_type == :lit
return string_from(exp) if stringish?(exp)
return hash_from(exp) if exp.sexp_type == :hash
process(exp)
UnsupportedExpression
end
def hash_from(exp)
exp.shift
values = exp.map{ |e| evaluate_expression(e) }
Hash[*values]
end
end
end
end
| 24.588235 | 106 | 0.600877 |
f8dbe057cb784c9d4a4647c4b0602a7be9e1b9b6 | 4,815 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
$LOAD_PATH << File.join(__dir__, '../', 'app', 'lib') | 49.132653 | 92 | 0.741641 |
1a45d3e553e078ca48e306729c4dfb311a7edc30 | 1,974 | $:.unshift File.dirname(__FILE__)
require 'remote_ip_proxy_scrubber/version'
module RemoteIpProxyScrubber
# Add the following to config/application.rb or conifg/environments/*
#
# config.middleware.insert_before(Rails::Rack::Logger, RemoteIpProxyScrubber.filter_middleware, [
# "216.73.93.70/31", # www.google.com
# "216.73.93.72/31", # www.google.com
# "17.0.0.0/8", # Apple
# ])
def filter_middleware
require 'remote_ip_proxy_scrubber/filter_proxy_ips'
RemoteIpProxyScrubber::Rails4::FilterProxyIPs
end
module_function :filter_middleware
# Returns a Class to be used a rack middleware,
# replacing the existing `Rails::Rack::Logger`.
#
# config.middleware.insert_before(Rails::Rack::Logger, RemoteIpProxyScrubber.patched_logger)
# config.middleware.delete(Rails::Rack::Logger)
def patched_logger
require 'remote_ip_proxy_scrubber/remote_ip_logger'
rails_version = self.rails_version
if rails_version >= Gem::Version.new('4.0.0')
RemoteIpProxyScrubber::Rails4::RemoteIPLogger
elsif rails_version >= Gem::Version.new('3.2.9')
RemoteIpProxyScrubber::Rails3_2_9::RemoteIPLogger
elsif rails_version >= Gem::Version.new('3.2.0')
RemoteIpProxyScrubber::Rails3_2_0::RemoteIPLogger
elsif rails_version >= Gem::Version.new('3.0.6')
RemoteIpProxyScrubber::Rails3_1::RemoteIPLogger
elsif rails_version >= Gem::Version.new('3.0.0')
RemoteIpProxyScrubber::Rails3_0::RemoteIPLogger
else
fail "Sorry, this gem doesn't know how to monkey-patch the Rails logger for Rails #{rails_version} yet."
end
end
module_function :patched_logger
def rails_version
rails_version = Rails.version rescue nil
rails_version ||= RAILS_GEM_VERSION rescue nil
if rails_version.nil?
fail "Unable to determine the current version of Rails"
end
Gem::Version.new(rails_version)
end
module_function :rails_version
end | 35.890909 | 110 | 0.723404 |
b984251e73e8851e5fa6a9dd501085e767d82ca0 | 2,782 | # frozen_string_literal: true
require 'omniauth-oauth2'
module OmniAuth
module Strategies
class Oktaoauth < OmniAuth::Strategies::OAuth2
DEFAULT_SCOPE = %[openid profile email].freeze
option :name, 'oktaoauth'
option :skip_jwt, false
option :jwt_leeway, 60
option :client_options, {
site: "configure this part ins client options with devise",
authorize_url: "configure this part in client options with devise",
token_url: "configure this part in client options with devise",
response_type: 'id_token'
}
option :scope, DEFAULT_SCOPE
uid { raw_info['sub'] }
info do
{
name: raw_info['name'],
email: raw_info['email'],
first_name: raw_info['given_name'],
last_name: raw_info['family_name'],
image: raw_info['picture']
}
end
extra do
hash = {}
hash[:raw_info] = raw_info unless skip_info?
hash[:id_token] = access_token.token
if !options[:skip_jwt] && !access_token.token.nil?
hash[:id_info] = validated_token(access_token.token)
end
hash
end
alias :oauth2_access_token :access_token
def access_token
::OAuth2::AccessToken.new(client, oauth2_access_token.token, {
:expires_in => oauth2_access_token.expires_in,
:expires_at => oauth2_access_token.expires_at,
:refresh_token => oauth2_access_token.refresh_token
})
end
def raw_info
if options[:auth_server_id]
options[:auth_server_id] = options[:auth_server_id] + "/"
else
options[:auth_server_id] = ""
end
@_raw_info ||= access_token.get('/oauth2/' + options[:auth_server_id] + 'v1/userinfo').parsed || {}
rescue ::Errno::ETIMEDOUT
raise ::Timeout::Error
end
def request_phase
super
end
def callback_phase
super
end
def callback_url
options[:redirect_uri] || (full_host + script_name + callback_path)
end
def validated_token(token)
JWT.decode(token,
nil,
false,
verify_iss: true,
iss: options[:issuer],
verify_aud: true,
aud: options[:audience],
verify_sub: true,
verify_expiration: true,
verify_not_before: true,
verify_iat: true,
verify_jti: false,
leeway: options[:jwt_leeway]
).first
end
end
end
end
| 27.27451 | 107 | 0.543494 |
03c1a7a6c5c5cc57fb5229552f4f471a881404e8 | 161 | # Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
ExperimentTracker::Application.initialize!
| 26.833333 | 52 | 0.813665 |
e870a8c7b8f4e115b7867e4f6ee58794d7957019 | 447 | require 'rails_helper'
RSpec.describe RevokeServiceProviderConsent do
let(:now) { Time.zone.now }
subject(:service) { RevokeServiceProviderConsent.new(identity, now: now) }
describe '#call' do
let!(:identity) { create(:service_provider_identity, deleted_at: nil) }
it 'sets the deleted_at' do
expect { service.call }.
to change { identity.reload.deleted_at&.to_i }.
from(nil).to(now.to_i)
end
end
end
| 24.833333 | 76 | 0.684564 |
3907544afa4012ca551a5d664baca95475376e06 | 421 | require 'puppetlabs_spec_helper/module_spec_helper'
require 'rspec-puppet-facts'
include RspecPuppetFacts
def fixture_path
File.expand_path(File.join(__FILE__, '..', 'fixtures'))
end
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + '/../'))
RSpec.configure do |c|
c.add_setting :fixture_path, :default => fixture_path
c.mock_with(:rspec)
Puppet[:config] = File.join(fixture_path,'puppet.conf')
end
| 26.3125 | 69 | 0.760095 |
3981d55a5f2fd05b3966fe8040a4ee50f4b54352 | 1,148 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'resque-serial-queues/version'
Gem::Specification.new do |spec|
spec.name = "resque-serial-queues"
spec.version = Resque::Plugins::SerialQueues::VERSION
spec.authors = ["Cristian Bica"]
spec.email = ["[email protected]"]
spec.summary = %q{Declare resque queues serial}
spec.description = %q{Declare resque queues serial and jobs in that queue will be run in serial mode}
spec.homepage = "http://github.com/cristianbica/resque-serial-queues"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency 'resque', '~>1.0'
spec.add_dependency 'redis-namespace'
spec.add_dependency 'activesupport'
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake"
spec.add_development_dependency "minitest"
end
| 39.586207 | 105 | 0.68554 |
6a79598578e0c191bc166a3748eb28b37c69fa6b | 6,605 | class StudySubjectsController < ApplicationController
before_filter :may_create_study_subjects_required,
:only => [:new,:create]
before_filter :may_read_study_subjects_required,
:only => [:show,:index,:dashboard,:followup,:reports,:by]
before_filter :may_update_study_subjects_required,
:only => [:edit,:update]
before_filter :may_destroy_study_subjects_required,
:only => :destroy
before_filter :valid_id_required,
:only => [:show,:edit,:update,:destroy,:next,:prev] #,:first,:last]
def index
record_or_recall_sort_order
conditions = [[],{}]
# Table names are not necessary if field is unambiguous.
%w( subjectid childid patid hospital_no icf_master_id first_name ).each do |attr|
if params[attr] and !params[attr].blank?
conditions[0] << "( #{attr} LIKE :#{attr} )"
conditions[1][attr.to_sym] = "%#{params[attr]}%"
end
end
validate_valid_date_range_for(:dob,conditions)
if params[:last_name] and !params[:last_name].blank?
conditions[0] << "( last_name LIKE :last_name OR maiden_name LIKE :last_name )"
conditions[1][:last_name] = "%#{params[:last_name]}%"
end
if params[:registrar_no].present?
conditions[0] << "( do_not_use_state_id_no LIKE :registrar_no OR do_not_use_state_registrar_no LIKE :registrar_no OR do_not_use_local_registrar_no LIKE :registrar_no )"
conditions[1][:registrar_no] = "%#{params[:registrar_no]}%"
end
if params[:subject_type].present?
conditions[0] << "( subject_type = :subject_type )"
conditions[1][:subject_type] = params[:subject_type]
end
if params[:phase].present?
conditions[0] << "( phase = :phase )"
conditions[1][:phase] = params[:phase].to_i
end
# LEFT JOIN because not all subjects will have a patient.
# otherwise, we'd effectively only search cases
@study_subjects = StudySubject.order(search_order)
.left_join_patient
.where(conditions[0].join(valid_find_operator), conditions[1])
.paginate(
:per_page => params[:per_page]||25,
:page => valid_find_page
)
#
# As it is possible to set a page and then add a filter,
# one could have samples but be on to high of a page to see them.
# length would return 0, but count is the total database count
#
if @study_subjects.length == 0 and @study_subjects.count > 0
flash[:warn] = "Page number was too high, so set to highest valid page number."
# Doesn't change the url string, but does work.
params[:page] = @study_subjects.total_pages
# It seems excessive to redirect and do it all again.
# Nevertheless ...
# redirect_to study_subjects_path(params)
# rails 4.2.0 is deprecating string keys
redirect_to study_subjects_path(params.symbolize_keys)
end
end
def edit
end
def show
end
def update
@study_subject.update_attributes!(study_subject_params)
flash[:notice] = 'Success!'
redirect_to study_subject_path(@study_subject)
rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid
flash.now[:error] = "There was a problem updating the study_subject"
render :action => "edit"
end
#
# The following actions are all "redirectors"
#
def by
if params[:by_id].present? && (
StudySubject.with_icf_master_id(params[:by_id]).exists? ||
StudySubject.with_subjectid(params[:by_id]).exists? )
# StudySubject.where( :icf_master_id => params[:by_id]).exists? ||
# StudySubject.where( :subjectid => params[:by_id]).exists? )
study_subject = StudySubject.with_icf_master_id(params[:by_id]).first ||
StudySubject.with_subjectid(params[:by_id]).first
redirect_to url_for_subject(study_subject)
else
flash[:warn] = "Valid icf_master_id or subjectid required."
redirect_to_referrer_or_default( root_path )
end
end
def first
first_study_subject = StudySubject.order('id asc').limit(1).first
redirect_to url_for_subject(first_study_subject)
end
def next
next_study_subject = StudySubject
.where(StudySubject.arel_table[:id].gt(@study_subject.id))
.order('id asc').limit(1).first
if next_study_subject.nil?
flash[:warn] = "Rolled over"
next_study_subject = StudySubject.order('id asc').first
end
redirect_to url_for_subject(next_study_subject)
end
#
# For some reason, redirect_to study_subject_path(nil)
# actually redirects to the current study_subject#show
# which is nice, but I don't understand why.
#
# This hain't true no mo.
#
def prev
prev_study_subject = StudySubject
.where(StudySubject.arel_table[:id].lt(@study_subject.id))
.order('id desc').limit(1).first
if prev_study_subject.nil?
flash[:warn] = "Rolled over"
prev_study_subject = StudySubject.order('id desc').first
end
redirect_to url_for_subject(prev_study_subject)
end
def last
last_study_subject = StudySubject.order('id desc').limit(1).first
redirect_to url_for_subject(last_study_subject)
end
protected
def url_for_subject(subject)
referrer_params = Odms::Application.routes.recognize_path(request.referrer||'') || {}
#referrer_params returns symbolized keys
case
when referrer_params.keys.include?(:study_subject_id)
if referrer_params.delete(:id)
referrer_params[:action] = 'index'
end
referrer_params[:study_subject_id] = subject.id
url_for(referrer_params)
else study_subject_path(subject)
end
end
def valid_id_required
if !params[:id].blank? and StudySubject.exists?(params[:id])
@study_subject = StudySubject.find(params[:id])
else
access_denied("Valid study_subject id required!", study_subjects_path)
end
end
def search_order
if params[:order] and
# %w( phase icf_master_id studyid last_name reference_date ).include?(params[:order].downcase)
# 20150211 - icf_master_id replaced by subjectid
# 20150211 - why was phase here?
%w( subjectid studyid last_name reference_date ).include?(params[:order].downcase)
order_string = params[:order]
dir = case params[:dir].try(:downcase)
when 'desc' then 'desc'
else 'asc'
end
[order_string,dir].join(' ')
else
nil
end
end
def study_subject_params
params.require(:study_subject).permit( :do_not_contact ,
:first_name, :middle_name, :last_name, :dob, :sex,
:do_not_use_state_registrar_no, :do_not_use_local_registrar_no, :reference_date, :vital_status,
:mother_first_name, :mother_middle_name, :mother_last_name, :mother_maiden_name,
:father_first_name, :father_middle_name, :father_last_name,
:guardian_first_name, :guardian_middle_name, :guardian_last_name,
:guardian_relationship, :other_guardian_relationship,
{ subject_races_attributes:
[:id, :_destroy, :race_code, :other_race, :mixed_race] }
)
end
end
| 33.358586 | 171 | 0.734746 |
28f2315370963d6bff1a92afd696e9e2f34e727e | 601 | require 'spec_helper'
describe 'taxons', type: :feature, caching: true do
let!(:taxonomy) { create(:taxonomy) }
let!(:taxon) { create(:taxon, taxonomy: taxonomy) }
before do
# warm up the cache
visit spree.root_path
assert_written_to_cache("views/en/spree/taxonomies/#{taxonomy.id}")
clear_cache_events
end
it 'busts the cache when max_level_in_taxons_menu conf changes' do
Spree::Config[:max_level_in_taxons_menu] = 5
visit spree.root_path
assert_written_to_cache("views/en/spree/taxonomies/#{taxonomy.id}")
expect(cache_writes.count).to eq(1)
end
end
| 27.318182 | 71 | 0.720466 |
088a4b29620d344f1e2b23bb850d54e37b72dfc3 | 233 | class CreateGroupsUsers < ActiveRecord::Migration[5.2]
def change
create_table :groups_users do |t|
t.integer :group_id, null: false
t.integer :user_id, null: false
t.timestamps null: false
end
end
end
| 21.181818 | 54 | 0.682403 |
1d973eeb1cb4f2584936433ec029ddb1adbbf470 | 798 | class PersonSerializer < ActiveModel::Serializer
attributes :id, :lock_version,
:name, :name_sort_by, :name_sort_by_confirmed,
:pseudonym, :pseudonym_sort_by, :pseudonym_sort_by_confirmed,
:published_name, :published_name_sort_by,
:job_title, :organization,
:pronouns, :year_of_birth, :gender, :ethnicity,
:opted_in, :comments,
:can_share, :can_photo, :can_record,
:invite_status, :acceptance_status,
:registered, :registration_type, :registration_number
has_one :bio
has_many :person_roles, serializer: PersonRoleSerializer
has_many :email_addresses, serializer: EmailAddressSerializer
# tag_list
attribute :tags do
object.base_tags.collect(&:name)
end
end
| 33.25 | 74 | 0.676692 |
acf47caad691c510c45f8f3d304950066bc523a1 | 3,179 | # square
#
# This file was automatically generated by APIMATIC v2.0
# ( https://apimatic.io ).
module Square
# All configuration including auth info and base URI for the API access
# are configured in this class.
class Configuration
# The attribute readers for properties.
attr_reader :http_client
attr_reader :timeout
attr_reader :max_retries
attr_reader :retry_interval
attr_reader :backoff_factor
attr_reader :environment
attr_reader :access_token
def additional_headers
@additional_headers.clone
end
class << self
attr_reader :environments
end
def initialize(timeout: 60, max_retries: 0, retry_interval: 1,
backoff_factor: 1, environment: 'production',
access_token: 'TODO: Replace', additional_headers: {})
# The value to use for connection timeout
@timeout = timeout
# The number of times to retry an endpoint call if it fails
@max_retries = max_retries
# Pause in seconds between retries
@retry_interval = retry_interval
# The amount to multiply each successive retry's interval amount
# by in order to provide backoff
@backoff_factor = backoff_factor
# Current API environment
@environment = environment
# OAuth 2.0 Access Token
@access_token = access_token
# Additional headers to add to each API request
@additional_headers = additional_headers.clone
# The Http Client to use for making requests.
@http_client = create_http_client
end
def clone_with(timeout: nil, max_retries: nil, retry_interval: nil,
backoff_factor: nil, environment: nil, access_token: nil,
additional_headers: nil)
timeout ||= self.timeout
max_retries ||= self.max_retries
retry_interval ||= self.retry_interval
backoff_factor ||= self.backoff_factor
environment ||= self.environment
access_token ||= self.access_token
additional_headers ||= self.additional_headers
Configuration.new(timeout: timeout, max_retries: max_retries,
retry_interval: retry_interval,
backoff_factor: backoff_factor,
environment: environment, access_token: access_token,
additional_headers: additional_headers)
end
def create_http_client
FaradayClient.new(timeout: timeout, max_retries: max_retries,
retry_interval: retry_interval,
backoff_factor: backoff_factor)
end
# All the environments the SDK can run in.
@environments = {
'production' => {
'default' => 'https://connect.squareup.com'
},
'sandbox' => {
'default' => 'https://connect.squareupsandbox.com'
}
}
# Generates the appropriate base URI for the environment and the server.
# @param [Configuration::Server] The server enum for which the base URI is
# required.
# @return [String] The base URI.
def get_base_uri(server = 'default')
self.class.environments[environment][server].clone
end
end
end
| 32.111111 | 78 | 0.656181 |
7933686f8b06a6bc8d3208209cd2d6395a4d428c | 70 | require 'backports/tools'
Backports.alias_method Proc, :yield, :call
| 17.5 | 42 | 0.785714 |
aca081c3768a857384b1f24587827924e5ebc275 | 1,029 | class Users::OmniauthCallbacksController < DeviseTokenAuth::OmniauthCallbacksController
before_filter :set_user_session
after_filter :handle_user_sessions
def handle_user_sessions
# puts "Session After: #{session[:previously_not_logged_in]} , #{session.id}"
# User just signed in
if session[:previously_not_logged_in] && user_signed_in?
# Assume previous session belongs to user
TranscriptEdit.updateUserSessions(session.id, current_user.id)
# Check if user is an admin
project = Project.getActive
admin_emails = project[:data]["adminEmails"]
if admin_emails.include?(current_user.email) && (!current_user.user_role || current_user.user_role.name != "admin")
current_user.setRole("admin")
end
end
end
def set_user_session
# puts "Session Before: #{session[:previously_not_logged_in]} , #{session.id}"
session[:previously_not_logged_in] = false
unless user_signed_in?
session[:previously_not_logged_in] = true
end
end
end
| 30.264706 | 121 | 0.724976 |
62b55a50fbceac27f63e482a4dc29ebac986745d | 238 | module Ckeditor
module Rails
class Railtie < ::Rails::Railtie
initializer 'ckeditor.assets.precompile', group: :all do |app|
app.config.assets.precompile += Ckeditor::Rails::Asset.new.files
end
end
end
end
| 23.8 | 72 | 0.672269 |
ed245539f1bf55839933464c289ce07f803d8200 | 2,744 | # frozen_string_literal: true
# Handles HTTP interaction that allows management of bulk jobs for an APO
class BulkJobsController < ApplicationController
include Blacklight::Searchable
# Generates the index page for a given DRUID's past bulk metadata upload jobs.
def index
params[:apo_id] = 'druid:' + params[:apo_id] unless params[:apo_id].include? 'druid'
@cocina = Dor::Services::Client.object(params[:apo_id]).find
authorize! :view_metadata, @cocina
@document = find(params[:apo_id])
@bulk_jobs = load_bulk_jobs(params[:apo_id])
end
# GET /apos/:apo_id/bulk_jobs/:time/log(.:format)
def show
@user_log = UserLog.new(params[:apo_id], params[:time])
respond_to do |format|
format.html do
# Generate both the actual log messages that go in the HTML and the CSV, since both need to be ready when the table is displayed to the user
@user_log.create_csv_log
end
format.csv do
if File.exist?(@user_log.csv_file)
send_file(@user_log.csv_file, type: 'text/csv')
else
render :nothing, status: :not_found
# Display error message and log the error
end
end
format.xml do
if File.exist?(@user_log.desc_metadata_xml_file)
send_file(@user_log.desc_metadata_xml_file, type: 'application/xml')
else
render :nothing, status: :not_found
# Display error message and log the error
end
end
end
end
def status_help; end
# DELETE /apos/:apo_id/bulk_jobs
def destroy
@apo = params[:apo_id]
directory_to_delete = File.join(Settings.bulk_metadata.directory, params[:dir])
FileUtils.remove_dir(directory_to_delete, true)
redirect_to apo_bulk_jobs_path(@apo), notice: "Bulk job for APO (#{@apo}) deleted."
end
def self.local_prefixes
super + ['catalog']
end
private
def find(id)
search_service.fetch(id).last
end
# Given a DRUID, loads any metadata bulk upload information associated with that DRUID into a hash.
def load_bulk_jobs(druid)
directory_list = []
bulk_info = []
bulk_load_dir = File.join(Settings.bulk_metadata.directory, druid)
# The metadata bulk upload processing stores its logs and other information in a very simple directory structure
directory_list = Dir.glob("#{bulk_load_dir}/*") if File.directory?(bulk_load_dir)
directory_list.each do |directory|
time = directory.sub("#{bulk_load_dir}/", '')
log = UserLog.new(druid, time)
bulk_info.push(log.bulk_job_metadata)
end
# Sort by start time (newest first)
sorted_info = bulk_info.sort_by { |b| b['argo.bulk_metadata.bulk_log_job_start'].to_s }
sorted_info.reverse!
end
end
| 32.282353 | 148 | 0.688047 |
ac17467d82af77fca1d858b99239f6c6c22235cc | 1,024 | class Codespell < Formula
include Language::Python::Virtualenv
desc "Fix common misspellings in source code and text files"
homepage "https://github.com/codespell-project/codespell"
url "https://files.pythonhosted.org/packages/7e/37/b15b4133e90bbef5acecfd2f3f3871c1352ee281c042fd64a22a72735fb8/codespell-1.17.1.tar.gz"
sha256 "25a2ecd86b9cdc111dc40a30d0ed28c578e13a0ce158d1c383f9d47811bfcd23"
bottle do
cellar :any_skip_relocation
sha256 "fb3fb87c3d707656b5c796fd40a13b6e7d0170f5cc4db6361751074b1f089bcf" => :catalina
sha256 "f44c96916092e661dfa53499d3570b98bba5fbcf964751f55c775e0aee68b37c" => :mojave
sha256 "752254907866753d1941f39193d67cb2fbaa54f294d6d0f4a1f11cd8a8247aae" => :high_sierra
sha256 "457962ac99c5f486ca4df20fe840035d2205d396cb8aa8c71dc0f0724eb6f4d8" => :x86_64_linux
end
depends_on "[email protected]"
def install
virtualenv_install_with_resources
end
test do
assert_equal "1: teh\n\tteh ==> the\n", shell_output("echo teh | #{bin}/codespell -", 1)
end
end
| 37.925926 | 138 | 0.802734 |
bb851cf2218c9635d1c3ced8abef9de812af8c1c | 118 | def stub_auth
stub_request(:get, 'http://oauth.ccci.us/users/' + user.access_token)
.to_return(status: 200)
end
| 23.6 | 71 | 0.711864 |
91f6d5f70a7eeed0d43fe72d09db520bdb635161 | 347 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'main/home.html.erb', type: :view do
# NEEDS TO BE REFACTORED
# it 'renders correctly' do
# user = FactoryBot.create(:user)
# allow(view).to receive(:user_signed_in?).and_return(user)
# render
# expect(rendered).to match('Herzlich willkommen')
# end
end
| 23.133333 | 63 | 0.697406 |
1c522af18e954add78c0a55d844f500305871640 | 561 | require 'rails_helper'
RSpec.describe Content, type: :model do
let(:page) { FactoryGirl.create(:page) }
before { @content = Content.new(kind: "h1", value: "Test header", page_id: page.id) }
subject { @content }
it { should respond_to(:kind) }
it { should respond_to(:value) }
it { should respond_to(:page_id) }
it { should respond_to(:page) }
it { should be_valid }
it { should belong_to(:page) }
its(:page) { should eq page }
describe "without kind" do
before { @content.kind = "" }
it { should_not be_valid }
end
end
| 20.035714 | 87 | 0.643494 |
62f2aa2ece459b6e9eef85f1b6fa5d827fb1187d | 1,584 | module HealthSeven::V2_3_1
class Obx < ::HealthSeven::Segment
# Set ID - OBX
attribute :set_id_obx, Si, position: "OBX.1"
# Value Type
attribute :value_type, Id, position: "OBX.2", require: true
# Observation Identifier
attribute :observation_identifier, Ce, position: "OBX.3", require: true
# Observation Sub-ID
attribute :observation_sub_id, St, position: "OBX.4", require: true
# Observation Value
attribute :observation_values, Array[Varies], position: "OBX.5", multiple: true
# Units
attribute :units, Ce, position: "OBX.6"
# References Range
attribute :references_range, St, position: "OBX.7"
# Abnormal Flags
attribute :abnormal_flags, Array[Id], position: "OBX.8", multiple: true
# Probability
attribute :probabilities, Array[Nm], position: "OBX.9", multiple: true
# Nature of Abnormal Test
attribute :nature_of_abnormal_test, Id, position: "OBX.10"
# Observation Result Status
attribute :observation_result_status, Id, position: "OBX.11", require: true
# Date Last Obs Normal Values
attribute :date_last_obs_normal_values, Ts, position: "OBX.12"
# User Defined Access Checks
attribute :user_defined_access_checks, St, position: "OBX.13"
# Date/Time of the Observation
attribute :date_time_of_the_observation, Ts, position: "OBX.14"
# Producer's ID
attribute :producer_s_id, Ce, position: "OBX.15"
# Responsible Observer
attribute :responsible_observers, Array[Xcn], position: "OBX.16", multiple: true
# Observation Method
attribute :observation_methods, Array[Ce], position: "OBX.17", multiple: true
end
end | 41.684211 | 82 | 0.738636 |
ed47072f6b422df2045e403041efeed8649134c3 | 2,469 | # Encoding: UTF-8
{fileTypes: [],
foldingStartMarker:
/(?<_1><(?i:(?<_2>head|table|tr|div|style|script|ul|ol|form|dl))\b.*?>|\{\{?(?<_3>if|foreach|capture|literal|foreach|php|section|strip)|\{\s*$)/,
foldingStopMarker:
/(?<_1><\/(?i:(?<_2>head|table|tr|div|style|script|ul|ol|form|dl))>|\{\{?\/(?<_3>if|foreach|capture|literal|foreach|php|section|strip)|(?<_4>^|\s)\})/,
name: "Smarty",
patterns:
[{begin: /(?<=\{)\*/,
captures: {0 => {name: "punctuation.definition.comment.smarty"}},
end: "\\*(?=\\})",
name: "comment.block.smarty"},
{match: /\b(?<_1>if|else|elseif|foreach|foreachelse|section)\b/,
name: "keyword.control.smarty"},
{match:
/\b(?<_1>capture|config_load|counter|cycle|debug|eval|fetch|include_php|include|insert|literal|math|strip|rdelim|ldelim|assign|html_[a-z_]*)\b/,
name: "support.function.built-in.smarty"},
{match: /\b(?<_1>and|or)\b/, name: "keyword.operator.smarty"},
{match: /\b(?<_1>eq|neq|gt|lt|gte|lte|is|not|even|odd|not|mod|div|by)\b/,
name: "keyword.operator.other.smarty"},
{match:
/\|(?<_1>capitalize|cat|count_characters|count_paragraphs|count_sentences|count_words|date_format|default|escape|indent|lower|nl2br|regex_replace|replace|spacify|string_format|strip_tags|strip|truncate|upper|wordwrap)/,
name: "support.function.variable-modifier.smarty"},
{match: /\b[a-zA-Z]+=/, name: "meta.attribute.smarty"},
{begin: /'/,
beginCaptures: {0 => {name: "punctuation.definition.string.begin.smarty"}},
end: "'",
endCaptures: {0 => {name: "punctuation.definition.string.end.smarty"}},
name: "string.quoted.single.smarty",
patterns: [{match: /\\./, name: "constant.character.escape.smarty"}]},
{begin: /"/,
beginCaptures: {0 => {name: "punctuation.definition.string.begin.smarty"}},
end: "\"",
endCaptures: {0 => {name: "punctuation.definition.string.end.smarty"}},
name: "string.quoted.double.smarty",
patterns: [{match: /\\./, name: "constant.character.escape.smarty"}]},
{captures: {1 => {name: "punctuation.definition.variable.smarty"}},
match: /\b(?<_1>\$)Smarty\./,
name: "variable.other.global.smarty"},
{captures: {1 => {name: "punctuation.definition.variable.smarty"}},
match: /(?<_1>\$)\w\w*?\b/,
name: "variable.other.smarty"},
{match: /\b(?<_1>TRUE|FALSE|true|false)\b/,
name: "constant.language.smarty"}],
scopeName: "source.smarty",
uuid: "4D6BBA54-E3FC-4296-9CA1-662B2AD537C6"}
| 51.4375 | 224 | 0.646821 |
e8b3012e70179dc0ae564ad3004210efb8ebf528 | 464 | module LogMinimal
module Methods
[:fatal, :error, :warn, :info, :debug].each do |method|
define_method "#{method}f" do |message|
caller = "%s#%s:%s" % [self.class, caller(1)[0].scan(/in `(.*)'/)[0][0], caller(1)[0].scan(/:(\d+):/)[0][0]]
logger.send(method, "%s\t%s" % [caller, message])
end
end
unless respond_to?(:logger)
def logger
@_logger ||= Logger.new(Configuration.path)
end
end
end
end
| 27.294118 | 116 | 0.551724 |
62166b6bf0c34ac17b19f9b1d413306c1e5cd685 | 4,309 | require File.expand_path('../../spec_helper', __FILE__)
module Pod
describe Specification::Set do
describe 'In general' do
before do
@source = Source.new(fixture('spec-repos/master'))
@set = Spec::Set.new('CocoaLumberjack', @source)
end
it 'returns the name of the pod' do
@set.name.should == 'CocoaLumberjack'
end
it 'returns the versions available for the pod ordered from highest to lowest' do
@set.versions.should.all { |v| v.is_a?(Version) }
@set.versions.map(&:to_s).should == %w(1.6.2 1.6.1 1.6 1.3.3 1.3.2 1.3.1 1.3 1.2.3 1.2.2 1.2.1 1.2 1.1 1.0)
end
it 'returns the highest version available for the pod' do
@set.highest_version.should == Version.new('1.6.2')
end
it 'returns the path of the spec with the highest version' do
@set.highest_version_spec_path.should == @source.repo + 'CocoaLumberjack/1.6.2/CocoaLumberjack.podspec'
end
it 'can test if it is equal to another set' do
@set.should == Spec::Set.new('CocoaLumberjack', @source)
@set.should.not == Spec::Set.new('RestKit', @source)
end
it 'returns a hash representation' do
spec_path = @source.repo + 'CocoaLumberjack/1.6.2/CocoaLumberjack.podspec'
@set.to_hash.should == {
'name' => 'CocoaLumberjack',
'versions' => {
'master' => [
'1.6.2', '1.6.1', '1.6', '1.3.3', '1.3.2', '1.3.1', '1.3', '1.2.3', '1.2.2',
'1.2.1', '1.2', '1.1', '1.0'
],
},
'highest_version' => '1.6.2',
'highest_version_spec' => spec_path.to_s,
}
end
#--------------------------------------#
it 'ignores dot files when getting the version directories' do
`touch #{fixture('spec-repos/master/CocoaLumberjack/.DS_Store')}`
should.not.raise do
@set.versions
end
end
end
#-------------------------------------------------------------------------#
describe 'Concerning multiple sources' do
before do
# JSONKit is in test repo has version 1.4 (duplicated) and the 999.999.999.
repos = [Source.new(fixture('spec-repos/test_repo')), Source.new(fixture('spec-repos/master'))]
@set = Source::Aggregate.new(repos).search_by_name('JSONKit').first
end
it 'returns the sources where a podspec is available' do
@set.sources.map(&:name).should == %w(test_repo master)
end
it 'returns all the available versions sorted from biggest to lowest' do
@set.versions.map(&:to_s).should == %w(999.999.999 1.13 1.5pre 1.4)
end
it 'returns all the available versions by source sorted from biggest to lowest' do
hash = {}
@set.versions_by_source.each { |source, versions| hash[source.name] = versions.map(&:to_s) }
hash['master'].should == %w(1.5pre 1.4)
hash['test_repo'].should == %w(999.999.999 1.13 1.4)
hash.keys.sort.should == %w(master test_repo)
end
end
end
#---------------------------------------------------------------------------#
describe Specification::Set::External do
before do
@spec = Spec.from_file(fixture('BananaLib.podspec'))
@set = Spec::Set::External.new(@spec)
end
it 'returns the specification' do
@set.specification.should == @spec
end
it 'returns the name' do
@set.name.should == 'BananaLib'
end
it 'returns whether it is equal to another set' do
@set.should == Spec::Set::External.new(@spec)
end
it 'returns the version of the specification' do
@set.versions.map(&:to_s).should == ['1.0']
end
end
#---------------------------------------------------------------------------#
describe 'Handling empty directories' do
before do
repos = [Source.new(fixture('spec-repos/test_empty_dir_repo'))]
@set = Source::Aggregate.new(repos).search_by_name('EmptyDir_spec').first
end
it 'raises when encountering empty directories' do
@set.name.should == 'EmptyDir_spec'
exception = lambda { @set.specification }.should.raise Informative
exception.message.should.include 'Could not find the highest version for `EmptyDir_spec`.'
end
end
end
| 34.472 | 115 | 0.570202 |
624eb075f81231ab8f7beddd416b99693869f09b | 1,679 | class Blockhash < Formula
desc "Perceptual image hash calculation tool"
homepage "https://github.com/commonsmachinery/blockhash"
url "https://github.com/commonsmachinery/blockhash/archive/v0.3.1.tar.gz"
sha256 "56e8d2fecf2c7658c9f8b32bfb2d29fdd0d0535ddb3082e44b45a5da705aca86"
license "MIT"
revision 2
head "https://github.com/commonsmachinery/blockhash.git"
bottle do
cellar :any
sha256 "4cc1dfdfa365edd25d95d9188e9b45f03477a7c138ff3e539dce3ff839f7330c" => :big_sur
sha256 "3db282d2098b5e52c197a62e977382fe5b192ce22ecb88020599534e07682475" => :catalina
sha256 "45c611b516f5a0f53c75588ede65591eab5ec76bc65e05e5400ef232cb367a89" => :mojave
sha256 "3b46ba7629e56dc9ef1b5a8a00fe7dc43b81d1f09b8f9efcb8bff49ecf16676e" => :high_sierra
end
depends_on "pkg-config" => :build
depends_on "imagemagick"
depends_on :macos # Due to Python 2
resource "testdata" do
url "https://raw.githubusercontent.com/commonsmachinery/blockhash/ce08b465b658c4e886d49ec33361cee767f86db6/testdata/clipper_ship.jpg"
sha256 "a9f6858876adadc83c8551b664632a9cf669c2aea4fec0c09d81171cc3b8a97f"
end
def install
system "./waf", "configure", "--prefix=#{prefix}"
# pkg-config adds -fopenmp flag during configuring
# This fails the build on system clang, and OpenMP is not used in blockhash
inreplace "build/c4che/_cache.py", "-fopenmp", ""
system "./waf"
system "./waf", "install"
end
test do
resource("testdata").stage testpath
hash = "00007ff07ff07fe07fe67ff07560600077fe701e7f5e000079fd40410001ffff"
result = shell_output("#{bin}/blockhash #{testpath}/clipper_ship.jpg")
assert_match hash, result
end
end
| 39.046512 | 137 | 0.773675 |
eda0e4bbb394c9368be080b6891e6f93ff533bbd | 940 | # encoding: UTF-8
# frozen_string_literal: true
#
# Copyright 2016, Ole Claussen <[email protected]>
#
# 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 'packer_dsl/provisioners/base'
module PackerDSL
module Provisioners
module Shell
class Local < Provisioners::Base
register_as Shell::Local, provisioner: 'shell-local'
property :command
property :execute_command
end
end
end
end
| 28.484848 | 74 | 0.735106 |
4a3e98055ba9cf551f6feeb985ebde61bbc6ef60 | 67 | # frozen_string_literal: true
class Staff < ApplicationRecord
end
| 13.4 | 31 | 0.820896 |
1ac537be8311e41de64eeb9fe76a056b1be65c70 | 2,438 | #
# Copyright (c) 2012 RightScale Inc
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# host/port are constants for Google Compute Engine.
module RightScale::Clouds
class Gce < RightScale::Cloud
def abbreviation
"gce"
end
def metadata_host
"http://metadata.google.internal"
end
def metadata_url
"/0.1/meta-data/"
end
def userdata_url
"/0.1/meta-data/attributes/"
end
def http_headers
{ "Metadata-Flavor" => "Google" }
end
def fetcher
options = @options.merge({
:headers => http_headers,
:skip => [/auth.token/]
})
@fetcher ||= RightScale::MetadataSources::HttpMetadataSource.new(options)
end
def finish
@fetcher.finish() if @fetcher
end
def metadata
metadata = fetcher.recursive_get(metadata_host + metadata_url)
# Filter out rightscale userdata keys, we get those for userdata below
if metadata && metadata['attributes']
rs_keys = metadata['attributes'].keys.select { |key| key =~ /^RS_/i }
rs_keys.each { |k| metadata['attributes'].delete(k)}
end
metadata
end
def userdata_raw
userdata_hash = fetcher.recursive_get(metadata_host + userdata_url)
userdata_raw = ""
userdata_hash.keys.sort.each do |k|
userdata_raw << "#{k}=#{userdata_hash[k]}&"
end
userdata_raw.chomp("&")
end
end
end
| 31.25641 | 79 | 0.68991 |
aca968d9174a029dc5ded06f1e66764165297254 | 2,445 | require "rubygems"
require File.join(File.dirname(__FILE__), "..", "minitest")
require "logstash/loadlibs"
require "logstash/testcase"
require "logstash/agent"
require "logstash/logging"
require "logstash/outputs/elasticsearch"
require "logstash/search/elasticsearch"
require "logstash/search/query"
require "tmpdir"
describe LogStash::Outputs::ElasticSearch do
before do
FileUtils.rm_r("data") if File.exists?("data")
@output = LogStash::Outputs::ElasticSearch.new({
"type" => ["foo"],
"embedded" => ["true"],
})
@output.register
end # before
after do
@output.teardown
FileUtils.rm_r("data") if File.exists?("data")
end # after
test "elasticsearch basic output" do
events = []
myfile = File.basename(__FILE__)
1.upto(5).each do |i|
events << LogStash::Event.new("@message" => "just another log rollin' #{i}",
"@source" => "logstash tests in #{myfile}")
end
# TODO(sissel): Need a way to hook when the agent is ready?
events.each do |e|
puts "Pushing event: #{e}" if $DEBUG
@output.receive(e)
end
tries = 30
es = LogStash::Search::ElasticSearch.new(:type => :local)
while tries > 0
tries -= 1
puts "Tries left: #{tries}" if $DEBUG
query = LogStash::Search::Query.new(:query_string => "*", :count => 5)
begin
es.search(query, async=false) do |result|
if events.size == result.events.size
puts "Found #{result.events.size} events, ready to verify!"
expected = events.clone
assert_equal(events.size, result.events.size)
#events.each { |e| p :expect => e }
result.events.each do |event|
assert(expected.include?(event), "Found event in results that was not expected: #{event.inspect}\n\nExpected: #{events.map{ |a| a.inspect }.join("\n")}")
end
return
else
tries -= 1
if tries <= 0
assert(false, "Gave up trying to query elasticsearch. Maybe we aren't indexing properly?")
return
end
end # if events.size == hits.size
end # es.search
rescue org.elasticsearch.action.search.SearchPhaseExecutionException => e
# ignore
end
sleep 0.2
end # while tries > 0
end # test_elasticsearch_basic
end # testing for LogStash::Outputs::ElasticSearch
| 31.753247 | 167 | 0.604499 |
1db2720c76bf0709d8be521ec15ab8bbfd231077 | 1,642 | #
# Be sure to run `pod lib lint SHPAnalytic.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'SHPAnalytic'
s.version = '0.1.0'
s.summary = 'A short description of SHPAnalytic.'
# 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
TODO: Add long description of the pod here.
DESC
s.homepage = 'https://github.com/[email protected]/SHPAnalytic'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { '[email protected]' => '[email protected]' }
s.source = { :git => 'https://github.com/[email protected]/SHPAnalytic.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0'
s.source_files = 'SHPAnalytic/Classes/**/*'
# s.resource_bundles = {
# 'SHPAnalytic' => ['SHPAnalytic/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 38.186047 | 117 | 0.6419 |
3972fd3badecc6c9814634973606befc91b7ed5e | 861 | module NavigationHelpers
# Maps a name to a path. Used by the
#
# When /^I go to (.+)$/ do |page_name|
#
# step definition in web_steps.rb
#
def path_to(page_name)
case page_name
when /^the home\s?page$/
'/'
# Add more mappings here.
# Here is an example that pulls values out of the Regexp:
#
# when /^(.*)'s profile page$/i
# user_profile_path(User.find_by_login($1))
else
begin
page_name =~ /^the (.*) page$/
path_components = $1.split(/\s+/)
self.send(path_components.push('path').join('_').to_sym)
rescue NoMethodError, ArgumentError
raise "Can't find mapping from \"#{page_name}\" to a path.\n" +
"Now, go and add a mapping in #{__FILE__}"
end
end
end
end
World(NavigationHelpers)
World(Rails.application.routes.url_helpers)
| 24.6 | 71 | 0.60511 |
e963cf336330f7b3098456b5c285bffd1fa340de | 1,801 | #
# Copyright:: Copyright (c) 2018 GitLab 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.
#
name 'graphicsmagick'
default_version '1.3.29'
license 'MIT'
license_file 'Copyright.txt'
skip_transitive_dependency_licensing true
dependency 'libpng'
dependency 'zlib'
source url: "http://ftp.icm.edu.pl/pub/unix/graphics/GraphicsMagick/1.3/GraphicsMagick-#{version}.tar.gz",
sha256: 'de820cd10597205941a7e9d02c2e679231e92e8e769c204ef09034d2279ad453'
relative_path "GraphicsMagick-#{version}"
build do
env = with_standard_compiler_flags(with_embedded_path)
configure_command = [
'./configure',
"--prefix=#{install_dir}/embedded",
'--disable-openmp',
'--without-magick-plus-plus',
'--with-perl=no',
'--without-bzlib',
'--without-dps',
'--without-fpx',
'--without-gslib',
'--without-jbig',
'--without-webp',
'--without-jpeg',
'--without-jp2',
'--without-lcms2',
'--without-lzma',
'--with-png',
"--with-sysroot=#{install_dir}/embedded",
'--without-tiff',
'--without-trio',
'--without-ttf',
'--without-umem',
'--without-wmf',
'--without-xml',
'--with-zlib',
'--without-x'
]
command configure_command.join(' '), env: env
make "-j #{workers}", env: env
make 'install', env: env
end
| 26.101449 | 106 | 0.679067 |
1caa3ec2a99d6be61ab12e1cae6e201cfe713a76 | 3,696 | require 'rails_helper'
RSpec.describe Hesa::Grade do
describe '.all' do
it 'returns a list of HESA grade structs' do
grades = described_class.all
expect(grades.size).to eq 15
pass = grades.find { |s| s.hesa_code == '14' }
expect(pass.hesa_code).to eq '14'
expect(pass.description).to eq 'Pass'
end
end
describe '.find_by_description' do
subject(:result) { described_class.find_by_description(description) }
context 'when search by description' do
let(:description) { 'Lower second-class honours (2:2)' }
it 'returns the result' do
expect(result.description).to eq(description)
end
end
context 'when search by a synonym' do
let(:description) { 'First class honours' }
it 'returns the result' do
expect(result).not_to be_nil
expect(result.description).to eq('First-class honours')
end
end
context 'when there is no data' do
let(:description) { 'This does not exist' }
it 'returns nil' do
expect(result).to be_nil
end
end
end
describe '.main_grouping' do
it 'returns undergrad and postgrad grades with the "main" visual grouping' do
main_grades = described_class.main_grouping
expect(main_grades.size).to eq 9
first = main_grades.first
merit = main_grades.find { |g| g.hesa_code == '13' }
expect(first.description).to eq 'First-class honours'
expect(merit.description).to eq 'Merit'
expect(first.visual_grouping).to eq :main_undergrad
expect(merit.visual_grouping).to eq :main_postgrad
end
end
describe '.undergrad_grouping_only' do
it 'returns only undergrad grades with the "main" visual grouping' do
main_grades = described_class.undergrad_grouping_only
expect(main_grades.size).to eq 5
first = main_grades.first
merit = main_grades.find { |g| g.hesa_code == '13' }
expect(first.description).to eq 'First-class honours'
expect(merit).to be_nil
end
end
describe '.other_grouping' do
it 'returns grades with the "other" visual grouping' do
other_grades = described_class.other_grouping
expect(other_grades.size).to eq 6
unclassified = other_grades.third
expect(unclassified.description).to eq 'Unclassified'
expect(unclassified.visual_grouping).to eq :other
end
end
describe '.grouping_for(degree_type_code:)' do
context 'given a valid HESA degree type code for a bachelors degree' do
let(:grouping) { described_class.grouping_for(degree_type_code: '51') }
it 'returns the undergrad grouping only' do
expect(grouping.size).to eq 5
expect(grouping.first.visual_grouping).to eq :main_undergrad
expect(grouping.find { |grade| grade.visual_grouping == :main_postgrad }).to be_nil
end
end
context 'given a valid HESA degree type code for a non-bachelors degree' do
let(:grouping) { described_class.grouping_for(degree_type_code: 200) }
it 'returns the entire main grouping' do
expect(grouping.size).to eq 9
expect(grouping.first.visual_grouping).to eq :main_undergrad
expect(grouping.find { |grade| grade.visual_grouping == :main_postgrad }).not_to be_nil
end
end
context 'given an invalid degree type code' do
let(:grouping) { described_class.grouping_for(degree_type_code: nil) }
it 'returns the entire main grouping' do
expect(grouping.size).to eq 9
expect(grouping.first.visual_grouping).to eq :main_undergrad
expect(grouping.find { |grade| grade.visual_grouping == :main_postgrad }).not_to be_nil
end
end
end
end
| 32.707965 | 95 | 0.682089 |
7a82901786bd751a0cdbcd32d2801c21a23b8b9e | 7,824 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Google
module Devtools
module Clouderrorreporting
module V1beta1
# Description of a group of similar error events.
# @!attribute [rw] name
# @return [String]
# The group resource name.
# Example: <code>projects/my-project-123/groups/my-groupid</code>
# @!attribute [rw] group_id
# @return [String]
# Group IDs are unique for a given project. If the same kind of error
# occurs in different service contexts, it will receive the same group ID.
# @!attribute [rw] tracking_issues
# @return [Array<Google::Devtools::Clouderrorreporting::V1beta1::TrackingIssue>]
# Associated tracking issues.
class ErrorGroup; end
# Information related to tracking the progress on resolving the error.
# @!attribute [rw] url
# @return [String]
# A URL pointing to a related entry in an issue tracking system.
# Example: https://github.com/user/project/issues/4
class TrackingIssue; end
# An error event which is returned by the Error Reporting system.
# @!attribute [rw] event_time
# @return [Google::Protobuf::Timestamp]
# Time when the event occurred as provided in the error report.
# If the report did not contain a timestamp, the time the error was received
# by the Error Reporting system is used.
# @!attribute [rw] service_context
# @return [Google::Devtools::Clouderrorreporting::V1beta1::ServiceContext]
# The +ServiceContext+ for which this error was reported.
# @!attribute [rw] message
# @return [String]
# The stack trace that was reported or logged by the service.
# @!attribute [rw] context
# @return [Google::Devtools::Clouderrorreporting::V1beta1::ErrorContext]
# Data about the context in which the error occurred.
class ErrorEvent; end
# Describes a running service that sends errors.
# Its version changes over time and multiple versions can run in parallel.
# @!attribute [rw] service
# @return [String]
# An identifier of the service, such as the name of the
# executable, job, or Google App Engine service name. This field is expected
# to have a low number of values that are relatively stable over time, as
# opposed to +version+, which can be changed whenever new code is deployed.
#
# Contains the service name for error reports extracted from Google
# App Engine logs or +default+ if the App Engine default service is used.
# @!attribute [rw] version
# @return [String]
# Represents the source code version that the developer provided,
# which could represent a version label or a Git SHA-1 hash, for example.
# @!attribute [rw] resource_type
# @return [String]
# Type of the MonitoredResource. List of possible values:
# https://cloud.google.com/monitoring/api/resources
#
# Value is set automatically for incoming errors and must not be set when
# reporting errors.
class ServiceContext; end
# A description of the context in which an error occurred.
# This data should be provided by the application when reporting an error,
# unless the
# error report has been generated automatically from Google App Engine logs.
# @!attribute [rw] http_request
# @return [Google::Devtools::Clouderrorreporting::V1beta1::HttpRequestContext]
# The HTTP request which was processed when the error was
# triggered.
# @!attribute [rw] user
# @return [String]
# The user who caused or was affected by the crash.
# This can be a user ID, an email address, or an arbitrary token that
# uniquely identifies the user.
# When sending an error report, leave this field empty if the user was not
# logged in. In this case the
# Error Reporting system will use other data, such as remote IP address, to
# distinguish affected users. See +affected_users_count+ in
# +ErrorGroupStats+.
# @!attribute [rw] report_location
# @return [Google::Devtools::Clouderrorreporting::V1beta1::SourceLocation]
# The location in the source code where the decision was made to
# report the error, usually the place where it was logged.
# For a logged exception this would be the source line where the
# exception is logged, usually close to the place where it was
# caught. This value is in contrast to +Exception.cause_location+,
# which describes the source line where the exception was thrown.
class ErrorContext; end
# HTTP request data that is related to a reported error.
# This data should be provided by the application when reporting an error,
# unless the
# error report has been generated automatically from Google App Engine logs.
# @!attribute [rw] method
# @return [String]
# The type of HTTP request, such as +GET+, +POST+, etc.
# @!attribute [rw] url
# @return [String]
# The URL of the request.
# @!attribute [rw] user_agent
# @return [String]
# The user agent information that is provided with the request.
# @!attribute [rw] referrer
# @return [String]
# The referrer information that is provided with the request.
# @!attribute [rw] response_status_code
# @return [Integer]
# The HTTP response status code for the request.
# @!attribute [rw] remote_ip
# @return [String]
# The IP address from which the request originated.
# This can be IPv4, IPv6, or a token which is derived from the
# IP address, depending on the data that has been provided
# in the error report.
class HttpRequestContext; end
# Indicates a location in the source code of the service for which
# errors are reported.
# This data should be provided by the application when reporting an error,
# unless the error report has been generated automatically from Google App
# Engine logs. All fields are optional.
# @!attribute [rw] file_path
# @return [String]
# The source code filename, which can include a truncated relative
# path, or a full path from a production machine.
# @!attribute [rw] line_number
# @return [Integer]
# 1-based. 0 indicates that the line number is unknown.
# @!attribute [rw] function_name
# @return [String]
# Human-readable name of a function or method.
# The value can include optional context like the class or package name.
# For example, +my.package.MyClass.method+ in case of Java.
class SourceLocation; end
end
end
end
end | 49.834395 | 90 | 0.63318 |
115bcea8d9649727e2af541301c614f66da55063 | 896 | # Convert a hash containing supplied and expected contents
# into either supplied or expected
#
# args = { placeholder: { provided: 'Seymour Skinner', output: 'Seymour Skinner' } }
# extract_args(args, :output)
#
# => { placeholder: 'Seymour Skinner' }
#
def extract_args(args, subkey)
args.each.with_object({}) { |(k, v), h| h[k] = v[subkey] }
end
def underscores_to_dashes(val)
val.to_s.tr('_', '-')
end
def dashes_to_underscores(val)
val.to_s.tr('-', '_')
end
def rails_version
ENV.fetch('RAILS_VERSION') { '6.1.1' }
end
def rails_version_later_than_6_1_0?
rails_version >= '6.1.0'
end
def extract_field_names_from_errors_summary_list(document)
document
.css('li > a')
.map { |element| element['href'] }
.map { |href| href.match(%r[#{object_name}-(?<attribute_name>.*)-field-error])[:attribute_name] }
.map { |attribute| dashes_to_underscores(attribute) }
end
| 24.888889 | 101 | 0.6875 |
03790485163a22bce4e0443f2cc60bd3a373dfc5 | 1,794 | class Proctools < Formula
desc "pgrep, pkill, and pfind for OpenBSD and Darwin (OS X)"
homepage "http://proctools.sourceforge.net/"
url "https://downloads.sourceforge.net/project/proctools/proctools/0.4pre1/proctools-0.4pre1.tar.gz"
version "0.4pre1"
sha256 "4553b9c6eda959b12913bc39b6e048a8a66dad18f888f983697fece155ec5538"
bottle do
cellar :any_skip_relocation
sha256 "ed8136da9f7b607eec69d014b1c3f81b9ef3f004f38cc2904400861c0d6adab0" => :el_capitan
sha256 "a05e2adbc0ff0e11be133a81748fc123adc8b32002ff5efb49d141a354f92d70" => :yosemite
sha256 "812961a8a321441010a786c4de1b97c830181a013dae457b6b44c96ce799eb22" => :mavericks
end
depends_on "bsdmake" => :build
# Patches via MacPorts
{
"pfind-Makefile" => "d3ee204bbc708ee650b7310f58e45681c5ca0b3c3c5aa82fa4b402f7f5868b11",
"pfind-pfind.c" => "88f1bc60e3cf269ad012799dc6ddce27c2470eeafb7745bc5d14b78a2bdfbe96",
"pgrep-Makefile" => "f7f2bc21cab6ef02a89ee9e9f975d6a533d012b23720c3c22e66b746beb493fb",
"pkill-Makefile" => "bac12837958bc214234d47abe204ee6ad0da2d69440cf38b1e39ab986cc39d29",
"proctools-fmt.c" => "1a95516de3b6573a96f4ec4be933137e152631ad495f1364c1dd5ce3a9c79bc8",
"proctools-proctools.c" => "1d08e570cc32ff08f8073308da187e918a89a783837b1ea20735ea25ae18bfdb",
"proctools-proctools.h" => "7c2ee6ac3dc7b26fb6738496fbabb1d1d065302a39207ae3fbacb1bc3a64371a",
}.each do |name, sha|
patch :p0 do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/f411d167/proctools/patch-#{name}.diff"
sha256 sha
end
end
def install
system "bsdmake", "PREFIX=#{prefix}"
["pgrep/pgrep", "pkill/pkill", "pfind/pfind"].each do |prog|
bin.install prog
man1.install prog + ".1"
end
end
end
| 42.714286 | 108 | 0.75864 |
91236063af4954903cc445c535c3e35dfbf522fa | 3,418 | require 'spec_helper'
describe 'simpmod' do
shared_examples_for "a structured module" do
it { is_expected.to compile.with_all_deps }
it { is_expected.to create_class('simpmod') }
it { is_expected.to contain_class('simpmod') }
it { is_expected.to contain_class('simpmod::install').that_comes_before('Class[simpmod::config]') }
it { is_expected.to contain_class('simpmod::config') }
it { is_expected.to contain_class('simpmod::service').that_subscribes_to('Class[simpmod::config]') }
it { is_expected.to contain_service('simpmod') }
it { is_expected.to contain_package('simpmod').with_ensure('present') }
end
context 'supported operating systems' do
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) do
facts
end
context "simpmod class without any parameters" do
let(:params) {{ }}
it_behaves_like "a structured module"
it { is_expected.to contain_class('simpmod').with_trusted_nets(['127.0.0.1/32']) }
end
context "simpmod class with firewall enabled" do
let(:params) {{
:trusted_nets => ['10.0.2.0/24'],
:tcp_listen_port => 1234,
:enable_firewall => true,
}}
###it_behaves_like "a structured module"
it { is_expected.to contain_class('simpmod::config::firewall') }
it { is_expected.to contain_class('simpmod::config::firewall').that_comes_before('Class[simpmod::service]') }
it { is_expected.to create_iptables__listen__tcp_stateful('allow_simpmod_tcp_connections').with_dports(1234)
}
end
context "simpmod class with selinux enabled" do
let(:params) {{
:enable_selinux => true,
}}
###it_behaves_like "a structured module"
it { is_expected.to contain_class('simpmod::config::selinux') }
it { is_expected.to contain_class('simpmod::config::selinux').that_comes_before('Class[simpmod::service]') }
it { is_expected.to create_notify('FIXME: selinux') }
end
context "simpmod class with auditing enabled" do
let(:params) {{
:enable_auditing => true,
}}
###it_behaves_like "a structured module"
it { is_expected.to contain_class('simpmod::config::auditing') }
it { is_expected.to contain_class('simpmod::config::auditing').that_comes_before('Class[simpmod::service]') }
it { is_expected.to create_notify('FIXME: auditing') }
end
context "simpmod class with logging enabled" do
let(:params) {{
:enable_logging => true,
}}
###it_behaves_like "a structured module"
it { is_expected.to contain_class('simpmod::config::logging') }
it { is_expected.to contain_class('simpmod::config::logging').that_comes_before('Class[simpmod::service]') }
it { is_expected.to create_notify('FIXME: logging') }
end
end
end
end
context 'unsupported operating system' do
describe 'simpmod class without any parameters on Solaris/Nexenta' do
let(:facts) {{
:osfamily => 'Solaris',
:operatingsystem => 'Nexenta',
}}
it { expect { is_expected.to contain_package('simpmod') }.to raise_error(Puppet::Error, /Nexenta not supported/) }
end
end
end
| 38.840909 | 120 | 0.626975 |
62583580558def73fd1f89c7851b60d498035f90 | 1,146 | cask '[email protected]' do
version '2018.3.7f1,9e14d22a41bb'
sha256 :no_check
url "https://download.unity3d.com/download_unity/9e14d22a41bb/MacEditorTargetInstaller/UnitySetup-Facebook-Games-Support-for-Editor-2018.3.7f1.pkg"
name 'Facebook Gameroom Build Support'
homepage 'https://unity3d.com/unity/'
pkg 'UnitySetup-Facebook-Games-Support-for-Editor-2018.3.7f1.pkg'
depends_on cask: '[email protected]'
preflight do
if File.exist? "/Applications/Unity"
FileUtils.move "/Applications/Unity", "/Applications/Unity.temp"
end
if File.exist? "/Applications/Unity-2018.3.7f1"
FileUtils.move "/Applications/Unity-2018.3.7f1", '/Applications/Unity'
end
end
postflight do
if File.exist? '/Applications/Unity'
FileUtils.move '/Applications/Unity', "/Applications/Unity-2018.3.7f1"
end
if File.exist? '/Applications/Unity.temp'
FileUtils.move '/Applications/Unity.temp', '/Applications/Unity'
end
end
uninstall quit: 'com.unity3d.UnityEditor5.x',
delete: '/Applications/Unity-2018.3.7f1/PlaybackEngines/Facebook'
end
| 31.833333 | 149 | 0.719895 |
ac69cc7e11c2ece2e2cbc3413db34e073360ce1d | 11,252 | require File.expand_path("../../../base", __FILE__)
require "vagrant/util/downloader"
describe Vagrant::Util::Downloader do
let(:source) { "foo" }
let(:destination) { "bar" }
let(:exit_code) { 0 }
let(:options) { {} }
let(:subprocess_result) do
double("subprocess_result").tap do |result|
allow(result).to receive(:exit_code).and_return(exit_code)
allow(result).to receive(:stderr).and_return("")
end
end
subject { described_class.new(source, destination, options) }
before :each do
allow(Vagrant::Util::Subprocess).to receive(:execute).and_return(subprocess_result)
allow(Vagrant).to receive(:in_installer?).and_return(false)
end
describe "#download!" do
let(:curl_options) {
["-q", "--fail", "--location", "--max-redirs", "10",
"--verbose", "--user-agent", described_class::USER_AGENT,
"--output", destination, source, {}]
}
context "with UI" do
let(:ui) { Vagrant::UI::Silent.new }
let(:options) { {ui: ui} }
let(:source) { "http://example.org/vagrant.box" }
let(:redirect) { nil }
let(:progress_data) { "Location: #{redirect}" }
after do
expect(subject).to receive(:execute_curl) do |*_, &data_proc|
expect(data_proc).not_to be_nil
data_proc.call(:stderr, progress_data)
end
subject.download!
end
context "with Location header at same host" do
let(:redirect) { "http://example.org/other-vagrant.box" }
it "should not output redirection information" do
expect(ui).not_to receive(:detail)
end
end
context "with Location header at different host" do
let(:redirect) { "http://example.com/vagrant.box" }
it "should output redirection information" do
expect(ui).to receive(:detail).with(/example.com/).and_call_original
end
end
context "with Location header at different subdomain" do
let(:redirect) { "http://downloads.example.org/vagrant.box" }
it "should output redirection information" do
expect(ui).to receive(:detail).with(/downloads.example.org/).and_call_original
end
end
context "with custom header including Location name" do
let(:custom_redirect) { "http://example.com/vagrant.box" }
let(:progress_data) { "X-Custom-Location: #{custom_redirect}" }
it "should not output redirection information" do
expect(ui).not_to receive(:detail)
end
context "with Location header at different host" do
let(:redirect) { "http://downloads.example.com/vagrant.box" }
let(:progress_data) { "X-Custom-Location: #{custom_redirect}\nLocation: #{redirect}" }
it "should output redirection information" do
expect(ui).to receive(:detail).with(/downloads.example.com/).and_call_original
end
end
end
end
context "with a good exit status" do
let(:exit_code) { 0 }
it "downloads the file and returns true" do
expect(Vagrant::Util::Subprocess).to receive(:execute).
with("curl", *curl_options).
and_return(subprocess_result)
expect(subject.download!).to be
end
end
context "with a bad exit status" do
let(:exit_code) { 1 }
let(:subprocess_result_416) do
double("subprocess_result").tap do |result|
allow(result).to receive(:exit_code).and_return(exit_code)
allow(result).to receive(:stderr).and_return("curl: (416) The download is fine")
end
end
it "continues on if a 416 was received" do
expect(Vagrant::Util::Subprocess).to receive(:execute).
with("curl", *curl_options).
and_return(subprocess_result_416)
expect(subject.download!).to be(true)
end
it "raises an exception" do
expect(Vagrant::Util::Subprocess).to receive(:execute).
with("curl", *curl_options).
and_return(subprocess_result)
expect { subject.download! }.
to raise_error(Vagrant::Errors::DownloaderError)
end
end
context "with a username and password" do
it "downloads the file with the proper flags" do
original_source = source
source = "http://foo:[email protected]/box.box"
subject = described_class.new(source, destination)
i = curl_options.index(original_source)
curl_options[i] = "http://example.com/box.box"
i = curl_options.index("--output")
curl_options.insert(i, "foo:bar")
curl_options.insert(i, "-u")
expect(Vagrant::Util::Subprocess).to receive(:execute).
with("curl", *curl_options).
and_return(subprocess_result)
expect(subject.download!).to be(true)
end
end
context "with an urlescaped username and password" do
it "downloads the file with unescaped credentials" do
original_source = source
source = "http://fo%5Eo:b%[email protected]/box.box"
subject = described_class.new(source, destination)
i = curl_options.index(original_source)
curl_options[i] = "http://example.com/box.box"
i = curl_options.index("--output")
curl_options.insert(i, "fo^o:b@r")
curl_options.insert(i, "-u")
expect(Vagrant::Util::Subprocess).to receive(:execute).
with("curl", *curl_options).
and_return(subprocess_result)
expect(subject.download!).to be(true)
end
end
context "with checksum" do
let(:checksum_expected_value){ 'MD5_CHECKSUM_VALUE' }
let(:checksum_invalid_value){ 'INVALID_VALUE' }
let(:filechecksum) { double("filechecksum", checksum: checksum_value) }
let(:checksum_value) { double("checksum_value") }
before { allow(FileChecksum).to receive(:new).with(any_args).and_return(filechecksum) }
[Digest::MD5, Digest::SHA1, Digest::SHA256, Digest::SHA384, Digest::SHA512].each do |klass|
short_name = klass.to_s.split("::").last.downcase
context "using #{short_name} digest" do
subject { described_class.new(source, destination, short_name.to_sym => checksum_expected_value) }
context "that matches expected value" do
let(:checksum_value) { checksum_expected_value }
it "should not raise an exception" do
expect(subject.download!).to be(true)
end
end
context "that does not match expected value" do
let(:checksum_value) { checksum_invalid_value }
it "should raise an exception" do
expect{ subject.download! }.to raise_error(Vagrant::Errors::DownloaderChecksumError)
end
end
end
end
context "using both md5 and sha1 digests" do
context "that both match expected values" do
let(:checksum_value) { checksum_expected_value }
subject { described_class.new(source, destination, md5: checksum_expected_value, sha1: checksum_expected_value) }
it "should not raise an exception" do
expect(subject.download!).to be(true)
end
end
context "that only sha1 matches expected value" do
subject { described_class.new(source, destination, md5: checksum_expected_value, sha1: checksum_expected_value) }
let(:valid_checksum) { double("valid_checksum", checksum: checksum_expected_value) }
let(:invalid_checksum) { double("invalid_checksum", checksum: checksum_invalid_value) }
before do
allow(FileChecksum).to receive(:new).with(anything, :sha1).and_return(valid_checksum)
allow(FileChecksum).to receive(:new).with(anything, :md5).and_return(invalid_checksum)
end
it "should raise an exception" do
expect{ subject.download! }.to raise_error(Vagrant::Errors::DownloaderChecksumError)
end
end
context "that only md5 matches expected value" do
subject { described_class.new(source, destination, md5: checksum_expected_value, sha1: checksum_expected_value) }
let(:valid_checksum) { double("valid_checksum", checksum: checksum_expected_value) }
let(:invalid_checksum) { double("invalid_checksum", checksum: checksum_invalid_value) }
before do
allow(FileChecksum).to receive(:new).with(anything, :md5).and_return(valid_checksum)
allow(FileChecksum).to receive(:new).with(anything, :sha1).and_return(invalid_checksum)
end
it "should raise an exception" do
expect{ subject.download! }.to raise_error(Vagrant::Errors::DownloaderChecksumError)
end
end
context "that none match expected value" do
let(:checksum_value) { checksum_expected_value }
subject { described_class.new(source, destination, md5: checksum_invalid_value, sha1: checksum_invalid_value) }
it "should raise an exception" do
expect{ subject.download! }.to raise_error(Vagrant::Errors::DownloaderChecksumError)
end
end
end
context "when extra download options specified" do
let(:options) { {:box_extra_download_options => ["--test", "arbitrary"]} }
subject { described_class.new(source, destination, options) }
it "inserts the extra download options" do
i = curl_options.index("--output")
curl_options.insert(i, "arbitrary")
curl_options.insert(i, "--test")
expect(Vagrant::Util::Subprocess).to receive(:execute).
with("curl", *curl_options).
and_return(subprocess_result)
expect(subject.download!).to be(true)
end
end
end
end
describe "#head" do
let(:curl_options) {
["-q", "-I", "--fail", "--location", "--max-redirs", "10",
"--verbose", "--user-agent", described_class::USER_AGENT,
source, {}]
}
it "returns the output" do
allow(subprocess_result).to receive(:stdout).and_return("foo")
expect(Vagrant::Util::Subprocess).to receive(:execute).
with("curl", *curl_options).and_return(subprocess_result)
expect(subject.head).to eq("foo")
end
end
describe "#options" do
describe "CURL_CA_BUNDLE" do
let(:ca_bundle){ "CUSTOM_CA_BUNDLE" }
context "when running within the installer" do
before do
allow(Vagrant).to receive(:in_installer?).and_return(true)
allow(ENV).to receive(:[]).with("CURL_CA_BUNDLE").and_return(ca_bundle)
end
it "should set custom CURL_CA_BUNDLE in subprocess ENV" do
_, subprocess_opts = subject.send(:options)
expect(subprocess_opts[:env]).not_to be_nil
expect(subprocess_opts[:env]["CURL_CA_BUNDLE"]).to eql(ca_bundle)
end
end
context "when not running within the installer" do
before{ allow(Vagrant).to receive(:installer?).and_return(false) }
it "should not set custom CURL_CA_BUNDLE in subprocess ENV" do
_, subprocess_opts = subject.send(:options)
expect(subprocess_opts[:env]).to be_nil
end
end
end
end
end
| 35.272727 | 123 | 0.635531 |
e8550f36c2c6d2c3e20b77f1b77be26ab73ae9cb | 6,791 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2015 the OpenProject Foundation (OPF)
#
# 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 doc/COPYRIGHT.rdoc for more details.
#++
require 'spec_helper'
describe WikiMenuItemsController, type: :controller do
let(:current_user) { FactoryGirl.create(:admin) }
# create project with wiki
let(:project) { FactoryGirl.create(:project).reload } # a wiki is created for project, but the object doesn't know of it (FIXME?)
let(:wiki) { project.wiki }
let(:wiki_page) { FactoryGirl.create(:wiki_page, wiki: wiki) } # first wiki page without child pages
let!(:top_level_wiki_menu_item) { FactoryGirl.create(:wiki_menu_item, :with_menu_item_options, wiki: wiki, title: wiki_page.title) }
before :each do
# log in user
allow(User).to receive(:current).and_return current_user
end
describe '#edit' do
# more wiki pages with menu items
let(:another_wiki_page) { FactoryGirl.create(:wiki_page, wiki: wiki) } # second wiki page with two child pages
let!(:another_wiki_page_top_level_wiki_menu_item) { FactoryGirl.create(:wiki_menu_item, wiki: wiki, title: another_wiki_page.title) }
# child pages of another_wiki_page
let(:child_page) { FactoryGirl.create(:wiki_page, parent: another_wiki_page, wiki: wiki) }
let!(:child_page_wiki_menu_item) { FactoryGirl.create(:wiki_menu_item, wiki: wiki, title: child_page.title) }
let(:another_child_page) { FactoryGirl.create(:wiki_page, parent: another_wiki_page, wiki: wiki) }
let!(:another_child_page_wiki_menu_item) { FactoryGirl.create(:wiki_menu_item, wiki: wiki, title: another_child_page.title, parent: top_level_wiki_menu_item) }
let(:grand_child_page) { FactoryGirl.create(:wiki_page, parent: child_page, wiki: wiki) }
let!(:grand_child_page_wiki_menu_item) { FactoryGirl.create(:wiki_menu_item, wiki: wiki, title: grand_child_page.title) }
context 'when no parent wiki menu item has been configured yet' do
context 'and it is a child page' do
before do get :edit, project_id: project.id, id: child_page.title end
subject { response }
it 'preselects the wiki menu item of the parent page as parent wiki menu item option' do
expect(assigns['selected_parent_menu_item_id']).to eq(another_wiki_page_top_level_wiki_menu_item.id)
# see FIXME in menu_helper.rb
end
end
context 'and it is a grand child page the parent of which is not a main item' do
before do
# ensure the parent page of grand_child_page is not a main item
child_page_wiki_menu_item.tap { |page| page.parent = top_level_wiki_menu_item }.save
get :edit, project_id: project.id, id: grand_child_page.title
end
subject { response }
it 'preselects the wiki menu item of the grand parent page as parent wiki menu item option' do
expect(assigns['selected_parent_menu_item_id']).to eq(another_wiki_page_top_level_wiki_menu_item.id)
end
end
end
context 'when a parent wiki menu item has already been configured' do
before do get :edit, project_id: project.id, id: another_child_page.title end
subject { response }
it 'preselects the parent wiki menu item that is already assigned' do
expect(assigns['selected_parent_menu_item_id']).to eq(top_level_wiki_menu_item.id)
end
end
end
shared_context 'when there is one more wiki page with a child page' do
let!(:child_page) { FactoryGirl.create(:wiki_page, parent: wiki_page, wiki: wiki) }
let!(:another_wiki_page) { FactoryGirl.create(:wiki_page, wiki: wiki) } # second wiki page with two child pages
let!(:another_child_page) { FactoryGirl.create(:wiki_page, parent: another_wiki_page, wiki: wiki) }
end
describe '#select_main_menu_item' do
include_context 'when there is one more wiki page with a child page'
before do get :select_main_menu_item, project_id: project, id: wiki_page.id end
subject { assigns['possible_wiki_pages'] }
context 'when selecting a new wiki page to replace the current main menu item' do
it { is_expected.to include wiki_page }
it { is_expected.to include child_page }
it { is_expected.to include another_wiki_page }
it { is_expected.to include another_child_page }
end
end
describe '#replace_main_menu_item' do
include_context 'when there is one more wiki page with a child page'
context 'when another wiki page is selected for replacement' do
let(:selected_page) { child_page }
let(:new_menu_item) { selected_page.menu_item }
before do
post :replace_main_menu_item, project_id: project,
id: wiki_page.id,
wiki_page: { id: selected_page.id }
end
it 'destroys the current wiki menu item' do
expect(wiki_page.menu_item).to be_nil
end
it 'creates a new main menu item for the selected wiki page' do
expect(selected_page.menu_item).to be_present
expect(selected_page.menu_item.parent).to be_nil
end
it 'transfers the menu item options to the selected wiki page' do
expect(new_menu_item.options).to eq(index_page: true, new_wiki_page: true)
end
end
context 'when its own wiki page is selected for replacement' do
let!(:wiki_menu_item) { wiki_page.menu_item }
before do
post :replace_main_menu_item, project_id: project,
id: wiki_page.id,
wiki_page: { id: wiki_page.id }
end
it 'does not destroy the wiki menu item' do
expect(wiki_menu_item.reload).to be_present
end
end
end
end
| 42.710692 | 163 | 0.706818 |
e905c1f13b8f9fa619245fcc5d1664837462b5c5 | 1,166 | module Tokamak
module Representation
module Atom
class Link < XML
def initialize(options_or_obj)
if options_or_obj.kind_of?(Hash)
@doc = Nokogiri::XML::Document.new()
options_or_obj = create_element("link", options_or_obj)
end
super(options_or_obj)
end
def href
@doc["href"]
end
def href=(value)
@doc["href"] = value
end
def rel
@doc["rel"]
end
def rel=(value)
@doc["rel"] = value
end
if method_defined?(:type)
alias_method :__type__, :type
end
def type
@doc["type"]
end
def type=(value)
@doc["type"] = value
end
def hreflang
@doc["hreflang"]
end
def hreflang=(value)
@doc["hreflang"] = value
end
def title
@doc["title"]
end
def title=(value)
@doc["title"] = value
end
def length
@doc["length"]
end
def length=(value)
@doc["length"] = value
end
end
end
end
end | 17.666667 | 65 | 0.473413 |
f756818334956935f08d84ab62fc4228413e4726 | 606 | module TokyoMetro::Factory::Seed::Reference::BarrierFreeFacility::ServiceDetailPattern
private
def pattern_in_db( operation_day_id , whole = nil , search_by: @info )
h = {
operation_day_id: operation_day_id
}.merge( search_by.time_to_h )
if whole.present?
whole.find_or_create_by(h)
else
self.class.db_instance_class_of_barrier_free_service_detail_pattern.find_or_create_by(h)
end
end
def pattern_id( operation_day_id , whole = nil , search_by: @info )
_in_db = pattern_in_db( operation_day_id , whole , search_by: search_by )
_in_db.id
end
end
| 26.347826 | 94 | 0.731023 |
38989ec871ffedfe13629111604ac50cc349a35c | 352 | def bitwise(a, b)
form = "%1$7s:%2$6d %2$016b"
puts form % ["a", a]
puts form % ["b", b]
puts form % ["a and b", a & b]
puts form % ["a or b ", a | b]
puts form % ["a xor b", a ^ b]
puts form % ["not a ", ~a]
puts form % ["a << b ", a << b] # left shift
puts form % ["a >> b ", a >> b] # arithmetic right shift
end
bitwise(14,3)
| 25.142857 | 59 | 0.482955 |
0166433539fbc256418d12fe7983bd3bb1db1e9f | 2,312 | require 'common'
test_check "eval"
test_ok(eval("") == nil)
$bad=false
eval 'while false; $bad = true; print "foo\n" end'
test_ok(!$bad)
test_ok(eval('TRUE'))
test_ok(eval('true'))
test_ok(!eval('NIL'))
test_ok(!eval('nil'))
test_ok(!eval('FALSE'))
test_ok(!eval('false'))
$foo = 'test_ok(true)'
begin
eval $foo
rescue
test_ok(false)
end
test_ok(eval("$foo") == 'test_ok(true)')
test_ok(eval("true") == true)
i = 5
test_ok(eval("i == 5"))
test_ok(eval("i") == 5)
test_ok(eval("defined? i"))
# eval with binding
def test_ev
local1 = "local1"
lambda {
local2 = "local2"
return binding
}.call
end
$x = test_ev
test_ok(eval("local1", $x) == "local1") # normal local var
test_ok(eval("local2", $x) == "local2") # nested local var
$bad = true
begin
p eval("local1")
rescue NameError # must raise error
$bad = false
end
test_ok(!$bad)
module EvTest
EVTEST1 = 25
evtest2 = 125
$x = binding
end
test_ok(eval("EVTEST1", $x) == 25) # constant in module
test_ok(eval("evtest2", $x) == 125) # local var in module
$bad = true
begin
eval("EVTEST1")
rescue NameError # must raise error
$bad = false
end
test_ok(!$bad)
x = proc{}
eval "i4 = 1", x
test_ok(eval("i4", x) == 1)
x = proc{proc{}}.call
eval "i4 = 22", x
test_ok(eval("i4", x) == 22)
$x = []
x = proc{proc{}}.call
eval "(0..9).each{|i5| $x[i5] = proc{i5*2}}", x
test_ok($x[4].call == 8)
x = binding
eval "i = 1", x
test_ok(eval("i", x) == 1)
x = proc{binding}.call
eval "i = 22", x
test_ok(eval("i", x) == 22)
$x = []
x = proc{binding}.call
eval "(0..9).each{|i5| $x[i5] = proc{i5*2}}", x
test_ok($x[4].call == 8)
x = proc{binding}.call
eval "for i6 in 1..1; j6=i6; end", x
test_ok(eval("defined? i6", x))
test_ok(eval("defined? j6", x))
proc {
p = binding
eval "foo11 = 1", p
foo22 = 5
proc{foo11=22}.call
proc{foo22=55}.call
test_ok(eval("foo11", p) == eval("foo11"))
test_ok(eval("foo11") == 1)
test_ok(eval("foo22", p) == eval("foo22"))
test_ok(eval("foo22") == 55)
}.call
p1 = proc{i7 = 0; proc{i7}}.call
test_ok(p1.call == 0)
eval "i7=5", p1
test_ok(p1.call == 5)
test_ok(!defined?(i7))
p1 = proc{i7 = 0; proc{i7}}.call
i7 = nil
test_ok(p1.call == 0)
eval "i7=1", p1
test_ok(p1.call == 1)
eval "i7=5", p1
test_ok(p1.call == 5)
test_ok(i7 == nil)
loop{iii=5; test_ok(eval("defined? iii")); break}
| 19.266667 | 58 | 0.610727 |
f769a5955c2c80e684484dd5876f59bd26f5578e | 227 | require 'rails_helper'
RSpec.describe MonitController, type: :controller do
describe "GET #index" do
it "returns http success" do
get :index
expect(response).to have_http_status(:success)
end
end
end
| 17.461538 | 52 | 0.700441 |
0862e170874fabbcc4c6eb556c0417cb599ebe55 | 353 | module EPUB
class OCF
class PhysicalContainer
class UnpackedDirectory < self
def open
yield self
end
def read(path_name)
::File.read(::File.join(@container_path, path_name))
rescue ::Errno::ENOENT => error
raise NoEntry.from_error(error)
end
end
end
end
end
| 19.611111 | 62 | 0.577904 |
03aa396ead7e949c522235cdfd53b9757b025ccf | 421 | Streakist::Container.finalize(:bugsnag) do |container|
require "bugsnag"
Bugsnag.configure do |config|
config.project_root = Pathname(__FILE__).join("../..").realpath.dirname.freeze
config.release_stage = ENV.fetch("RACK_ENV", "development")
config.notify_release_stages = ["production"]
config.api_key = Streakist::Container.settings.bugsnag_api_key
config.logger.level = Logger::INFO
end
end
| 35.083333 | 82 | 0.738717 |
87209a7ab78920802e79bd8f93c340ad1e6732d7 | 115,676 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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 SqladminV1
# Cloud SQL Admin API
#
# API for Cloud SQL database instance management
#
# @example
# require 'google/apis/sqladmin_v1'
#
# Sqladmin = Google::Apis::SqladminV1 # Alias the module
# service = Sqladmin::SQLAdminService.new
#
# @see https://developers.google.com/cloud-sql/
class SQLAdminService < 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.
attr_accessor :quota_user
def initialize
super('https://sqladmin.googleapis.com/', '',
client_name: 'google-apis-sqladmin_v1',
client_version: Google::Apis::SqladminV1::GEM_VERSION)
@batch_path = 'batch'
end
# Deletes the backup taken by a backup run.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Fixnum] id
# The ID of the backup run to delete. To find a backup run ID, use the [list](
# https://cloud.google.com/sql/docs/mysql/admin-api/rest/v1/backupRuns/list)
# 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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 delete_backup_run(project, instance, id, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:delete, 'v1/projects/{project}/instances/{instance}/backupRuns/{id}', options)
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.params['id'] = id unless id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Retrieves a resource containing information about a backup run.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Fixnum] id
# The ID of this backup run.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::BackupRun] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::BackupRun]
#
# @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_backup_run(project, instance, id, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/projects/{project}/instances/{instance}/backupRuns/{id}', options)
command.response_representation = Google::Apis::SqladminV1::BackupRun::Representation
command.response_class = Google::Apis::SqladminV1::BackupRun
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.params['id'] = id unless id.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Creates a new backup run on demand.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::BackupRun] backup_run_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 insert_backup_run(project, instance, backup_run_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/backupRuns', options)
command.request_representation = Google::Apis::SqladminV1::BackupRun::Representation
command.request_object = backup_run_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists all backup runs associated with the project or a given instance and
# configuration in the reverse chronological order of the backup initiation time.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID, or "-" for all instances. This does not include the
# project ID.
# @param [Fixnum] max_results
# Maximum number of backup runs per response.
# @param [String] page_token
# A previously-returned page token representing part of the larger set of
# results to view.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::BackupRunsListResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::BackupRunsListResponse]
#
# @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_backup_runs(project, instance, max_results: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/projects/{project}/instances/{instance}/backupRuns', options)
command.response_representation = Google::Apis::SqladminV1::BackupRunsListResponse::Representation
command.response_class = Google::Apis::SqladminV1::BackupRunsListResponse
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.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?
execute_or_queue_command(command, &block)
end
# Generates a short-lived X509 certificate containing the provided public key
# and signed by a private key specific to the target instance. Users may use the
# certificate to authenticate as themselves when connecting to the database.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::GenerateEphemeralCertRequest] generate_ephemeral_cert_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::GenerateEphemeralCertResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::GenerateEphemeralCertResponse]
#
# @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 generate_connect_ephemeral_cert(project, instance, generate_ephemeral_cert_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}:generateEphemeralCert', options)
command.request_representation = Google::Apis::SqladminV1::GenerateEphemeralCertRequest::Representation
command.request_object = generate_ephemeral_cert_request_object
command.response_representation = Google::Apis::SqladminV1::GenerateEphemeralCertResponse::Representation
command.response_class = Google::Apis::SqladminV1::GenerateEphemeralCertResponse
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Retrieves connect settings about a Cloud SQL instance.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [String] read_time
# Optional. Optional snapshot read timestamp to trade freshness for performance.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::ConnectSettings] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::ConnectSettings]
#
# @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_connect(project, instance, read_time: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/projects/{project}/instances/{instance}/connectSettings', options)
command.response_representation = Google::Apis::SqladminV1::ConnectSettings::Representation
command.response_class = Google::Apis::SqladminV1::ConnectSettings
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['readTime'] = read_time unless read_time.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Deletes a database from a Cloud SQL instance.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Database instance ID. This does not include the project ID.
# @param [String] database
# Name of the database to be deleted in the instance.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 delete_database(project, instance, database, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:delete, 'v1/projects/{project}/instances/{instance}/databases/{database}', options)
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.params['database'] = database unless database.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Retrieves a resource containing information about a database inside a Cloud
# SQL instance.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Database instance ID. This does not include the project ID.
# @param [String] database
# Name of the database in the instance.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Database] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Database]
#
# @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_database(project, instance, database, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/projects/{project}/instances/{instance}/databases/{database}', options)
command.response_representation = Google::Apis::SqladminV1::Database::Representation
command.response_class = Google::Apis::SqladminV1::Database
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.params['database'] = database unless database.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Inserts a resource containing information about a database inside a Cloud SQL
# instance.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Database instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::Database] database_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 insert_database(project, instance, database_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/databases', options)
command.request_representation = Google::Apis::SqladminV1::Database::Representation
command.request_object = database_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists databases in the specified Cloud SQL instance.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::DatabasesListResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::DatabasesListResponse]
#
# @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_databases(project, instance, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/projects/{project}/instances/{instance}/databases', options)
command.response_representation = Google::Apis::SqladminV1::DatabasesListResponse::Representation
command.response_class = Google::Apis::SqladminV1::DatabasesListResponse
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Partially updates a resource containing information about a database inside a
# Cloud SQL instance. This method supports patch semantics.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Database instance ID. This does not include the project ID.
# @param [String] database
# Name of the database to be updated in the instance.
# @param [Google::Apis::SqladminV1::Database] database_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 patch_database(project, instance, database, database_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:patch, 'v1/projects/{project}/instances/{instance}/databases/{database}', options)
command.request_representation = Google::Apis::SqladminV1::Database::Representation
command.request_object = database_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.params['database'] = database unless database.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Updates a resource containing information about a database inside a Cloud SQL
# instance.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Database instance ID. This does not include the project ID.
# @param [String] database
# Name of the database to be updated in the instance.
# @param [Google::Apis::SqladminV1::Database] database_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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_database(project, instance, database, database_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:put, 'v1/projects/{project}/instances/{instance}/databases/{database}', options)
command.request_representation = Google::Apis::SqladminV1::Database::Representation
command.request_object = database_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.params['database'] = database unless database.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists all available database flags for Cloud SQL instances.
# @param [String] database_version
# Database type and version you want to retrieve flags for. By default, this
# method returns flags for all database types and versions.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::FlagsListResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::FlagsListResponse]
#
# @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_flags(database_version: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/flags', options)
command.response_representation = Google::Apis::SqladminV1::FlagsListResponse::Representation
command.response_class = Google::Apis::SqladminV1::FlagsListResponse
command.query['databaseVersion'] = database_version unless database_version.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Adds a new trusted Certificate Authority (CA) version for the specified
# instance. Required to prepare for a certificate rotation. If a CA version was
# previously added but never used in a certificate rotation, this operation
# replaces that version. There cannot be more than one CA version waiting to be
# rotated in.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 add_instance_server_ca(project, instance, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/addServerCa', options)
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Creates a Cloud SQL instance as a clone of the source instance. Using this
# operation might cause your instance to restart.
# @param [String] project
# Project ID of the source as well as the clone Cloud SQL instance.
# @param [String] instance
# The ID of the Cloud SQL instance to be cloned (source). This does not include
# the project ID.
# @param [Google::Apis::SqladminV1::InstancesCloneRequest] instances_clone_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 clone_instance(project, instance, instances_clone_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/clone', options)
command.request_representation = Google::Apis::SqladminV1::InstancesCloneRequest::Representation
command.request_object = instances_clone_request_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Deletes a Cloud SQL instance.
# @param [String] project
# Project ID of the project that contains the instance to be deleted.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 delete_instance(project, instance, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:delete, 'v1/projects/{project}/instances/{instance}', options)
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Demotes the stand-alone instance to be a Cloud SQL read replica for an
# external database server.
# @param [String] project
# ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance name.
# @param [Google::Apis::SqladminV1::InstancesDemoteMasterRequest] instances_demote_master_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 demote_instance_master(project, instance, instances_demote_master_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/demoteMaster', options)
command.request_representation = Google::Apis::SqladminV1::InstancesDemoteMasterRequest::Representation
command.request_object = instances_demote_master_request_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Exports data from a Cloud SQL instance to a Cloud Storage bucket as a SQL dump
# or CSV file.
# @param [String] project
# Project ID of the project that contains the instance to be exported.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::InstancesExportRequest] instances_export_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 export_instance(project, instance, instances_export_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/export', options)
command.request_representation = Google::Apis::SqladminV1::InstancesExportRequest::Representation
command.request_object = instances_export_request_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Initiates a manual failover of a high availability (HA) primary instance to a
# standby instance, which becomes the primary instance. Users are then rerouted
# to the new primary. For more information, see the [Overview of high
# availability](https://cloud.google.com/sql/docs/mysql/high-availability) page
# in the Cloud SQL documentation. If using Legacy HA (MySQL only), this causes
# the instance to failover to its failover replica instance.
# @param [String] project
# ID of the project that contains the read replica.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::InstancesFailoverRequest] instances_failover_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 failover_instance(project, instance, instances_failover_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/failover', options)
command.request_representation = Google::Apis::SqladminV1::InstancesFailoverRequest::Representation
command.request_object = instances_failover_request_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Retrieves a resource containing information about a Cloud SQL instance.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Database instance ID. This does not include the project ID.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::DatabaseInstance] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::DatabaseInstance]
#
# @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_instance(project, instance, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/projects/{project}/instances/{instance}', options)
command.response_representation = Google::Apis::SqladminV1::DatabaseInstance::Representation
command.response_class = Google::Apis::SqladminV1::DatabaseInstance
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Imports data into a Cloud SQL instance from a SQL dump or CSV file in Cloud
# Storage.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::InstancesImportRequest] instances_import_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 import_instance(project, instance, instances_import_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/import', options)
command.request_representation = Google::Apis::SqladminV1::InstancesImportRequest::Representation
command.request_object = instances_import_request_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Creates a new Cloud SQL instance.
# @param [String] project
# Project ID of the project to which the newly created Cloud SQL instances
# should belong.
# @param [Google::Apis::SqladminV1::DatabaseInstance] database_instance_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 insert_instance(project, database_instance_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances', options)
command.request_representation = Google::Apis::SqladminV1::DatabaseInstance::Representation
command.request_object = database_instance_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists instances under a given project.
# @param [String] project
# Project ID of the project for which to list Cloud SQL instances.
# @param [String] filter
# A filter expression that filters resources listed in the response. The
# expression is in the form of field:value. For example, 'instanceType:
# CLOUD_SQL_INSTANCE'. Fields can be nested as needed as per their JSON
# representation, such as 'settings.userLabels.auto_start:true'. Multiple filter
# queries are space-separated. For example. 'state:RUNNABLE instanceType:
# CLOUD_SQL_INSTANCE'. By default, each expression is an AND expression. However,
# you can include AND and OR expressions explicitly.
# @param [Fixnum] max_results
# The maximum number of results to return per response.
# @param [String] page_token
# A previously-returned page token representing part of the larger set of
# results to view.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::InstancesListResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::InstancesListResponse]
#
# @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_instances(project, filter: nil, max_results: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/projects/{project}/instances', options)
command.response_representation = Google::Apis::SqladminV1::InstancesListResponse::Representation
command.response_class = Google::Apis::SqladminV1::InstancesListResponse
command.params['project'] = project unless project.nil?
command.query['filter'] = filter unless filter.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?
execute_or_queue_command(command, &block)
end
# Lists all of the trusted Certificate Authorities (CAs) for the specified
# instance. There can be up to three CAs listed: the CA that was used to sign
# the certificate that is currently in use, a CA that has been added but not yet
# used to sign a certificate, and a CA used to sign a certificate that has
# previously rotated out.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::InstancesListServerCasResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::InstancesListServerCasResponse]
#
# @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_instance_server_cas(project, instance, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/projects/{project}/instances/{instance}/listServerCas', options)
command.response_representation = Google::Apis::SqladminV1::InstancesListServerCasResponse::Representation
command.response_class = Google::Apis::SqladminV1::InstancesListServerCasResponse
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Updates settings of a Cloud SQL instance. This method supports patch semantics.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::DatabaseInstance] database_instance_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 patch_instance(project, instance, database_instance_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:patch, 'v1/projects/{project}/instances/{instance}', options)
command.request_representation = Google::Apis::SqladminV1::DatabaseInstance::Representation
command.request_object = database_instance_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Promotes the read replica instance to be a stand-alone Cloud SQL instance.
# Using this operation might cause your instance to restart.
# @param [String] project
# ID of the project that contains the read replica.
# @param [String] instance
# Cloud SQL read replica instance name.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 promote_instance_replica(project, instance, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/promoteReplica', options)
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Deletes all client certificates and generates a new server SSL certificate for
# the instance.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 reset_instance_ssl_config(project, instance, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/resetSslConfig', options)
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Restarts a Cloud SQL instance.
# @param [String] project
# Project ID of the project that contains the instance to be restarted.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 restart_instance(project, instance, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/restart', options)
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Restores a backup of a Cloud SQL instance. Using this operation might cause
# your instance to restart.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::InstancesRestoreBackupRequest] instances_restore_backup_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 restore_instance_backup(project, instance, instances_restore_backup_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/restoreBackup', options)
command.request_representation = Google::Apis::SqladminV1::InstancesRestoreBackupRequest::Representation
command.request_object = instances_restore_backup_request_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Rotates the server certificate to one signed by the Certificate Authority (CA)
# version previously added with the addServerCA method.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::InstancesRotateServerCaRequest] instances_rotate_server_ca_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 rotate_instance_server_ca(project, instance, instances_rotate_server_ca_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/rotateServerCa', options)
command.request_representation = Google::Apis::SqladminV1::InstancesRotateServerCaRequest::Representation
command.request_object = instances_rotate_server_ca_request_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Starts the replication in the read replica instance.
# @param [String] project
# ID of the project that contains the read replica.
# @param [String] instance
# Cloud SQL read replica instance name.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 start_instance_replica(project, instance, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/startReplica', options)
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Stops the replication in the read replica instance.
# @param [String] project
# ID of the project that contains the read replica.
# @param [String] instance
# Cloud SQL read replica instance name.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 stop_instance_replica(project, instance, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/stopReplica', options)
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Truncate MySQL general and slow query log tables MySQL only.
# @param [String] project
# Project ID of the Cloud SQL project.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::InstancesTruncateLogRequest] instances_truncate_log_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 truncate_instance_log(project, instance, instances_truncate_log_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/truncateLog', options)
command.request_representation = Google::Apis::SqladminV1::InstancesTruncateLogRequest::Representation
command.request_object = instances_truncate_log_request_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Updates settings of a Cloud SQL instance. Using this operation might cause
# your instance to restart.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::DatabaseInstance] database_instance_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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_instance(project, instance, database_instance_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:put, 'v1/projects/{project}/instances/{instance}', options)
command.request_representation = Google::Apis::SqladminV1::DatabaseInstance::Representation
command.request_object = database_instance_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Retrieves an instance operation that has been performed on an instance.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] operation
# Instance operation ID.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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_operation(project, operation, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/projects/{project}/operations/{operation}', options)
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['operation'] = operation unless operation.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists all instance operations that have been performed on the given Cloud SQL
# instance in the reverse chronological order of the start time.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Fixnum] max_results
# Maximum number of operations per response.
# @param [String] page_token
# A previously-returned page token representing part of the larger set of
# results to view.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::OperationsListResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::OperationsListResponse]
#
# @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_operations(project, instance: nil, max_results: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/projects/{project}/operations', options)
command.response_representation = Google::Apis::SqladminV1::OperationsListResponse::Representation
command.response_class = Google::Apis::SqladminV1::OperationsListResponse
command.params['project'] = project unless project.nil?
command.query['instance'] = instance unless instance.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?
execute_or_queue_command(command, &block)
end
# Reschedules the maintenance on the given instance.
# @param [String] project
# ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::SqlInstancesRescheduleMaintenanceRequestBody] sql_instances_reschedule_maintenance_request_body_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 reschedule_project_instance_maintenance(project, instance, sql_instances_reschedule_maintenance_request_body_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/rescheduleMaintenance', options)
command.request_representation = Google::Apis::SqladminV1::SqlInstancesRescheduleMaintenanceRequestBody::Representation
command.request_object = sql_instances_reschedule_maintenance_request_body_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Start External primary instance migration.
# @param [String] project
# ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::SqlInstancesStartExternalSyncRequest] sql_instances_start_external_sync_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 start_project_instance_external_sync(project, instance, sql_instances_start_external_sync_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/startExternalSync', options)
command.request_representation = Google::Apis::SqladminV1::SqlInstancesStartExternalSyncRequest::Representation
command.request_object = sql_instances_start_external_sync_request_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Verify External primary instance external sync settings.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::SqlInstancesVerifyExternalSyncSettingsRequest] sql_instances_verify_external_sync_settings_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::SqlInstancesVerifyExternalSyncSettingsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::SqlInstancesVerifyExternalSyncSettingsResponse]
#
# @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_project_instance_external_sync_settings(project, instance, sql_instances_verify_external_sync_settings_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/verifyExternalSyncSettings', options)
command.request_representation = Google::Apis::SqladminV1::SqlInstancesVerifyExternalSyncSettingsRequest::Representation
command.request_object = sql_instances_verify_external_sync_settings_request_object
command.response_representation = Google::Apis::SqladminV1::SqlInstancesVerifyExternalSyncSettingsResponse::Representation
command.response_class = Google::Apis::SqladminV1::SqlInstancesVerifyExternalSyncSettingsResponse
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Generates a short-lived X509 certificate containing the provided public key
# and signed by a private key specific to the target instance. Users may use the
# certificate to authenticate as themselves when connecting to the database.
# @param [String] project
# Project ID of the Cloud SQL project.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::SslCertsCreateEphemeralRequest] ssl_certs_create_ephemeral_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::SslCert] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::SslCert]
#
# @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_ssl_cert_ephemeral(project, instance, ssl_certs_create_ephemeral_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/createEphemeral', options)
command.request_representation = Google::Apis::SqladminV1::SslCertsCreateEphemeralRequest::Representation
command.request_object = ssl_certs_create_ephemeral_request_object
command.response_representation = Google::Apis::SqladminV1::SslCert::Representation
command.response_class = Google::Apis::SqladminV1::SslCert
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Deletes the SSL certificate. For First Generation instances, the certificate
# remains valid until the instance is restarted.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [String] sha1_fingerprint
# Sha1 FingerPrint.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 delete_ssl_cert(project, instance, sha1_fingerprint, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:delete, 'v1/projects/{project}/instances/{instance}/sslCerts/{sha1Fingerprint}', options)
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.params['sha1Fingerprint'] = sha1_fingerprint unless sha1_fingerprint.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Retrieves a particular SSL certificate. Does not include the private key (
# required for usage). The private key must be saved from the response to
# initial creation.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [String] sha1_fingerprint
# Sha1 FingerPrint.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::SslCert] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::SslCert]
#
# @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_ssl_cert(project, instance, sha1_fingerprint, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/projects/{project}/instances/{instance}/sslCerts/{sha1Fingerprint}', options)
command.response_representation = Google::Apis::SqladminV1::SslCert::Representation
command.response_class = Google::Apis::SqladminV1::SslCert
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.params['sha1Fingerprint'] = sha1_fingerprint unless sha1_fingerprint.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Creates an SSL certificate and returns it along with the private key and
# server certificate authority. The new certificate will not be usable until the
# instance is restarted.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::SslCertsInsertRequest] ssl_certs_insert_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::SslCertsInsertResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::SslCertsInsertResponse]
#
# @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 insert_ssl_cert(project, instance, ssl_certs_insert_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/sslCerts', options)
command.request_representation = Google::Apis::SqladminV1::SslCertsInsertRequest::Representation
command.request_object = ssl_certs_insert_request_object
command.response_representation = Google::Apis::SqladminV1::SslCertsInsertResponse::Representation
command.response_class = Google::Apis::SqladminV1::SslCertsInsertResponse
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists all of the current SSL certificates for the instance.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Cloud SQL instance ID. This does not include the project ID.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::SslCertsListResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::SslCertsListResponse]
#
# @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_ssl_certs(project, instance, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/projects/{project}/instances/{instance}/sslCerts', options)
command.response_representation = Google::Apis::SqladminV1::SslCertsListResponse::Representation
command.response_class = Google::Apis::SqladminV1::SslCertsListResponse
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists all available machine types (tiers) for Cloud SQL, for example, `db-
# custom-1-3840`. For more information, see https://cloud.google.com/sql/pricing.
# @param [String] project
# Project ID of the project for which to list tiers.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::TiersListResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::TiersListResponse]
#
# @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_tiers(project, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/projects/{project}/tiers', options)
command.response_representation = Google::Apis::SqladminV1::TiersListResponse::Representation
command.response_class = Google::Apis::SqladminV1::TiersListResponse
command.params['project'] = project unless project.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Deletes a user from a Cloud SQL instance.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Database instance ID. This does not include the project ID.
# @param [String] host
# Host of the user in the instance.
# @param [String] name
# Name of the user in the instance.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 delete_user(project, instance, host: nil, name: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:delete, 'v1/projects/{project}/instances/{instance}/users', options)
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['host'] = host unless host.nil?
command.query['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Creates a new user in a Cloud SQL instance.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Database instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::User] user_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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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 insert_user(project, instance, user_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1/projects/{project}/instances/{instance}/users', options)
command.request_representation = Google::Apis::SqladminV1::User::Representation
command.request_object = user_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists users in the specified Cloud SQL instance.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Database instance ID. This does not include the project ID.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::UsersListResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::UsersListResponse]
#
# @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_users(project, instance, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1/projects/{project}/instances/{instance}/users', options)
command.response_representation = Google::Apis::SqladminV1::UsersListResponse::Representation
command.response_class = Google::Apis::SqladminV1::UsersListResponse
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Updates an existing user in a Cloud SQL instance.
# @param [String] project
# Project ID of the project that contains the instance.
# @param [String] instance
# Database instance ID. This does not include the project ID.
# @param [Google::Apis::SqladminV1::User] user_object
# @param [String] host
# Optional. Host of the user in the instance.
# @param [String] name
# Name of the user in the instance.
# @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.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::SqladminV1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::SqladminV1::Operation]
#
# @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_user(project, instance, user_object = nil, host: nil, name: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:put, 'v1/projects/{project}/instances/{instance}/users', options)
command.request_representation = Google::Apis::SqladminV1::User::Representation
command.request_object = user_object
command.response_representation = Google::Apis::SqladminV1::Operation::Representation
command.response_class = Google::Apis::SqladminV1::Operation
command.params['project'] = project unless project.nil?
command.params['instance'] = instance unless instance.nil?
command.query['host'] = host unless host.nil?
command.query['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.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?
end
end
end
end
end
| 62.561385 | 195 | 0.676329 |
ab9817f6ae188e8a9739ed2369f5d4b7ca1fb1f5 | 135 | class RemoveEmailFromSubmissions < ActiveRecord::Migration[6.1]
def change
remove_column :submissions, :email, :string
end
end
| 22.5 | 63 | 0.77037 |
f880edc264fbc7ec0f0b97dd1f13f82bcdc2b540 | 6,500 | require 'pathname'
Puppet::Type.newtype(:dsc_xvhd) do
require Pathname.new(__FILE__).dirname + '../../' + 'puppet/type/base_dsc'
require Pathname.new(__FILE__).dirname + '../../puppet_x/puppetlabs/dsc_type_helpers'
@doc = %q{
The DSC xVHD resource type.
Automatically generated from
'xHyper-V/DSCResources/MSFT_xVHD/MSFT_xVHD.schema.mof'
To learn more about PowerShell Desired State Configuration, please
visit https://technet.microsoft.com/en-us/library/dn249912.aspx.
For more information about built-in DSC Resources, please visit
https://technet.microsoft.com/en-us/library/dn249921.aspx.
For more information about xDsc Resources, please visit
https://github.com/PowerShell/DscResources.
}
validate do
fail('dsc_name is a required attribute') if self[:dsc_name].nil?
fail('dsc_path is a required attribute') if self[:dsc_path].nil?
end
def dscmeta_resource_friendly_name; 'xVHD' end
def dscmeta_resource_name; 'MSFT_xVHD' end
def dscmeta_module_name; 'xHyper-V' end
def dscmeta_module_version; '3.2.0.0' end
newparam(:name, :namevar => true ) do
end
ensurable do
newvalue(:exists?) { provider.exists? }
newvalue(:present) { provider.create }
newvalue(:absent) { provider.destroy }
defaultto { :present }
end
# Name: Name
# Type: string
# IsMandatory: True
# Values: None
newparam(:dsc_name) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "Name - Name of the VHD File"
isrequired
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: Path
# Type: string
# IsMandatory: True
# Values: None
newparam(:dsc_path) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "Path - Folder where the VHD will be created"
isrequired
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: ParentPath
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_parentpath) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "ParentPath - Parent VHD file path, for differencing disk"
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: MaximumSizeBytes
# Type: uint64
# IsMandatory: False
# Values: None
newparam(:dsc_maximumsizebytes) do
def mof_type; 'uint64' end
def mof_is_embedded?; false end
desc "MaximumSizeBytes - Maximum size of Vhd to be created"
validate do |value|
unless (value.kind_of?(Numeric) && value >= 0) || (value.to_i.to_s == value && value.to_i >= 0)
fail("Invalid value #{value}. Should be a unsigned Integer")
end
end
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_integer(value)
end
end
# Name: Generation
# Type: string
# IsMandatory: False
# Values: ["Vhd", "Vhdx"]
newparam(:dsc_generation) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "Generation - Virtual disk format - Vhd or Vhdx Valid values are Vhd, Vhdx."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
unless ['Vhd', 'vhd', 'Vhdx', 'vhdx'].include?(value)
fail("Invalid value '#{value}'. Valid values are Vhd, Vhdx")
end
end
end
# Name: Ensure
# Type: string
# IsMandatory: False
# Values: ["Present", "Absent"]
newparam(:dsc_ensure) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "Ensure - Should the VHD be created or deleted Valid values are Present, Absent."
validate do |value|
resource[:ensure] = value.downcase
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
unless ['Present', 'present', 'Absent', 'absent'].include?(value)
fail("Invalid value '#{value}'. Valid values are Present, Absent")
end
end
end
# Name: ID
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_id) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "ID - Virtual Disk Identifier"
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: Type
# Type: string
# IsMandatory: False
# Values: None
newparam(:dsc_type) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "Type - Type of Vhd - Dynamic, Fixed, Differencing"
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: FileSizeBytes
# Type: uint64
# IsMandatory: False
# Values: None
newparam(:dsc_filesizebytes) do
def mof_type; 'uint64' end
def mof_is_embedded?; false end
desc "FileSizeBytes - Current size of the VHD"
validate do |value|
unless (value.kind_of?(Numeric) && value >= 0) || (value.to_i.to_s == value && value.to_i >= 0)
fail("Invalid value #{value}. Should be a unsigned Integer")
end
end
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_integer(value)
end
end
# Name: IsAttached
# Type: boolean
# IsMandatory: False
# Values: None
newparam(:dsc_isattached) do
def mof_type; 'boolean' end
def mof_is_embedded?; false end
desc "IsAttached - Is the VHD attached to a VM or not"
validate do |value|
end
newvalues(true, false)
munge do |value|
PuppetX::Dsc::TypeHelpers.munge_boolean(value.to_s)
end
end
def builddepends
pending_relations = super()
PuppetX::Dsc::TypeHelpers.ensure_reboot_relationship(self, pending_relations)
end
end
Puppet::Type.type(:dsc_xvhd).provide :powershell, :parent => Puppet::Type.type(:base_dsc).provider(:powershell) do
confine :true => (Gem::Version.new(Facter.value(:powershell_version)) >= Gem::Version.new('5.0.10240.16384'))
defaultfor :operatingsystem => :windows
mk_resource_methods
end
| 29.279279 | 114 | 0.637538 |
79da3550f28c9b87b60c1e057ff4ca10bba9c7b3 | 1,640 | # TODO: clean these requires up so they're consistent
require_relative "ruby_cover_band/amplifier"
require_relative "ruby_cover_band/band"
require_relative "ruby_cover_band/concert"
require_relative "ruby_cover_band/instruments/guitar"
require_relative "ruby_cover_band/instruments/guitar/chords/chord"
require_relative "ruby_cover_band/instruments/guitar/chords/b_flat_half_bar"
require_relative "ruby_cover_band/instruments/guitar/chords/c_half_bar"
require_relative "ruby_cover_band/instruments/guitar/chords/drop_d_low_d"
require_relative "ruby_cover_band/instruments/guitar/chords/d_half_bar"
require_relative "ruby_cover_band/instruments/guitar/chords/f_half_bar"
require_relative "ruby_cover_band/instruments/guitar/chords/power_chord"
require_relative "ruby_cover_band/instruments/guitar/finger_placement"
require_relative "ruby_cover_band/instruments/guitar/fret"
require_relative "ruby_cover_band/instruments/guitar/string"
require_relative "ruby_cover_band/note"
require_relative "ruby_cover_band/setlist"
require_relative "ruby_cover_band/song"
require_relative "ruby_cover_band/songs/the_line_begins_to_blur"
def build_band(name: "Nine Inch Nails")
band = RubyCoverBand::Band.new(name: name)
band.guitarist = RubyCoverBand::Instruments::Guitar.new(tuning: :drop_d, amplifier: RubyCoverBand::Amplifier.new)
band
end
band = build_band(name: "Nine Inch Nails")
setlist = RubyCoverBand::Setlist.new(band)
setlist.add_song(RubyCoverBand::Songs::TheLineBeginsToBlur.new)
concert = RubyCoverBand::Concert.new("RubyConf 2020")
concert.setlist = setlist
10.times do
concert.set_up
concert.perform
concert.load_out
end
| 40 | 115 | 0.846951 |
799cda63e8dd46b743c371c0f68b669ecd8481a0 | 155 | class AddRoleToUsersGroup < ActiveRecord::Migration
def change
add_column :users_groups, :role, :string
add_index :users_groups, :role
end
end
| 22.142857 | 51 | 0.754839 |
87510670d8d10472a327fec96e9d670b30e5b818 | 2,166 | class Frotz < Formula
desc "Infocom-style interactive fiction player"
homepage "https://661.org/proj/if/frotz/"
url "https://gitlab.com/DavidGriffith/frotz/-/archive/2.53/frotz-2.53.tar.bz2"
sha256 "8da558828dd74d6d6ee30483bb32276ef918b8b72b7f6e89b4f7cb27e7abf58b"
license "GPL-2.0-or-later"
head "https://gitlab.com/DavidGriffith/frotz.git"
bottle do
sha256 arm64_monterey: "4b52b494b83a2d60e856a5663e4b84bb2e20d0479ff4781e77a1148dcdf155b3"
sha256 arm64_big_sur: "a51e453e14b7bd58a0a90169ae238f04650b8ffd1f2178f2245afc09127ff2cd"
sha256 monterey: "919b65bd87568ee0060f6ae9668293f95df602e72185d531af6dd9112b9cc901"
sha256 big_sur: "36f0a6760575194191ee9035e479357451ffeeef291fb4697deb61c19524b2ad"
sha256 catalina: "d84c37e5af40ea04a4a23569605d2648480abf394bddc9a1a8e4d75988c73e24"
sha256 mojave: "44612a1e36afeb27bbec0ada1dd7474e20d8f2d8580d32791dd98c2ea862ff0c"
sha256 x86_64_linux: "4eb6b4247b3e7b99e9ce2646f171c312d4af4b961909e33ab394957ed3fa6112"
end
depends_on "pkg-config" => :build
depends_on "freetype"
depends_on "jpeg"
depends_on "libao"
depends_on "libmodplug"
depends_on "libpng"
depends_on "libsamplerate"
depends_on "libsndfile"
depends_on "libvorbis"
depends_on "sdl2"
depends_on "sdl2_mixer"
uses_from_macos "ncurses"
uses_from_macos "zlib"
resource("testdata") do
url "https://gitlab.com/DavidGriffith/frotz/-/raw/2.53/src/test/etude/etude.z5"
sha256 "bfa2ef69f2f5ce3796b96f9b073676902e971aedb3ba690b8835bb1fb0daface"
end
def install
args = %W[PREFIX=#{prefix} MANDIR=#{man} SYSCONFDIR=#{etc} ITALIC=]
targets = %w[frotz dumb sdl]
targets.each do |target|
system "make", target, *args
end
ENV.deparallelize # install has race condition
targets.each do |target|
system "make", "install_#{target}", *args
end
end
test do
resource("testdata").stage do
assert_match "TerpEtude", shell_output("echo \".\" | #{bin}/dfrotz etude.z5")
end
assert_match "FROTZ", shell_output("#{bin}/frotz -v").strip
assert_match "FROTZ", shell_output("#{bin}/sfrotz -v").strip
end
end
| 36.711864 | 93 | 0.750231 |
6237566c7f6035c9700908b26c3cb571920a8a99 | 399 | node = S($input, "application/json")
currencies = node.prop("orderDetails").prop("currencies")
$oldSize = currencies.elements().size()
$oldValue = currencies.elements().get(1).stringValue()
currencies.insertBefore($oldValue, "Test")
$newSize = currencies.elements().size()
$newValue = currencies.elements().get(1).stringValue()
$oldValueOnNewPosition = currencies.elements().get(2).stringValue()
| 33.25 | 67 | 0.744361 |
ff8cbad68fd823202ddb415fe8877ffda3090b1e | 6,073 | require 'spec_helper'
require 'pinpoint_supported_countries'
RSpec.describe PinpointSupportedCountries do
before do
stub_request(:get, PinpointSupportedCountries::PINPOINT_SMS_URL).
to_return(body: sms_table)
stub_request(:get, PinpointSupportedCountries::PINPOINT_VOICE_URL).
to_return(body: voice_table)
stub_const('STDERR', StringIO.new)
end
subject(:countries) { PinpointSupportedCountries.new }
let(:sms_table) do
<<-HTML
<table>
<thead>
<tr>
<th>Country or region</th>
<th>ISO code</th>
<th>Supports sender IDs</th>
<th>Supports two-way SMS (Amazon Pinpoint only)</th>
</tr>
</thead>
<tr>
<td>Argentina</td>
<td>AR</td>
<td></td>
<td>Yes</td>
</tr>
<tr>
<td>Australia</td>
<td>AU</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>Belarus</td>
<td>BY</td>
<td>Yes<sup><a href="#sms-support-note-1">1</a></sup></td>
<td></td>
</tr>
</table>
HTML
end
let(:voice_table) do
<<-HTML
<table>
<thead>
<tr>
<th>Country or Region</th>
<th>Local address required?</th>
<th>Supports SMS?</th>
</tr>
</thead>
<tr>
<td>Argentina</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Australia</td>
<td>Yes</td>
<td>No</td>
</tr>
</table>
HTML
end
describe '#run' do
it 'returns a hash that matches the structure of country_dialing_codes.yml' do
expect(countries.run).to eq YAML.safe_load <<-STR
AR:
country_code: '54'
name: Argentina
supports_sms: true
supports_voice: true
AU:
country_code: '61'
name: Australia
supports_sms: true
supports_voice: true
BY:
country_code: '375'
name: Belarus
supports_sms: false
supports_voice: false
STR
end
end
describe '#sms_support' do
# rubocop:disable Layout/LineLength
it 'parses the SMS page from poinpoint an array of configs' do
expect(countries.sms_support).to eq [
PinpointSupportedCountries::CountrySupport.new(iso_code: 'AR', name: 'Argentina', supports_sms: true),
PinpointSupportedCountries::CountrySupport.new(iso_code: 'AU', name: 'Australia', supports_sms: true),
PinpointSupportedCountries::CountrySupport.new(iso_code: 'BY', name: 'Belarus', supports_sms: false),
]
end
# rubocop:enable Layout/LineLength
end
describe '#voice_support' do
it 'parses the voice page from poinpoint an array of configs' do
expect(countries.voice_support).to eq [
PinpointSupportedCountries::CountrySupport.new(name: 'Argentina', supports_voice: true),
PinpointSupportedCountries::CountrySupport.new(name: 'Australia', supports_voice: true),
]
end
end
describe '#country_dialing_codes' do
# rubocop:disable Layout/LineLength
it 'combines sms and voice support and country code into a shared config' do
expect(countries.country_dialing_codes).to eq [
PinpointSupportedCountries::CountryDialingCode.new(country_code: '54', iso_code: 'AR', name: 'Argentina', supports_sms: true, supports_voice: true),
PinpointSupportedCountries::CountryDialingCode.new(country_code: '61', iso_code: 'AU', name: 'Australia', supports_sms: true, supports_voice: true),
PinpointSupportedCountries::CountryDialingCode.new(country_code: '375', iso_code: 'BY', name: 'Belarus', supports_sms: false, supports_voice: false),
]
end
# rubocop:enable Layout/LineLength
end
describe '#country_code' do
it 'adds the leading digits if they are all digits' do
expect(countries.country_code(country_code: '1', leading_digits: '2345')).to eq('12345')
end
it 'is only the country code if the leading digits have a regex' do
expect(countries.country_code(country_code: '1', leading_digits: '2[3]4')).to eq('1')
end
end
describe PinpointSupportedCountries::CountrySupport do
describe '#merge' do
it 'combines two structs by ||-ing the attributes' do
a = PinpointSupportedCountries::CountrySupport.new(
iso_code: 'US',
supports_sms: true,
)
b = PinpointSupportedCountries::CountrySupport.new(
iso_code: 'US',
name: 'United States',
supports_voice: true,
)
expect(a.merge(b)).to eq PinpointSupportedCountries::CountrySupport.new(
iso_code: 'US',
name: 'United States',
supports_sms: true,
supports_voice: true,
)
end
end
end
describe PinpointSupportedCountries::TableConverter do
describe '#convert' do
let(:html) do
<<-HTML
<html>
<body>
<div>
<table>
<thead>
<tr>
<th>First</th>
<th>Second</th>
<th>Third</th>
</tr>
</thead>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
<tr>
<td>d</td>
<td>e</td>
<td>f</td>
</tr>
</table>
</div>
</body>
</html>
HTML
end
subject(:converter) { PinpointSupportedCountries::TableConverter.new(html) }
it 'converts an HTML table into an array of hashes' do
expect(converter.convert).to eq [
{ 'First' => 'a', 'Second' => 'b', 'Third' => 'c' },
{ 'First' => 'd', 'Second' => 'e', 'Third' => 'f' },
]
end
end
end
end
| 29.62439 | 157 | 0.55014 |
5dba222bba7cefff84398d6c6d4cce3b04e7f8e4 | 486 | # frozen_string_literal: true
require 'spec_helper'
describe RubyHelm::Commands::Reset do
before do
RubyHelm.configure do |config|
config.binary = 'path/to/binary'
end
end
after do
RubyHelm.reset!
end
it 'calls the helm reset command' do
command = described_class.new(binary: 'helm')
allow(Open4).to(receive(:spawn))
command.execute
expect(Open4).to(
have_received(:spawn)
.with('helm reset', any_args)
)
end
end
| 16.758621 | 49 | 0.656379 |
3394c1ec294734745d8b3c9f7f7abb6b4d97f5eb | 992 | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20181017215234) do
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| 41.333333 | 86 | 0.760081 |
e8c2fe879f33fef30ffd424712b0499f7c058c87 | 2,802 | require 'date'
require 'yaml'
require 'fileutils'
require 'sys/proctable'
module MCLimit
# The default number of minutes of game play to allow per day when env not set
DEFAULT_MINUTES = 30
# The minimum number of remaining minutes needed to start the game
MINIMUM_MINUTES = 1
REMAINING_FILE = 'remaining.yml'
GAME_COMMAND = %{javaw.exe -Xms512m -Xmx1024m -cp "%APPDATA%\\.minecraft\\bin\\*" -Djava.library.path="%APPDATA%\\.minecraft\\bin\\natives" net.minecraft.client.Minecraft "#{Etc.getlogin}"}
def self.disappoint( title, body )
GUI.error( body, title )
exit 1
end
def self.game_command
ENV['MC_LIMIT_COMMAND'] || GAME_COMMAND
end
def self.remaining_file
if ENV['MC_LIMIT_FILE'].nil?
if RUBY_PLATFORM =~ /mingw/
File.join( ENV['APPDATA'], '.mc-limit', REMAINING_FILE )
else
File.join( ENV['HOME'], '.mc-limit', REMAINING_FILE )
end
else
ENV['MC_LIMIT_FILE']
end
end
def self.admin_password
ENV['MC_LIMIT_ADMIN_PASSWORD']
end
def self.default_minutes
Float( ENV['DEFAULT_MC_LIMIT'] || DEFAULT_MINUTES )
end
def self.remaining_minutes( date = Date.today )
FileUtils.mkdir_p( File.dirname( MCLimit.remaining_file ) )
yaml = YAML.load_file( MCLimit.remaining_file )
( yaml[:date] == date ) ? Float(yaml[:remaining]) : default_minutes
rescue
default_minutes
end
def self.update_remaining_minutes( minutes )
yaml = { :date => Date.today, :remaining => minutes }.to_yaml
FileUtils.mkdir_p( File.dirname( MCLimit.remaining_file ) )
File.open( MCLimit.remaining_file, 'wt' ) { |f| f.write yaml }
end
def self.stop_minecraft(pids)
if RUBY_PLATFORM =~ /mingw/
Win.close_process(pids, 'Minecraft')
else
pids.each { |pid| kill(:QUIT, pid) }
end
end
def self.timeout_pid(pid, minutes)
Thread.new do
sleep minutes * 60
pids = [ pid ]
Sys::ProcTable.ps do |process|
pids << process.pid if pids.include? process.ppid
end
MCLimit.stop_minecraft(pids)
end
pid
end
def self.validate_sufficient( time_limit )
return if time_limit >= MINIMUM_MINUTES
disappoint( 'Sorry', 'No more Minecraft allowed today!' )
end
def self.run( command, time_limit )
validate_sufficient time_limit
pid = timeout_pid( Process.spawn( command ), time_limit )
end
def self.launch
GUI.new.main_loop do
remaining = MCLimit.remaining_minutes
pid = MCLimit.run( MCLimit.game_command, remaining )
start = Time.now
Process.waitpid( pid, 0 )
finish = Time.now
consumed = ( finish - start ) / 60
remaining = [ 0, remaining - consumed ].sort.last
MCLimit.update_remaining_minutes( remaining )
end
end
end
# vim:ts=2:sw=2:et
| 26.186916 | 191 | 0.668808 |
18bc99e76e49456f0626a0b5fd45689d7cb89206 | 676 | RSpec::Matchers.define :contain_parsed_output do |expected|
match do |actual|
actual_output = pluck_keys expected.keys, actual
expect(actual_output).to eq(expected)
end
def pluck_keys key_names, obj
res = {}
Class.new(Parslet::Transform) do
key_names.each do |key_name|
rule(key_name => subtree(:x)) do |dictionary|
if res[key_name].respond_to? :push
res[key_name] << dictionary[:x]
elsif res[key_name].present?
res[key_name] = [res[key_name], dictionary[:x]]
else
res[key_name] = dictionary[:x]
end
end
end
end.new.apply(obj)
res
end
end
| 27.04 | 59 | 0.606509 |
d582229fcf69bde355d6e77f04a83f67a26b8b7d | 143 | class AddAttributesToRequests < ActiveRecord::Migration[5.1]
def change
add_column :requests, :approved, :string, default: nil
end
end
| 23.833333 | 60 | 0.755245 |
03cc44cf507ad81f6273f9be7df1211d5c69fd6a | 1,590 | require 'test_helper'
class FollowingTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
@other = users(:archer)
log_in_as(@user)
end
test "following page" do
get following_user_path(@user)
assert_not @user.following.empty?
assert_match @user.following.count.to_s, response.body
@user.following.each do |user|
assert_select "a[href=?]", user_path(user)
end
end
test "followers page" do
get followers_user_path(@user)
assert_not @user.followers.empty?
assert_match @user.followers.count.to_s, response.body
@user.followers.each do |user|
assert_select "a[href=?]", user_path(user)
end
end
# Follow/Unfollow
test "should follow a user the standard way" do
assert_difference '@user.following.count', 1 do
post relationships_path, followed_id: @other.id
end
end
test "should follow a user with Ajax" do
assert_difference '@user.following.count', 1 do
xhr :post, relationships_path, followed_id: @other.id
end
end
test "should unfollow a user the standard way" do
@user.follow(@other)
relationship = @user.active_relationships.find_by(followed_id: @other.id)
assert_difference '@user.following.count', -1 do
delete relationship_path(relationship)
end
end
test "should unfollow a user with Ajax" do
@user.follow(@other)
relationship = @user.active_relationships.find_by(followed_id: @other.id)
assert_difference '@user.following.count', -1 do
xhr :delete, relationship_path(relationship)
end
end
end
| 27.894737 | 77 | 0.704403 |
61f546be36423d6ccd36a6a61f8a6767bf653c65 | 1,455 | module StashEngine
describe Lock, '.acquire' do
before :each do
@reader, @writer = IO.pipe
end
def fork_with_new_connection
config = ActiveRecord::Base.remove_connection
fork do
ActiveRecord::Base.establish_connection(config)
yield
ensure
ActiveRecord::Base.remove_connection
Process.exit!
end
ActiveRecord::Base.establish_connection(config)
end
it 'should synchronize processes on the same lock' do
(1..20).each do |i|
fork_with_new_connection do
@reader.close
ActiveRecord::Base.connection.reconnect!
Lock.acquire('lock') do
@writer.puts "Started: #{i}"
sleep 0.01
@writer.puts "Finished: #{i}"
end
@writer.close
end
end
@writer.close
# test whether we always get alternating "Started" / "Finished" lines
lines = []
@reader.each_line { |line| lines << line }
expect(lines).to be_truthy # it is empty if the processes all crashed due to a typo or similar
lines.each_slice(2) do |start, finish|
start_matchdata = /Started: (.*)/.match(start)
expect(start_matchdata).to be_truthy
finish_matchdata = /Finished: (.*)/.match(finish)
expect(finish_matchdata).to be_truthy
expect(finish_matchdata[1]).to eq(start_matchdata[1])
end
@reader.close
end
end
end
| 27.980769 | 100 | 0.613746 |
e2d2e99dda3711c9cfefd7ea2e28819d9350aca4 | 1,572 | require "rayyan-formats/version"
require "rayyan-formats-core"
require "rayyan-formats-plugins"
require "rayyan-scrapers"
require 'logger'
module RayyanFormats
class Command
def initialize(args)
# check arguments
raise "Must provide input file name(s) as the first arguments followed by the output file name\n" +
"USAGE: #{File.basename($0)} <input-file1> [<input-file2> [<input-file3> [...]]] <output-file>" \
if args.length < 2
@output_file = args.pop
@input_files = args
@ext = File.extname(@output_file).delete('.')
raise "Output file name must have an extension" if @ext.empty?
# configure RayyanFormats
logger = Logger.new(STDERR)
logger.level = Logger::WARN
Base.logger = logger
Base.plugins = Base.available_plugins
Base.max_file_size = 1_073_741_824 # 1GB
end
def run
begin
plugin = Base.get_export_plugin(@ext)
out, total, grand_total = File.open(@output_file, "w"), 0, 0
@input_files.each do |input_filename|
total = 0
Base.import(Source.new(input_filename)) { |target|
out.puts plugin.export(target, {include_abstracts: true})
total += 1
}
grand_total += total
$stdout.puts "Imported #{total} #{total == 1 ? 'entry' : 'entries'} from: #{input_filename}"
end
$stdout.puts "Exported #{grand_total} #{grand_total == 1 ? 'entry' : 'entries'} to: #{@output_file}"
ensure
out.close if out
end
end
end
end
| 32.081633 | 109 | 0.61514 |