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
031b29a6ebb542d81ac25f83186bc39e88c3e526
441
class Brand < ActiveRecord::Base has_and_belongs_to_many(:stores) validates :name, :presence => true, :length => {:minimum => 3, :maximum => 100}, :uniqueness => {:case_sensitive => false} validates_numericality_of :price, :presence=>true before_save(:uppercase_words) private def uppercase_words self.name=(self.name.split.map(&:capitalize).join(' ')) self.name=(name().capitalize()) end end
29.4
60
0.662132
186ee4b5c4687b0dcc73ba8e73173d579a24dab8
121
class CharacterSerializer < ActiveModel::Serializer attributes :id, :name def player object.player.id end end
15.125
51
0.743802
e9acb74f42fc50b85ddca23aaf075d5bd41e15de
676
require File.expand_path '../spec_helper.rb', __FILE__ require 'sidekiq/testing' describe DOIWorker do let(:entries) { BibTeX.open(fixture('paper.bib'), :filter => :latex) } before(:each) do Sidekiq::Worker.clear_all end subject do described_class.new end context "instance methods" do it "should know how to check DOIs" do expect(subject.check_dois(entries)).to eq( { :invalid =>["10.1038/INVALID is INVALID", "http://notadoi.org/bioinformatics/btp450 is INVALID because of 'https://doi.org/' prefix"], :missing=>[], :ok=>["10.1038/nmeth.3252 is OK"] } ) end end end
25.037037
146
0.616864
87c7339de2bb979ca139e14781758f0b7a5db935
1,461
class Cockatrice < Formula desc "Virtual tabletop for multiplayer card games" homepage "https://github.com/Cockatrice/Cockatrice" url "https://github.com/Cockatrice/Cockatrice.git", :tag => "2017-03-14-Release", :revision => "6e723b2a992022ba343d45d881b3c92b9d1c6ba2" version "2017-03-14" head "https://github.com/Cockatrice/Cockatrice.git" bottle do sha256 "75fa21c8c692249679a262dbd66f1e105b7182297e66f363e44968512fb0f0a0" => :sierra sha256 "fa97822a7217a4b995619cc4745a831e77a23b63987e85620addad1f05e2465a" => :el_capitan sha256 "c5497646ed72a5354a9219f846e6bca22fda579d1e665c8c02894e63804ae117" => :yosemite end option "with-server", "Build `servatrice` for running game servers" depends_on :macos => :mavericks depends_on "cmake" => :build depends_on "protobuf" if build.with? "server" depends_on "qt5" => "with-mysql" else depends_on "qt5" end fails_with :clang do build 503 cause "Undefined symbols for architecture x86_64: google::protobuf" end def install mkdir "build" do args = std_cmake_args args << "-DWITH_SERVER=ON" if build.with? "server" system "cmake", "..", *args system "make", "install" prefix.install Dir["release/*.app"] end doc.install Dir["doc/usermanual/*"] end test do (prefix/"cockatrice.app/Contents/MacOS/cockatrice").executable? (prefix/"oracle.app/Contents/MacOS/oracle").executable? end end
29.816327
92
0.713895
7a276faf370b85b0bb6cba95bbed15c74f92ac68
7,789
# encoding: utf-8 require 'bigdecimal' module Cql module Protocol class CqlByteBuffer < Ione::ByteBuffer def read_unsigned_byte read_byte rescue RangeError => e raise DecodingError, e.message, e.backtrace end def read_varint(len=bytesize, signed=true) bytes = read(len) n = 0 bytes.each_byte do |b| n = (n << 8) | b end if signed && bytes.getbyte(0) & 0x80 == 0x80 n -= 2**(bytes.length * 8) end n rescue RangeError => e raise DecodingError, e.message, e.backtrace end def read_decimal(len=bytesize) size = read_signed_int number_string = read_varint(len - 4).to_s if number_string.length < size if number_string.start_with?(MINUS) number_string = number_string[1, number_string.length - 1] fraction_string = MINUS + ZERO << DECIMAL_POINT else fraction_string = ZERO + DECIMAL_POINT end (size - number_string.length).times { fraction_string << ZERO } fraction_string << number_string else fraction_string = number_string[0, number_string.length - size] fraction_string << DECIMAL_POINT fraction_string << number_string[number_string.length - size, number_string.length] end BigDecimal.new(fraction_string) rescue DecodingError => e raise DecodingError, e.message, e.backtrace end def read_long top, bottom = read(8).unpack(Formats::TWO_INTS_FORMAT) return (top << 32) | bottom if top <= 0x7fffffff top ^= 0xffffffff bottom ^= 0xffffffff -((top << 32) | bottom) - 1 rescue RangeError => e raise DecodingError, e.message, e.backtrace end def read_double read(8).unpack(Formats::DOUBLE_FORMAT).first rescue RangeError => e raise DecodingError, "Not enough bytes available to decode a double: #{e.message}", e.backtrace end def read_float read(4).unpack(Formats::FLOAT_FORMAT).first rescue RangeError => e raise DecodingError, "Not enough bytes available to decode a float: #{e.message}", e.backtrace end def read_signed_int n = read_int return n if n <= 0x7fffffff n - 0xffffffff - 1 rescue RangeError => e raise DecodingError, "Not enough bytes available to decode an int: #{e.message}", e.backtrace end def read_unsigned_short read_short rescue RangeError => e raise DecodingError, "Not enough bytes available to decode a short: #{e.message}", e.backtrace end def read_string length = read_unsigned_short string = read(length) string.force_encoding(::Encoding::UTF_8) string rescue RangeError => e raise DecodingError, "Not enough bytes available to decode a string: #{e.message}", e.backtrace end def read_long_string length = read_signed_int string = read(length) string.force_encoding(::Encoding::UTF_8) string rescue RangeError => e raise DecodingError, "Not enough bytes available to decode a long string: #{e.message}", e.backtrace end def read_uuid(impl=Uuid) impl.new(read_varint(16, false)) rescue DecodingError => e raise DecodingError, "Not enough bytes available to decode a UUID: #{e.message}", e.backtrace end def read_string_list size = read_unsigned_short Array.new(size) { read_string } end def read_bytes size = read_signed_int return nil if size & 0x80000000 == 0x80000000 read(size) rescue RangeError => e raise DecodingError, "Not enough bytes available to decode a bytes: #{e.message}", e.backtrace end def read_short_bytes size = read_unsigned_short return nil if size & 0x8000 == 0x8000 read(size) rescue RangeError => e raise DecodingError, "Not enough bytes available to decode a short bytes: #{e.message}", e.backtrace end def read_option id = read_unsigned_short value = nil if block_given? value = yield id, self end [id, value] end def read_inet size = read_byte ip_addr = IPAddr.new_ntoh(read(size)) port = read_int [ip_addr, port] rescue RangeError => e raise DecodingError, "Not enough bytes available to decode an INET: #{e.message}", e.backtrace end def read_consistency index = read_unsigned_short raise DecodingError, "Unknown consistency index #{index}" if index >= CONSISTENCIES.size || CONSISTENCIES[index].nil? CONSISTENCIES[index] end def read_string_map map = {} map_size = read_unsigned_short map_size.times do key = read_string map[key] = read_string end map end def read_string_multimap map = {} map_size = read_unsigned_short map_size.times do key = read_string map[key] = read_string_list end map end def append_int(n) append([n].pack(Formats::INT_FORMAT)) end def append_short(n) append([n].pack(Formats::SHORT_FORMAT)) end def append_string(str) str = str.to_s append_short(str.bytesize) append(str) end def append_long_string(str) append_int(str.bytesize) append(str) end def append_uuid(uuid) v = uuid.value append_int((v >> 96) & 0xffffffff) append_int((v >> 64) & 0xffffffff) append_int((v >> 32) & 0xffffffff) append_int((v >> 0) & 0xffffffff) end def append_string_list(strs) append_short(strs.size) strs.each do |str| append_string(str) end self end def append_bytes(bytes) if bytes append_int(bytes.bytesize) append(bytes) else append_int(-1) end end def append_short_bytes(bytes) if bytes append_short(bytes.bytesize) append(bytes) else append_short(-1) end end def append_consistency(consistency) index = CONSISTENCIES.index(consistency) raise EncodingError, %(Unknown consistency "#{consistency}") if index.nil? || CONSISTENCIES[index].nil? append_short(index) end def append_string_map(map) append_short(map.size) map.each do |key, value| append_string(key) append_string(value) end self end def append_long(n) top = n >> 32 bottom = n & 0xffffffff append_int(top) append_int(bottom) end def append_varint(n) num = n bytes = [] until num == 0 bytes << (num & 0xff) num = num >> 8 break if num == -1 end append(bytes.reverse.pack(Formats::BYTES_FORMAT)) end def append_decimal(n) sign, number_string, _, size = n.split num = number_string.to_i raw = self.class.new.append_varint(sign * num) append_int(number_string.length - size) append(raw) end def append_double(n) append([n].pack(Formats::DOUBLE_FORMAT)) end def append_float(n) append([n].pack(Formats::FLOAT_FORMAT)) end private MINUS = '-'.freeze ZERO = '0'.freeze DECIMAL_POINT = '.'.freeze end end end
27.329825
125
0.586596
08abd7d8bfea74f408ee2e1995b3621229d3082a
65
require File.dirname(__FILE__) + "/app" run Sinatra::Application
21.666667
39
0.769231
ab47277fe0fcd5403561103b2e0d0deb099050d0
933
Pod::Spec.new do |s| s.name = 'qgnotification' s.version = '3.2.0' s.documentation_url = 'http://docs.qgraph.io' s.summary = 'This sdk creates Carousel/Slider, Image, Video, Audio and GIF push notifications.' s.homepage = 'https://github.com/quantumgraph/ios-notification-sdk' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'QUANTUMGRAPH' => '[email protected]' } s.source = { :git => 'https://github.com/quantumgraph/ios-notification-sdk.git', :tag => "v#{s.version}" } s.platform = :ios, '10.0' s.source_files = '*.{m,h}' s.requires_arc = true s.default_subspec = 'QGNotificationSdk' s.subspec 'QGNotificationSdk' do |ss| ss.source_files = '*.{h,m}' ss.vendored_library = 'libQGNotificationSdk.a' end end
31.1
100
0.54448
1af90b77df0aad4f6bf52e8d707db287e06fb848
1,651
module VCAP::CloudController module Jobs class AppApplyManifestActionJob < VCAP::CloudController::Jobs::CCJob def initialize(app_guid, apply_manifest_message, apply_manifest_action) @app_guid = app_guid @apply_manifest_message = apply_manifest_message @apply_manifest_action = apply_manifest_action end def perform logger = Steno.logger('cc.background') logger.info("Applying app manifest to app: #{resource_guid}") apply_manifest_action.apply(resource_guid, apply_manifest_message) rescue AppPatchEnvironmentVariables::InvalidApp, AppUpdate::InvalidApp, AppApplyManifest::NoDefaultDomain, ProcessScale::InvalidProcess, ProcessScale::SidecarMemoryLessThanProcessMemory, ProcessUpdate::InvalidProcess, SidecarCreate::InvalidSidecar, SidecarUpdate::InvalidSidecar, ManifestRouteUpdate::InvalidRoute, Route::InvalidOrganizationRelation, ServiceBindingCreate::InvalidServiceBinding => e error = CloudController::Errors::ApiError.new_from_details('UnprocessableEntity', e.message) error.set_backtrace(e.backtrace) raise error end def job_name_in_configuration :apply_manifest_job end def max_attempts 1 end def resource_type 'app' end def display_name 'app.apply_manifest' end def resource_guid @app_guid end private attr_reader :apply_manifest_action, :apply_manifest_message end end end
28.465517
100
0.666869
91c094ed39f3dec348c42657fefe34267351ad5b
19,268
require 'rndk' module RNDK # Allows user to select from a items of alphabetically sorted # words. # # Use the arrow keys to navigate on the items or type in the # beginning of the word and it'll automagically adjust # itself in the correct place. # # ## Keybindings # # Since Alphaitems is built from both the Scroll and Entry Widgets, # the key bindings are the same for the respective fields. # # Extra key bindings are itemsed below: # # Up Arrow:: Scrolls the scrolling items up one line. # Down Arrow:: Scrolls the scrolling items down one line. # Page Up:: Scrolls the scrolling items up one page. # CTRL-B:: Scrolls the scrolling items up one page. # Page Down:: Scrolls the scrolling items down one page. # CTRL-F:: Scrolls the scrolling items down one page. # Tab:: Tries to complete the word in the entry field. # If the word segment is not unique then the widget # will beep and present a items of close matches. # Return:: Returns the word in the entry field. # It also sets the widget data exitType to `:NORMAL`. # Escape:: Exits the widget and returns `nil`. # It also sets the widget data exitType to `:ESCAPE_HIT`. # # ## Developer notes # # This widget, like the file selector widget, is a compound widget # of both the entry field widget and the scrolling items widget - sorted. # # @todo Kinda buggy, fix first words, mate # class Alphalist < Widget attr_reader :scroll_field, :entry_field, :items # Creates an Alphalist Widget. # # ## Settings # # * `x` is the x position - can be an integer or `RNDK::LEFT`, # `RNDK::RIGHT`, `RNDK::CENTER`. # * `y` is the y position - can be an integer or `RNDK::TOP`, # `RNDK::BOTTOM`, `RNDK::CENTER`. # * `width`/`height` are integers - if either are 0, Widget # will be created with full width/height of the screen. # If it's a negative value, will create with full width/height # minus the value. # * `title` can be more than one line - just split them # with `\n`s. # * `label` is the String that will appear on the label # of the Entry field. # * `items` is an Array of Strings with the content to # display. # * `filler_char` is the character to display on the # empty spaces in the Entry field. # * `highlight` is the attribute/color of the current # item. # * `box` if the Widget is drawn with a box outside it. # * `shadow` turns on/off the shadow around the Widget. # def initialize(screen, config={}) super() @widget_type = :alphaitems @supported_signals += [:before_input, :after_input] # This is UGLY AS HELL # But I don't have time to clean this up right now # (lots of widgets, you know) :( x = 0 y = 0 width = 0 height = 0 title = "alphaitems" label = "label" items = [] filler_char = '.' highlight = RNDK::Color[:reverse] box = true shadow = false config.each do |key, val| x = val if key == :x y = val if key == :y width = val if key == :width height = val if key == :height title = val if key == :title label = val if key == :label items = val if key == :items filler_char = val if key == :filler_char highlight = val if key == :highlight box = val if key == :box shadow = val if key == :shadow end parent_width = Ncurses.getmaxx screen.window parent_height = Ncurses.getmaxy screen.window box_width = width box_height = height label_len = 0 if not self.create_items items self.destroy return nil end self.set_box box # If the height is a negative value, the height will be ROWS-height, # otherwise the height will be the given height. box_height = RNDK.set_widget_dimension(parent_height, height, 0) # If the width is a negative value, the width will be COLS-width, # otherwise the width will be the given width. box_width = RNDK.set_widget_dimension(parent_width, width, 0) # Translate the label string to a chtype array if label.size > 0 lentmp = [] chtype_label = RNDK.char2Chtype(label, lentmp, []) label_len = lentmp[0] end # Rejustify the x and y positions if we need to. xtmp = [x] ytmp = [y] RNDK.alignxy(screen.window, xtmp, ytmp, box_width, box_height) xpos = xtmp[0] ypos = ytmp[0] # Make the file selector window. @win = Ncurses.newwin(box_height, box_width, ypos, xpos) if @win.nil? self.destroy return nil end Ncurses.keypad(@win, true) @screen = screen @parent = screen.window @highlight = highlight @filler_char = filler_char @box_width = box_width @box_height = box_height @shadow = shadow @shadow_win = nil # Do we want a shadow? if shadow @shadow_win = Ncurses.newwin(box_height, box_width, ypos+1, xpos+1) end # Create the entry field. temp_width = if Alphalist.isFullWidth(width) then RNDK::FULL else box_width - 2 - label_len end @entry_field = RNDK::Entry.new(screen, { :x => Ncurses.getbegx(@win), :y => Ncurses.getbegy(@win), :title => title, :label => label, :filler => filler_char, :field_width => temp_width, :box => box }) if @entry_field.nil? self.destroy return nil end @entry_field.setLLchar Ncurses::ACS_LTEE @entry_field.setLRchar Ncurses::ACS_RTEE # Set the key bindings for the entry field. @entry_field.bind_key(Ncurses::KEY_UP) { self.autocomplete } @entry_field.bind_key(RNDK::KEY_TAB) { self.autocomplete } @entry_field.bind_key(Ncurses::KEY_DOWN) { self.adjust_items } @entry_field.bind_key(Ncurses::KEY_NPAGE) { self.adjust_items } @entry_field.bind_key(Ncurses::KEY_PPAGE) { self.adjust_items } @entry_field.bind_signal(:before_input) { |char| self.pre_process_entry_field(char) } # Create the scrolling items. It overlaps the entry field by one line if # we are using box-borders. temp_height = Ncurses.getmaxy(@entry_field.win) - @border_size temp_width = if Alphalist.isFullWidth(width) then RNDK::FULL else box_width - 1 end @scroll_field = RNDK::Scroll.new(screen, { :x => Ncurses.getbegx(@win), :y => Ncurses.getbegy(@entry_field.win) + temp_height, :width => temp_width, :height => box_height - temp_height, :title => '', :items => items, :box => box }) @scroll_field.setULchar Ncurses::ACS_LTEE @scroll_field.setURchar Ncurses::ACS_RTEE screen.register(:alphaitems, self) end # @see Widget#erase def erase if self.valid? @scroll_field.erase @entry_field.erase RNDK.window_erase(@shadow_win) RNDK.window_erase(@win) end end # @see Widget#move def move(x, y, relative, refresh_flag) windows = [@win, @shadow_win] subwidgets = [@entry_field, @scroll_field] self.move_specific(x, y, relative, refresh_flag, windows, subwidgets) end # The alphaitems's focus resides in the entry widget. But the scroll widget # will not draw items highlighted unless it has focus. Temporarily adjust # the focus of the scroll widget when drawing on it to get the right # highlighting. def saveFocus @save = @scroll_field.has_focus @scroll_field.has_focus = @entry_field.has_focus end def restoreFocus @scroll_field.has_focus = @save end def draw_scroller self.saveFocus @scroll_field.draw self.restoreFocus end def injectMyScroller(key) self.saveFocus @scroll_field.inject(key) self.restoreFocus end # Draws the Widget on the Screen. # # If `box` is true, it is drawn with a box. def draw Draw.drawShadow @shadow_win unless @shadow_win.nil? # Draw in the entry field. @entry_field.draw @entry_field.box # Draw in the scroll field. self.draw_scroller end # Activates the Alphalist Widget, letting the user interact with it. # # `actions` is an Array of characters. If it's non-null, # will #inject each char on it into the Widget. # # See Alphalist for keybindings. # # @return The text currently inside the entry field (and # `exit_type` will be `:NORMAL`) or `nil` (and # `exit_type` will be `:ESCAPE_HIT`). def activate(actions=[]) ret = 0 # Draw the widget. self.draw # Activate the widget. ret = @entry_field.activate actions # Copy the exit type from the entry field. @exit_type = @entry_field.exit_type # Determine the exit status. if @exit_type != :EARLY_EXIT return ret end return 0 end # Makes the Alphalist react to `char` just as if the user # had pressed it. # # Nice to simulate batch actions on a Widget. # # Besides normal keybindings (arrow keys and such), see # Widget#set_exit_type to see how the Widget exits. # def inject input ret = false self.draw # Inject a character into the widget. ret = @entry_field.inject input # Copy the eixt type from the entry field. @exit_type = @entry_field.exit_type # Determine the exit status. ret = false if @exit_type == :EARLY_EXIT @result_data = ret ret end # Sets multiple attributes of the Widget. # # See Alphalist#initialize. def set(items, filler_char, highlight, box) self.set_contents items self.set_filler_char filler_char self.set_highlight highlight self.set_box box end # This function sets the textrmation inside the alphaitems. def set_contents items return if not self.create_items items # Set the textrmation in the scrolling items. @scroll_field.set(@items, @items_size, false, @scroll_field.highlight, @scroll_field.box) # Clean out the entry field. self.set_current_item(0) @entry_field.clean # Redraw the widget. self.erase self.draw end # This returns the contents of the widget. def getContents size size << @items_size return @items end # Get/set the current position in the scroll widget. def get_current_item return @scroll_field.get_current_item end def set_current_item item if @items_size != 0 @scroll_field.set_current_item item @entry_field.setValue @items[@scroll_field.get_current_item] end end # This sets the filler character of the entry field of the alphaitems. def set_filler_char char @filler_char = char @entry_field.set_filler_char char end def get_filler_char return @filler_char end # This sets the highlgith bar attributes def set_highlight(highlight) @highlight = highlight end def getHighlight @highlight end # These functions set the drawing characters of the widget. def setMyULchar(character) @entry_field.setULchar(character) end def setMyURchar(character) @entry_field.setURchar(character) end def setMyLLchar(character) @scroll_field.setLLchar(character) end def setMyLRchar(character) @scroll_field.setLRchar(character) end def setMyVTchar(character) @entry_field.setVTchar(character) @scroll_field.setVTchar(character) end def setMyHZchar(character) @entry_field.setHZchar(character) @scroll_field.setHZchar(character) end def setMyBXattr(character) @entry_field.setBXattr(character) @scroll_field.setBXattr(character) end # This sets the background attribute of the widget. def set_bg_color(attrib) @entry_field.set_bg_color(attrib) @scroll_field.set_bg_color(attrib) end def destroyText @items = '' @items_size = 0 end # This destroys the alpha items def destroy self.destroyText # Clean the key bindings. self.clean_bindings @entry_field.destroy @scroll_field.destroy # Free up the window pointers. RNDK.window_delete(@shadow_win) RNDK.window_delete(@win) # Unregister the widget. @screen.unregister self end # @see Widget#bind_signal def bind_signal(signal, &action) @entry_field.bind_signal(signal, action) end def create_items items if items.size >= 0 newitems = [] # Copy in the new textrmation. status = true (0...items.size).each do |x| newitems << items[x] if newitems[x] == 0 status = false break end end if status self.destroyText @items_size = items.size @items = newitems @items.sort! end else self.destroyText status = true end status end def focus self.entry_field.focus end def unfocus self.entry_field.unfocus end def self.isFullWidth(width) width == RNDK::FULL || (Ncurses.COLS != 0 && width >= Ncurses.COLS) end def position super(@win) end protected def autocomplete scrollp = self.scroll_field entry = self.entry_field if scrollp.items_size > 0 # Adjust the scrolling items. self.injectMyScroller Ncurses::KEY_UP # Set the value in the entry field. current = RNDK.chtype2Char scrollp.item[scrollp.current_item] entry.setValue current entry.draw entry.box return true end RNDK.beep false end def adjust_items entry = self.entry_field scrollp = nil selected = -1 ret = 0 alt_words = [] if entry.text.size == 0 RNDK.beep return true end # Look for a unique word match. index = RNDK.search_list(self.items, self.items.size, entry.text) # if the index is less than zero, return we didn't find a match if index < 0 RNDK.beep return true end # Did we find the last word in the items? if index == self.items.size - 1 entry.setValue self.items[index] entry.draw entry.box return true end # Ok, we found a match, is the next item similar? len = [entry.text.size, self.items[index + 1].size].min ret = self.items[index + 1][0...len] <=> entry.text if ret == 0 current_index = index match = 0 selected = -1 # Start looking for alternate words # FIXME(original): bsearch would be more suitable. while (current_index < self.items.size) and ((self.items[current_index][0...len] <=> entry.text) == 0) alt_words << self.items[current_index] current_index += 1 end # Determine the height of the scrolling items. height = if alt_words.size < 8 then alt_words.size + 3 else 11 end # Create a scrolling items of close matches. scrollp = RNDK::Scroll.new(entry.screen, { :x => RNDK::CENTER, :y => RNDK::CENTER, :width => -30, :height => height, :title => "<C></B/5>Possible Matches.", :items => alt_words, :numbers => true }) # Allow them to select a close match. match = scrollp.activate selected = scrollp.current_item # Check how they exited the items. if scrollp.exit_type == :ESCAPE_HIT # Destroy the scrolling items. scrollp.destroy RNDK.beep # Redraw the self and return. self.draw(self.box) return true end # Destroy the scrolling items. scrollp.destroy # Set the entry field to the selected value. entry.set(alt_words[match], entry.min, entry.max, entry.box) # Move the highlight bar down to the selected value. (0...selected).each do |x| self.injectMyScroller(Ncurses::KEY_DOWN) end # Redraw the self. self.draw self.box else # Set the entry field with the found item. entry.set(self.items[index], entry.min, entry.max, entry.box) entry.draw entry.box end true end def pre_process_entry_field(input) scrollp = self.scroll_field entry = self.entry_field text_len = entry.text.size result = 1 empty = false if self.is_bound? input result = 1 # Don't try to use this key in editing elsif (RNDK.is_char?(input) && input.chr.match(/^[[:alnum:][:punct:]]$/)) || [Ncurses::KEY_BACKSPACE, Ncurses::KEY_DC].include?(input) index = 0 curr_pos = entry.screen_col + entry.left_char pattern = entry.text.clone if [Ncurses::KEY_BACKSPACE, Ncurses::KEY_DC].include? input curr_pos -= 1 if input == Ncurses::KEY_BACKSPACE pattern.slice!(curr_pos) if curr_pos >= 0 else front = (pattern[0...curr_pos] or '') back = (pattern[curr_pos..-1] or '') pattern = front + input.chr + back end if pattern.size == 0 empty = true elsif (index = RNDK.search_list(self.items, self.items.size, pattern)) >= 0 # XXX: original uses n scroll downs/ups for <10 positions change scrollp.set_position(index) self.draw_scroller else RNDK.beep result = 0 end end if empty scrollp.set_position(0) self.draw_scroller end result end end end
28.460857
95
0.575981
e97e74c1515e5fe8db73b23de73c5dc1bbdb4e11
11,289
# frozen_string_literal: true require 'spec_helper' RSpec.describe Ci::CreatePipelineService do let(:project) { create(:project, :repository) } let(:user) { project.owner } let(:ref) { 'refs/heads/master' } let(:source) { :push } let(:service) { described_class.new(project, user, { ref: ref }) } let(:pipeline) { service.execute(source) } let(:build_names) { pipeline.builds.pluck(:name) } context 'job:rules' do before do stub_ci_pipeline_yaml_file(config) allow_next_instance_of(Ci::BuildScheduleWorker) do |instance| allow(instance).to receive(:perform).and_return(true) end end context 'exists:' do let(:config) do <<-EOY regular-job: script: 'echo Hello, World!' rules-job: script: "echo hello world, $CI_COMMIT_REF_NAME" rules: - exists: - README.md when: manual - exists: - app.rb when: on_success delayed-job: script: "echo See you later, World!" rules: - exists: - README.md when: delayed start_in: 4 hours EOY end let(:regular_job) { pipeline.builds.find_by(name: 'regular-job') } let(:rules_job) { pipeline.builds.find_by(name: 'rules-job') } let(:delayed_job) { pipeline.builds.find_by(name: 'delayed-job') } context 'with matches' do let(:project) { create(:project, :custom_repo, files: { 'README.md' => '' }) } it 'creates two jobs' do expect(pipeline).to be_persisted expect(build_names).to contain_exactly('regular-job', 'rules-job', 'delayed-job') end it 'sets when: for all jobs' do expect(regular_job.when).to eq('on_success') expect(rules_job.when).to eq('manual') expect(delayed_job.when).to eq('delayed') expect(delayed_job.options[:start_in]).to eq('4 hours') end end context 'with matches on the second rule' do let(:project) { create(:project, :custom_repo, files: { 'app.rb' => '' }) } it 'includes both jobs' do expect(pipeline).to be_persisted expect(build_names).to contain_exactly('regular-job', 'rules-job') end it 'sets when: for the created rules job based on the second clause' do expect(regular_job.when).to eq('on_success') expect(rules_job.when).to eq('on_success') end end context 'without matches' do let(:project) { create(:project, :custom_repo, files: { 'useless_script.rb' => '' }) } it 'only persists the job without rules' do expect(pipeline).to be_persisted expect(regular_job).to be_persisted expect(rules_job).to be_nil expect(delayed_job).to be_nil end it 'sets when: for the created job' do expect(regular_job.when).to eq('on_success') end end end context 'with allow_failure and exit_codes', :aggregate_failures do def find_job(name) pipeline.builds.find_by(name: name) end let(:config) do <<-EOY job-1: script: exit 42 allow_failure: exit_codes: 42 rules: - if: $CI_COMMIT_REF_NAME == "master" allow_failure: false job-2: script: exit 42 allow_failure: exit_codes: 42 rules: - if: $CI_COMMIT_REF_NAME == "master" allow_failure: true job-3: script: exit 42 allow_failure: exit_codes: 42 rules: - if: $CI_COMMIT_REF_NAME == "master" when: manual EOY end it 'creates a pipeline' do expect(pipeline).to be_persisted expect(build_names).to contain_exactly( 'job-1', 'job-2', 'job-3' ) end it 'assigns job:allow_failure values to the builds' do expect(find_job('job-1').allow_failure).to eq(false) expect(find_job('job-2').allow_failure).to eq(true) expect(find_job('job-3').allow_failure).to eq(false) end it 'removes exit_codes if allow_failure is specified' do expect(find_job('job-1').options.dig(:allow_failure_criteria)).to be_nil expect(find_job('job-2').options.dig(:allow_failure_criteria)).to be_nil expect(find_job('job-3').options.dig(:allow_failure_criteria, :exit_codes)).to eq([42]) end end context 'if:' do context 'variables:' do let(:config) do <<-EOY job: script: "echo job1" variables: VAR1: my var 1 VAR2: my var 2 rules: - if: $CI_COMMIT_REF_NAME =~ /master/ variables: VAR1: overridden var 1 - if: $CI_COMMIT_REF_NAME =~ /feature/ variables: VAR2: overridden var 2 VAR3: new var 3 - when: on_success EOY end let(:job) { pipeline.builds.find_by(name: 'job') } context 'when matching to the first rule' do let(:ref) { 'refs/heads/master' } it 'overrides VAR1' do variables = job.scoped_variables.to_hash expect(variables['VAR1']).to eq('overridden var 1') expect(variables['VAR2']).to eq('my var 2') expect(variables['VAR3']).to be_nil end end context 'when matching to the second rule' do let(:ref) { 'refs/heads/feature' } it 'overrides VAR2 and adds VAR3' do variables = job.scoped_variables.to_hash expect(variables['VAR1']).to eq('my var 1') expect(variables['VAR2']).to eq('overridden var 2') expect(variables['VAR3']).to eq('new var 3') end end context 'when no match' do let(:ref) { 'refs/heads/wip' } it 'does not affect vars' do variables = job.scoped_variables.to_hash expect(variables['VAR1']).to eq('my var 1') expect(variables['VAR2']).to eq('my var 2') expect(variables['VAR3']).to be_nil end end end end end context 'when workflow:rules are used' do before do stub_ci_pipeline_yaml_file(config) end context 'with a single regex-matching if: clause' do let(:config) do <<-EOY workflow: rules: - if: $CI_COMMIT_REF_NAME =~ /master/ - if: $CI_COMMIT_REF_NAME =~ /wip$/ when: never - if: $CI_COMMIT_REF_NAME =~ /feature/ regular-job: script: 'echo Hello, World!' EOY end context 'matching the first rule in the list' do it 'saves a pending pipeline' do expect(pipeline).to be_pending expect(pipeline).to be_persisted end end context 'matching the last rule in the list' do let(:ref) { 'refs/heads/feature' } it 'saves a pending pipeline' do expect(pipeline).to be_pending expect(pipeline).to be_persisted end end context 'matching the when:never rule' do let(:ref) { 'refs/heads/wip' } it 'invalidates the pipeline with a workflow rules error' do expect(pipeline.errors[:base]).to include('Pipeline filtered out by workflow rules.') expect(pipeline).not_to be_persisted end end context 'matching no rules in the list' do let(:ref) { 'refs/heads/fix' } it 'invalidates the pipeline with a workflow rules error' do expect(pipeline.errors[:base]).to include('Pipeline filtered out by workflow rules.') expect(pipeline).not_to be_persisted end end end context 'when root variables are used' do let(:config) do <<-EOY variables: VARIABLE: value workflow: rules: - if: $VARIABLE regular-job: script: 'echo Hello, World!' EOY end context 'matching the first rule in the list' do it 'saves a pending pipeline' do expect(pipeline).to be_pending expect(pipeline).to be_persisted end end end context 'with a multiple regex-matching if: clause' do let(:config) do <<-EOY workflow: rules: - if: $CI_COMMIT_REF_NAME =~ /master/ - if: $CI_COMMIT_REF_NAME =~ /^feature/ && $CI_COMMIT_REF_NAME =~ /conflict$/ when: never - if: $CI_COMMIT_REF_NAME =~ /feature/ regular-job: script: 'echo Hello, World!' EOY end context 'with partial match' do let(:ref) { 'refs/heads/feature' } it 'saves a pending pipeline' do expect(pipeline).to be_pending expect(pipeline).to be_persisted end end context 'with complete match' do let(:ref) { 'refs/heads/feature_conflict' } it 'invalidates the pipeline with a workflow rules error' do expect(pipeline.errors[:base]).to include('Pipeline filtered out by workflow rules.') expect(pipeline).not_to be_persisted end end end context 'with job rules' do let(:config) do <<-EOY workflow: rules: - if: $CI_COMMIT_REF_NAME =~ /master/ - if: $CI_COMMIT_REF_NAME =~ /feature/ regular-job: script: 'echo Hello, World!' rules: - if: $CI_COMMIT_REF_NAME =~ /wip/ - if: $CI_COMMIT_REF_NAME =~ /feature/ EOY end context 'where workflow passes and the job fails' do let(:ref) { 'refs/heads/master' } it 'invalidates the pipeline with an empty jobs error' do expect(pipeline.errors[:base]).to include('No stages / jobs for this pipeline.') expect(pipeline).not_to be_persisted end end context 'where workflow passes and the job passes' do let(:ref) { 'refs/heads/feature' } it 'saves a pending pipeline' do expect(pipeline).to be_pending expect(pipeline).to be_persisted end end context 'where workflow fails and the job fails' do let(:ref) { 'refs/heads/fix' } it 'invalidates the pipeline with a workflow rules error' do expect(pipeline.errors[:base]).to include('Pipeline filtered out by workflow rules.') expect(pipeline).not_to be_persisted end end context 'where workflow fails and the job passes' do let(:ref) { 'refs/heads/wip' } it 'invalidates the pipeline with a workflow rules error' do expect(pipeline.errors[:base]).to include('Pipeline filtered out by workflow rules.') expect(pipeline).not_to be_persisted end end end end end
29.865079
95
0.558065
6abd6bd34dba4174f762bf78569e1a6e2ecf8341
19,727
# # Copyright (c) 2009-2011 RightScale Inc # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. require 'set' module RightScale class LoginManager class SystemConflict < SecurityError; end include RightSupport::Ruby::EasySingleton attr_accessor :login_policy_tag_set RIGHTSCALE_KEYS_FILE = '/home/rightscale/.ssh/authorized_keys' RESTRICTED_TAG = 'rs_login:state=restricted' COMMENT = /^\s*#/ SSH_DEFAULT_KEYS = [ File.join(RightScale::Platform.filesystem.ssh_cfg_dir, 'ssh_host_rsa_key'), File.join(RightScale::Platform.filesystem.ssh_cfg_dir, 'ssh_host_dsa_key'), File.join(RightScale::Platform.filesystem.ssh_cfg_dir, 'ssh_host_ecdsa_key') ] def initialize @login_policy_tag_set = false require 'etc' end # Can the login manager function on this platform? # # == Returns: # @return [TrueClass] if LoginManager works on this platform # @return [FalseClass] if LoginManager does not work on this platform # def supported_by_platform? right_platform = RightScale::Platform.linux? # avoid calling user_exists? on unsupported platform(s) right_platform && LoginUserManager.user_exists?('rightscale') && FeatureConfigManager.feature_enabled?('managed_login_enable') end # Enact the login policy specified in new_policy for this system. The policy becomes # effective immediately and controls which public keys are trusted for SSH access to # the superuser account. # # == Parameters: # @param [RightScale::LoginPolicy] New login policy # @param [String] Serialized instance agent identity # # == Yields: # @yield [String] audit content yielded to the block provided # # == Returns: # @return [TrueClass] if supported by given platform # @return [FalseClass] if not supported by given platform # def update_policy(new_policy, agent_identity) return false unless supported_by_platform? update_users(new_policy.users, agent_identity, new_policy) do |audit_content| yield audit_content if block_given? end true end # Returns prefix command for public key record # # == Parameters: # @param [String] account's username # @param [String] account's email address # @param [String] account's uuid # @param [Boolean] designates whether the account has superuser privileges # @param [String] optional profile_data to be included # # == Returns: # @return [String] command string # def get_key_prefix(username, email, uuid, superuser, profile_data = nil) if profile_data profile = " --profile #{Shellwords.escape(profile_data).gsub('"', '\\"')}" else profile = "" end superuser = superuser ? " --superuser" : "" %Q{command="rs_thunk --username #{username} --uuid #{uuid}#{superuser} --email #{email}#{profile}" } end # Returns current SSH host keys # # == Returns: # @return [Array<String>] Base64 encoded SSH public keys def get_ssh_host_keys() # Try to read the sshd_config file first keys = File.readlines( File.join(RightScale::Platform.filesystem.ssh_cfg_dir, 'sshd_config')).map do |l| key = nil /^\s*HostKey\s+([^ ].*)/.match(l) { |m| key = m.captures[0] } key end.compact # If the config file was empty, try these defaults keys = keys.empty? ? SSH_DEFAULT_KEYS : keys # Assume the public keys are just the public keys with '.pub' extended and # read in each existing key. keys.map { |k| k="#{k}.pub"; File.exists?(k) ? File.read(k) : nil }.compact end protected # For any user with a public key fingerprint but no public key, obtain the public key # from the old policy or by querying RightScale using the fingerprints # Remove a user if no public keys are available for it # # == Parameters: # @param [Array<LoginUsers>] Login users whose public keys are to be populated # @param [String] Serialized instance agent identity # @param [RightScale::LoginPolicy] New login policy # # == Yields: # @yield [String] audit content yielded to the block provided # # == Returns: # @return [TrueClass] always returns true # def update_users(users, agent_identity, new_policy) # Create cache of public keys from stored instance state # but there won't be any on initial launch public_keys_cache = {} if old_policy = InstanceState.login_policy public_keys_cache = old_policy.users.inject({}) do |keys, user| user.public_key_fingerprints ||= user.public_keys.map { |key| fingerprint(key, user.username) } user.public_keys.zip(user.public_key_fingerprints).each { |(k, f)| keys[f] = k if f } keys end end # See if there are any missing keys and if so, send a request to retrieve them # Then make one more pass to populate any missing keys and reject any that are still not populated unless (missing = populate_public_keys(users, public_keys_cache)).empty? payload = {:agent_identity => agent_identity, :public_key_fingerprints => missing.map { |(u, f)| f }} request = RightScale::RetryableRequest.new("/key_server/retrieve_public_keys", payload) request.callback do |public_keys| if public_keys missing = populate_public_keys(users, public_keys, remove_if_missing = true) finalize_policy(new_policy, agent_identity, users, missing.map { |(u, f)| u }.uniq) do |audit_content| yield audit_content end end end request.errback do |error| Log.error("Failed to retrieve public keys for users #{missing.map { |(u, f)| u.username }.uniq.inspect} (#{error})") missing = populate_public_keys(users, {}, remove_if_missing = true) finalize_policy(new_policy, agent_identity, users, missing.map { |(u, f)| u }.uniq) do |audit_content| yield audit_content end end request.run else finalize_policy(new_policy, agent_identity, users, missing.map { |(u, f)| u }.uniq) do |audit_content| yield audit_content end end true end # Manipulates the authorized_keys file to match the given login policy # Schedules expiration of users from policy and audits the policy in # a human-readable format # # == Parameters: # @param [RightScale::LoginPolicy] New login policy # @param [String] Serialized instance agent identity # @param [Array<LoginUsers>] Array of updated users # @param [Array<LoginUsers>] Array of users with public keys missing # # == Yields: # @yield [String] audit content yielded to the block provided # # == Returns: # @return [TrueClass] always returns true # def finalize_policy(new_policy, agent_identity, new_policy_users, missing) manage_existing_users(new_policy_users) user_lines = login_users_to_authorized_keys(new_policy_users) InstanceState.login_policy = new_policy write_keys_file(user_lines, RIGHTSCALE_KEYS_FILE, { :user => 'rightscale', :group => 'rightscale' }) unless @login_policy_tag_set tags = [RESTRICTED_TAG] AgentTagManager.instance.add_tags(tags) @login_policy_tag_set = true end # Schedule a timer to handle any expiration that is planned to happen in the future schedule_expiry(new_policy, agent_identity) # Yield a human-readable description of the policy, e.g. for an audit entry yield describe_policy(new_policy_users, new_policy_users.select { |u| u.superuser }, missing) true end # Populate missing public keys from old public keys using associated fingerprints # Also populate any missing fingerprints where possible # # == Parameters: # @param [Array<LoginUser>] Login users whose public keys are to be updated if nil # @param [Hash<String, String>] Public keys with fingerprint as key and public key as value # @param [Boolean] Whether to remove a user's public key if it cannot be obtained # and the user itself if none of its public keys can be obtained # # == Returns: # @return [Array<LoginUser,String] User and fingerprint for each missing public key # def populate_public_keys(users, public_keys_cache, remove_if_missing = false) missing = [] users.reject! do |user| reject = false # Create any missing fingerprints from the public keys so that fingerprints # are as populated as possible user.public_key_fingerprints ||= user.public_keys.map { |key| fingerprint(key, user.username) } user.public_key_fingerprints = user.public_keys.zip(user.public_key_fingerprints).map do |(k, f)| f || fingerprint(k, user.username) end # Where possible use cache of old public keys to populate any missing ones public_keys = user.public_keys.zip(user.public_key_fingerprints).inject([]) do |keys, (k, f)| if f if k ||= public_keys_cache[f] keys << k else if remove_if_missing Log.error("Failed to obtain public key with fingerprint #{f.inspect} for user #{user.username}, " + "removing it from login policy") else keys << k end missing << [user, f] end else Log.error("Failed to obtain public key with fingerprint #{f.inspect} for user #{user.username}, " + "removing it from login policy") end keys end # Reject user if none of its public keys could be populated # This will not happen unless remove_if_missing is true if public_keys.empty? reject = true else user.public_keys = public_keys end reject end missing end # Create fingerprint for public key # # == Parameters: # @param [String] RSA public key # @param [String] Name of user owning this key # # == Return: # @return [String] Fingerprint for key if it could create it # @return [NilClass] if it could not create it # def fingerprint(public_key, username) LoginUser.fingerprint(public_key) if public_key rescue Exception => e Log.error("Failed to create public key fingerprint for user #{username}", e) nil end # Returns array of public keys of specified authorized_keys file # # == Parameters: # @param [String] path to authorized_keys file # # == Returns: # # @return [Array<Array(String, String, String)>] array of authorized_key parameters: algorith, public key, comment # def load_keys(path) file_lines = read_keys_file(path) keys = [] file_lines.map do |l| components = LoginPolicy.parse_public_key(l) if components #preserve algorithm, key and comments; discard options (the 0th element) keys << [ components[1], components[2], components[3] ] elsif l =~ COMMENT next else RightScale::Log.error("Malformed (or not SSH2) entry in authorized_keys file: #{l}") next end end keys end # Return a verbose, human-readable description of the login policy, suitable # for appending to an audit entry. Contains formatting such as newlines and tabs. # # == Parameters: # @param [Array<LoginUser>] All LoginUsers # @param [Array<LoginUser>] Subset of LoginUsers who are authorized to act as superusers # @param [LoginPolicy] Effective login policy # @param [Array<LoginUser>] Users for which a public key could not be obtained # # == Returns: # @return [String] description # def describe_policy(users, superusers, missing = []) normal_users = users - superusers audit = "#{users.size} authorized users (#{normal_users.size} normal, #{superusers.size} superuser).\n" audit << "Public key missing for #{missing.map { |u| u.username }.join(", ") }.\n" if missing.size > 0 #unless normal_users.empty? # audit += "\nNormal users:\n" # normal_users.each do |u| # audit += " #{u.common_name.ljust(40)} #{u.username}\n" # end #end # #unless superusers.empty? # audit += "\nSuperusers:\n" # superusers.each do |u| # audit += " #{u.common_name.ljust(40)} #{u.username}\n" # end #end return audit end # Given a LoginPolicy, add an EventMachine timer to handle the # expiration of LoginUsers whose expiry time occurs in the future. # This ensures that their login privilege expires on time and in accordance # with the policy (so long as the agent is running). Expiry is handled by # taking the policy exactly as it was received and passing it to #update_policy, # which already knows how to filter out users who are expired at the time the policy # is applied. # # == Parameters: # @param [LoginPolicy] Policy for which expiry is to be scheduled # @param [String] Serialized instance agent identity # # == Returns: # @return [TrueClass] if expiry was scheduled # @return [FalseClass] if expiry was not scheduled # def schedule_expiry(policy, agent_identity) if @expiry_timer @expiry_timer.cancel @expiry_timer = nil end # Find the next expiry time that is in the future now = Time.now next_expiry = policy.users.map { |u| u.expires_at }.compact.select { |t| t > now }.min return false unless next_expiry delay = next_expiry.to_i - Time.now.to_i + 1 #Clip timer to one day (86,400 sec) to work around EM timer bug involving #32-bit integer. This works because update_policy is idempotent and can #be safely called at any time. It will "reconverge" if it is called when #no permissions have changed. delay = [delay, 86_400].min return false unless delay > 0 @expiry_timer = EM::Timer.new(delay) do update_policy(policy, agent_identity) end return true end # Given a list of LoginUsers, compute an authorized_keys file that encompasses all # of the users and has a suitable options field that invokes rs_thunk with the right # command-line params for that user. Omit any users who are expired. # # == Parameters: # @param [Array<LoginUser>] array of updated users list # # == Returns: # @return [Array<String>] public key lines of user accounts # def login_users_to_authorized_keys(new_users) now = Time.now user_lines = [] new_users.each do |u| if u.expires_at.nil? || u.expires_at > now u.public_keys.each do |k| user_lines << "#{get_key_prefix(u.username, u.common_name, u.uuid, u.superuser, u.profile_data)} #{k}" end end end return user_lines.sort end # Schedules expiration of new users from policy and existing ones # # @param [Array<LoginUsers>] Array of updated users # # == Returns: # @return [TrueClass] always returns true def manage_existing_users(new_policy_users) now = Time.now previous = {} if InstanceState.login_policy InstanceState.login_policy.users.each do |user| previous[user.uuid] = user end end current = {} new_policy_users.each do |user| current[user.uuid] = user end added = current.keys - previous.keys removed = previous.keys - current.keys stayed = current.keys & previous.keys removed.each do |k| begin user = current[k] || previous[k] LoginUserManager.manage_user(user.uuid, user.superuser, :disable => true) rescue Exception => e RightScale::Log.error("Failed to disable user '#{user.uuid}'", e) unless e.is_a?(ArgumentError) end end (added + stayed).each do |k| begin user = current[k] || previous[k] disable = !!(user.expires_at) && (now >= user.expires_at) LoginUserManager.manage_user(user.uuid, user.superuser, :disable => disable) rescue Exception => e RightScale::Log.error("Failed to manage existing user '#{user.uuid}'", e) unless e.is_a?(ArgumentError) end end rescue Exception => e RightScale::Log.error("Failed to manage existing users", e) end # === OS specific methods # Reads specified keys file if it exists # # == Parameters # @param [String] path to authorized_keys file # # == Return # @return [Array<String>] list of lines of authorized_keys file # def read_keys_file(path) return [] unless File.exists?(path) File.readlines(path).map! { |l| l.chomp.strip } end # Replace the contents of specified keys file # # == Parameters: # @param [Array<String>] list of lines that authorized_keys file should contain # @param [String] path to authorized_keys file # @param [Hash] additional parameters for user/group # # == Returns: # @return [TrueClass] always returns true # def write_keys_file(keys, keys_file, chown_params = nil) dir = File.dirname(keys_file) FileUtils.mkdir_p(dir) FileUtils.chmod(0700, dir) File.open(keys_file, 'w') do |f| f.puts "#" * 78 f.puts "# USE CAUTION WHEN EDITING THIS FILE BY HAND" f.puts "# This file is generated based on the RightScale dashboard permission" f.puts "# 'server_login'. You can add trusted public keys to the file, but" f.puts "# it is regenerated every 24 hours and keys may be added or removed" f.puts "# without notice if they correspond to a dashboard user." f.puts "#" f.puts "# Instead of editing this file, you probably want to do one of the" f.puts "# following:" f.puts "# - Edit dashboard permissions (Settings > Account > Users)" f.puts "# - Change your personal public key (Settings > User > SSH)" f.puts "#" keys.each { |k| f.puts k } end FileUtils.chmod(0600, keys_file) FileUtils.chown_R(chown_params[:user], chown_params[:group], File.dirname(keys_file)) if chown_params return true end end end
36.804104
132
0.647488
0317476604a9569257bfe3ccf81b16d55594e099
98
# frozen_string_literal: true class AboutController < ApplicationController def about; end end
16.333333
45
0.816327
1a4544d11fb1454a125458c7d1eef2f5652f0776
141
class AddMtWorkerIDToWorkerMessages < ActiveRecord::Migration def change add_column :worker_messages, :mt_worker_id, :string end end
23.5
61
0.801418
aba8a419c14b6b05ec05865ba44d2d76bbe4c3c3
2,105
require "kitchen/transport/speedy/version" require 'kitchen' require 'mixlib/shellout' module Kitchen module Transport module SpeedyBase # require :log_prefix # copy paste from ssh transport # see https://github.com/test-kitchen/test-kitchen/pull/726 def create_new_connection(options, &block) if @connection logger.debug("[#{log_prefix}] shutting previous connection #{@connection}") @connection.close end @connection_options = options @connection = self.class::Connection.new(options, &block) end end module SpeedyConnectionBase def valid_local_requirements? raise NotImplementedError end def valid_remote_requirements? raise NotImplementedError end def archive_locally(path, archive_path) raise NotImplementedError end def dearchive_remotely(archive_basename, remote) raise NotImplementedError end def upload(locals, remote) unless valid_local_requirements? && valid_remote_requirements? logger.debug("Calling back default implementation since requirements cannot be validate locally and in the box") return super end Array(locals).each do |local| if ::File.directory?(local) file_count = ::Dir.glob(::File.join(local, '**/*')).size logger.debug("#{local} contains #{file_count}") archive_basename = ::File.basename(local) + '.tar' archive = ::File.join(::File.dirname(local), archive_basename) Mixlib::ShellOut.new(archive_locally(local, archive)).run_command.error! execute(ensure_remotedir_exists(remote)) logger.debug("Calling regular upload for #{archive} to #{remote}") super(archive, remote) execute(dearchive_remotely(archive_basename, remote)) else logger.debug("Calling regular upload for #{local} since it is a simple file") super(local, remote) end end end end end end
30.507246
122
0.641805
ab201fba6e075b7961447cde4f59ee4dbe3fac4e
1,146
require 'pact_broker/db/data_migrations/helpers' module PactBroker module DB module DataMigrations class MigrateWebhookHeaders extend Helpers def self.call(connection) if columns_exist?(connection) connection[:webhook_headers].for_update.each do | webhook_header | webhook = connection[:webhooks].for_update.where(id: webhook_header[:webhook_id]).first new_headers = webhook[:headers] ? JSON.parse(webhook[:headers]) : {} new_headers.merge!(webhook_header[:name] => webhook_header[:value]) connection[:webhooks].where(id: webhook[:id]).update(headers: new_headers.to_json) connection[:webhook_headers].where(webhook_header).delete end end end def self.columns_exist?(connection) column_exists?(connection, :webhooks, :headers) && column_exists?(connection, :webhook_headers, :name) && column_exists?(connection, :webhook_headers, :value) && column_exists?(connection, :webhook_headers, :webhook_id) end end end end end
36.967742
101
0.643979
18d1dbafcd3edfa250b51015975c6b1342919a16
179
AwsSesNewsletters::Engine.routes.draw do # SNS post 'email_responses/bounce' => 'email_responses#bounce' post 'email_responses/complaint' => 'email_responses#complaint' end
29.833333
65
0.776536
398a87b3441fe53c1d275ee147d33a44be436fe6
210
module Moip2 module Resource class Invoice < SimpleDelegator attr_reader :client def initialize(client, response) super(response) @client = client end end end end
16.153846
38
0.633333
e2c535d2d5d0ded680dfc8e8405b2522af6b0e37
525
require_relative "base_index" module Fontist module Indexes class DefaultFamilyFontIndex < BaseIndex def self.path Fontist.formula_index_path end def add_formula(formula) formula.fonts.each do |font| font.styles.each do |style| font_name = style.default_family_name || font.name add_index_formula(font_name, formula.to_index_formula) end end end def normalize_key(key) key.downcase end end end end
21
66
0.632381
610e35038e2ba4452d90458bc2c208e959e45626
1,419
# frozen_string_literal: true module RuboCop module Cop module Minitest # This cop enforces the test to use `refute_nil` instead of using # `refute_equal(nil, something)`, `refute(something.nil?)`, or `refute_predicate(something, :nil?)`. # # @example # # bad # refute_equal(nil, actual) # refute_equal(nil, actual, 'message') # refute(actual.nil?) # refute(actual.nil?, 'message') # refute_predicate(object, :nil?) # refute_predicate(object, :nil?, 'message') # # # good # refute_nil(actual) # refute_nil(actual, 'message') # class RefuteNil < Base include ArgumentRangeHelper include NilAssertionHandleable extend AutoCorrector ASSERTION_TYPE = 'refute' RESTRICT_ON_SEND = %i[refute refute_equal refute_predicate].freeze def_node_matcher :nil_refutation, <<~PATTERN { (send nil? :refute_equal nil $_ $...) (send nil? :refute (send $_ :nil?) $...) (send nil? :refute_predicate $_ (sym :nil?) $...) } PATTERN def on_send(node) nil_refutation(node) do |actual, message| register_offense(node, actual, message) end end private def assertion_type ASSERTION_TYPE end end end end end
26.773585
106
0.568006
7a378da6e9654b171f7d2da4db454108af63ccb1
324
# encoding: UTF-8 # frozen_string_literal: true class MigrateAllCurrencyModelsToSingle < ActiveRecord::Migration def change execute %[ UPDATE deposits SET type = 'Deposits::Coin' WHERE type <> 'Deposits::Bank' ] execute %[ UPDATE withdraws SET type = 'Withdraws::Coin' WHERE type <> 'Withdraws::Bank' ] end end
32.4
94
0.725309
7926a3681a35f330a0fabd0079c1528fde84bf7a
22,022
class Graph require 'digest/md5' attr_accessor :data_sets, :data def initialize ###########removed between 1.9.3 and 1.9.6 #@title_size = 30 #@line_default = "&line=3,#87421F" + "& \n" ########### same since 1.9.3 @data = [] @x_labels = [] @y_min = 0 @y_max = 20 @title = "" @title_style = "" @x_tick_size = -1 @y2_max = '' @y2_min = '' # GRID styles @y_axis_color = '' @x_axis_color = '' @x_grid_color = '' @y_grid_color = "" @x_axis_3d = '' @x_axis_steps = 1 @y2_axis_color = '' # AXIS LABEL styles @x_label_style = '' @y_label_style = '' @y_label_style_right = '' # AXIS LEGEND styles @x_legend = '' @y_legend = '' @y_legend_right = '' @lines = {} @bg_color = '' @bg_image = '' @inner_bg_color = '' @inner_bg_color_2 = '' @inner_bg_angle = '' # PIE chart @pie = '' @pie_values = '' @pie_colors = '' @pie_labels = '' @pie_links = '' @tool_tip = '' @y2_lines = [] @y_label_steps = 5 ########## new between 1.9.3 and 1.9.6 @data_sets = [] @links = [] @width = 250 @height = 200 @base = 'js/' @x_min = 0 @x_max = 20 @y_steps = '' @occurence = 0 @x_offset = '' @x_legend_size = 20 @x_legend_color = '#000000' @line_default = {'type' => 'line', 'values' => '3,#87421F'} @js_line_default = 'so.addVariable("line","3,#87421F")' @y_format = '' @num_decimals = '' @is_fixed_num_decimals_forced = '' @is_decimal_separator_comma = '' @is_thousand_separator_disabled = '' ##### OTHER THINGS @unique_id = "" @js_path = "/javascripts/" @swf_path = "/" @output_type = "" end # new methods between 1.9.3 and 1.9.6 def set_unique_id() md5 = Digest::MD5.new << Time.now.to_s << String(Time.now.usec) << String(rand(0)) << String($$) << "open_flash_chart" @unique_id = md5.hexdigest end def get_unique_id() @unique_id end def set_js_path(path) @js_path = path end def set_swf_path(path) @swf_path = path end def set_output_type(type) @output_type = type end def next_line line_num = '' line_num = '_' + (@lines.size + 1).to_s if @lines.size > 0 line_num end def self.esc(text) tmp = text.to_s.gsub(",","#comma#") CGI::escape(tmp) end def format_output(function, values) if @output_type == 'js' return "so.addVariable('#{function}','#{values}');" else return "&#{function}=#{values}&" end end %w(width height base y_format num_decimals).each do |method| define_method("set_#{method}") do |a| self.instance_variable_set("@#{method}", a) end end %w(x_offset is_fixed_num_decimals_forced is_decimal_separator_comma is_thousand_separator_disabled).each do |method| define_method("set_#{method}") do |a| self.instance_variable_set("@#{method}", a ? 'true':'false') end end ##################################### %w(data links).each do |method| define_method("set_#{method}") do |a| @data << a.join(',') if method == 'data' @links << a.join(',') if method == 'links' end end %w(tool_tip).each do |method| define_method("set_#{method}") do |a| self.instance_variable_set("@#{method}", Graph.esc(a)) end end # create the set methods for these instance variables in a loop since they are all the same %w(bg_color x_max x_min y_max y_min).each do |method| define_method("set_#{method}") do |a| self.instance_variable_set("@#{method}", a) end end def set_x_labels(a) @x_labels = a end def set_y_label_steps(val) @y_steps = val end %w(x_tick_size x_axis_steps x_axis_3d).each do |method| define_method("set_#{method}") do |a| self.instance_variable_set("@#{method}", a) if a > 0 end end def set_x_label_style(size, color='', orientation=0, step=-1, grid_color='') @x_label_style = size.to_s @x_label_style += ",#{color}" if color.size > 0 @x_label_style += ",#{orientation}" if orientation > -1 @x_label_style += ",#{step}" if step > 0 @x_label_style += ",#{grid_color}" if grid_color.size > 0 end def set_bg_image(url, x='center', y='center') @bg_image = url @bg_image_x = x @bg_image_y = y end def attach_to_y_right_axis(data_number) @y2_lines << data_number end def set_inner_background(col, col2='', angle=-1) @inner_bg_color = col @inner_bg_color_2 = col2 if col2.size > 0 @inner_bg_angle = angle if angle != -1 end %w(y_label_style y_right_label_style).each do |method| define_method("set_#{method}") do |size, color| temp = size.to_s temp += ",#{color}" if color.size > 0 if method == "y_right_label_style" self.instance_variable_set("@y_label_style_right", temp) else self.instance_variable_set("@#{method}", temp) end end end %w(max min).each do |m| define_method("set_y_right_#{m}") do |x| temp = "&y2_#{m}=#{x}& \n" self.instance_variable_set("@y2_#{m}", temp) end end def set_title(title, style='') @title = Graph.esc(title) @title_style = style if style.size > 0 end def title(title, style='') set_title(title, style) end def set_x_legend(text, size=-1, color='') # next three lines will only be needed if defining y_rigth_legend method = "x_legend" self.instance_variable_set("@#{method}", Graph.esc(text)) self.instance_variable_set("@#{method}" + "_size", size) if size > 0 self.instance_variable_set("@#{method}" + "_color", color) if color.size > 0 end %w(y_legend y_legend_right).each do |method| define_method("set_" + method) do |text, *optional| size,color = *optional size ||= -1 color ||= '' # next three lines will only be needed if defining y_rigth_legend method = "y_legend_right" if method =~ /right/ label = method label = "y2_legend" if method =~ /right/ temp = text temp += ",#{size}" if size > 0 temp += ",#{color}" if !color.blank? self.instance_variable_set("@#{method}", temp) end end def line(width, color='', text='', size=-1, circles=-1) type = 'line' + next_line description = '' if width > 0 description += "#{width}" description += ",#{color}" end if text.size > 0 description += ",#{text}" description += ",#{size}" end if circles > 0 description += ",#{circles}" end @lines[type] = description end %w(line_dot line_hollow).each do |method| define_method(method) do |width, dot_size, color, *optional| text,font_size = *optional text ||= '' font_size ||= '' type = method + next_line description = "#{width},#{color},#{text}" description += ",#{font_size},#{dot_size}" @lines[type] = description end end def area_hollow(width, dot_size, color, alpha, text='', font_size='', fill_color='') type = "area_hollow" + next_line description = "#{width},#{dot_size},#{color},#{alpha}" description += ",#{text},#{font_size}" if text.size > 0 description += ",#{fill_color}" if fill_color.size > 0 @lines[type] = description end %w(bar bar_3d bar_fade).each do |method| define_method(method) do |alpha, *optional| color,text,size = *optional color ||= '' text ||= '' size ||= -1 type = method + next_line description = "#{alpha},#{color},#{text},#{size}" @lines[type] = description end end %w(bar_glass bar_filled).each do |method| define_method(method) do |alpha, color, color_outline, *optional| text,size = *optional text ||= "" size ||= -1 method = "filled_bar" if method == "bar_filled" type = method + next_line description = "#{alpha},#{color},#{color_outline},#{text},#{size}" @lines[type] = description end end def bar_sketch(alpha, offset, color, color_outline, text='', size=-1) type = "bar_sketch" + next_line description = "#{alpha},#{offset},#{color},#{color_outline},#{text},#{size}" @lines[type] = description end %w(candle hlc).each do |method| define_method(method) do |data, alpha, line_width, color, *optional| text,size = *optional text ||= "" size ||= -1 type = method + next_line description = "#{alpha},#{line_width},#{color},#{text},#{size}" @lines[type] = description @data << data.collect{|d| d.toString}.join(",") end end def scatter(data, line_width, color, text='',size=-1) type = "scatter" + next_line description = "#{line_width},#{color},#{text},#{size}" @lines[type] = description @data << data.collect{|d| d.toString}.join(",") end %w(x y).each do |method| define_method("set_" + method + "_axis_color") do |axis, *optional| grid = *optional grid ||= '' self.instance_variable_set("@#{method}_axis_color", axis) self.instance_variable_set("@#{method}_grid_color", grid) end end def y_right_axis_color(color) @y2_axis_color = color end def pie(alpha, line_color, style, gradient = true, border_size = false) @pie = "#{alpha},#{line_color},#{style}" if !gradient @pie += ",#{!gradient}" end if border_size @pie += "," if gradient === false @pie += ",#{border_size}" end end def pie_values(values, labels = [], links = []) @pie_values = values.join(',') @pie_labels = labels.join(',') @pie_links = links.join(",") end def pie_slice_colors(colors) @pie_colors = colors.join(",") end def render temp = [] if @output_type == 'js' set_unique_id temp << '<div id="my_chart' + "#{@unique_id}" + '"></div>' temp << '<script type="text/javascript" src="' + "#{@js_path}/swfobject.js" + '"></script>' temp << '<script type="text/javascript">' temp << 'var so = new SWFObject("' + @swf_path + 'open-flash-chart.swf", "ofc", "' + @width.to_s + '", "' + @height.to_s + '", "9", "#FFFFFF");' temp << 'so.addVariable("variables","true");' end {"title" => [@title, @title_style], "x_legend" => [@x_legend, @x_legend_size, @x_legend_color], "x_label_style" => [@x_label_style], "x_ticks" => [@x_tick_size], "x_axis_steps" => [@x_axis_steps], "x_axis_3d" => [@x_axis_3d], "y_legend" => [@y_legend], "y2_legend" => [@y_legend_right], "y_min" => [@y_min], "y_label_style" => [@y_label_style], "y2_min" => [@y2_min], "y2_max" => [@y2_max], "bg_colour" => [@bg_color], "bg_image" => [@bg_image], "bg_image_x" => [@bg_image_x], "bg_image_y" => [@bg_image_y], "x_axis_colour" => [@x_axis_color], "x_grid_colour" => [@x_grid_color], "y_axis_colour" => [@y_axis_color], "y_grid_colour" => [@y_grid_color], "y2_axis_colour" => [@y2_axis_color], "x_offset" => [@x_offset], "inner_background" => [@inner_bg_color, @inner_bg_color_2, @inner_bg_angle], "tool_tip" => [@tool_tip], "y_format" => [@y_format], "num_decimals" => [@num_decimals], "is_fixed_num_decimals_forced" => [@is_fixed_num_decimals_forced], "is_decimal_separator_comma" => [@is_decimal_separator_comma], "is_thousand_separator_disabled" => [@is_thousand_separator_disabled] }.each do |k,v| next if v[0].nil? next if (v[0].class == String ? v[0].size <= 0 : v[0] < 0) temp << format_output(k, v.compact.join(",")) end temp << format_output("y_ticks", "5,10,#{@y_steps}") if @lines.size == 0 and @data_sets.size == 0 temp << format_output(@line_default['type'], @line_default['values']) else @lines.each do |type,description| temp << format_output(type, description) end end num = 1 @data.each do |data| if num == 1 temp << format_output('values', data) else temp << format_output("values_#{num}", data) end num += 1 end num = 1 @links.each do |link| if num == 1 temp << format_output('links', link) else temp << format_output("links_#{num}", link) end num += 1 end if @y2_lines.size > 0 temp << format_output('y2_lines', @y2_lines.join(',')) temp << format_output('show_y2', 'true') end if @x_labels.size > 0 temp << format_output('x_labels', @x_labels.join(",")) else temp << format_output('x_min', @x_min) if @x_min.size > 0 temp << format_output('x_max', @x_max) if @x_max.size > 0 end temp << format_output('y_min', @y_min) temp << format_output('y_max', @y_max) if @pie.size > 0 temp << format_output('pie', @pie) temp << format_output('values', @pie_values) temp << format_output('pie_labels', @pie_labels) temp << format_output('colours', @pie_colors) temp << format_output('links', @pie_links) end count = 1 @data_sets.each do |set| temp << set.toString(@output_type, count > 1 ? "_#{count}" : '') count += 1 end if @output_type == "js" temp << 'so.write("my_chart' + @unique_id + '");' temp << '</script>' end return temp.join("\r\n") end end class Line attr_accessor :line_width, :color, :_key, :key, :key_size, :data, :tips, :var def initialize(line_width, color) @var = 'line' @line_width = line_width @color = color @data = [] @links = [] @tips = [] @_key = false end def key(key, size) @_key = true @key = Graph.esc(key) @key_size = size end def add(data) @data << (data.nil? ? 'null' : data) end def add_link(data, link) add(data) @links << Graph.esc(link) end def add_data_tip(data, tip) add(data) @tips << Graph.esc(tip) end def add_data_link_tip(data, link, tip) add_link(data, link) @tips << Graph.esc(tip) end def _get_variable_list values = [] values << @line_width values << @color if @_key values << @key values << @key_size end return values end def toString(output_type, set_num) values = _get_variable_list.join(",") tmp = [] if output_type == 'js' tmp << 'so.addVariable("' + @var + set_num.to_s + '","' + values + '");' tmp << 'so.addVariable("values' + set_num.to_s + '","' + @data.join(",") + '");' if [email protected]? tmp << 'so.addVariable("links' + set_num.to_s + '","' + @links.join(",") + '");' end if [email protected]? tmp << 'so.addVariable("tool_tips_set' + set_num.to_s + '","' + @tips.join(",") + '");' end else tmp << '&' + @var + set_num.to_s + '=' + values + '&' tmp << '&values' + set_num.to_s + '=' + @data.join(",") + '&' if [email protected]? tmp << '&links' + set_num.to_s + '=' + @links.join(",") + '&' end if [email protected]? tmp << '&tool_tips_set' + set_num.to_s + '=' + @tips.join(",") + '&' end end return tmp.join("\r\n") end end class LineHollow < Line attr_accessor :dot_size, :var def initialize(line_width, dot_size, color) super(line_width, color) @var = 'line_hollow' @dot_size = dot_size end def _get_variable_list values = [] values << @line_width values << @color if @_key values << @key values << @key_size else values << '' values << '' end values << @dot_size return values end end class LineDot < LineHollow def initialize(line_width, dot_size, color) super(line_width, dot_size, color) @var = 'line_dot' end end class Bar attr_accessor :color, :alpha, :data, :links, :_key, :key, :key_size, :tips, :var def initialize(alpha, color) @var = 'bar' @alpha = alpha @color = color @data = [] @links = [] @tips = [] @_key = false end def key(key, size) @_key = true @key = Graph.esc(key) @key_size = size end def add(data) @data << (data.nil? ? 'null' : data) end def add_link(data, link) add(data) @links << Graph.esc(link) end def add_data_tip(data, tip) add(data) @tips << Graph.esc(tip) end def _get_variable_list values = [] values << @alpha values << @color if @_key values << @key values << @key_size end return values end def toString(output_type, set_num) values = _get_variable_list.join(",") temp = [] if output_type == 'js' temp << 'so.addVariable("' + @var + set_num.to_s + '","' + values + '");' temp << 'so.addVariable("values' + set_num.to_s + '","' + @data.join(",") + '");' if @links.size > 0 temp << 'so.addVariable("links' + set_num.to_s + '","' + @links.join(",") + '");' end if @tips.size > 0 temp << 'so.addVariable("tool_tips_set' + set_num.to_s + '","' + @tips.join(",") + '");' end else temp << '&' + @var + set_num.to_s + '=' + values + '&' temp << '&values' + set_num.to_s + '=' + @data.join(",") + '&' if @links.size > 0 temp << '&links' + set_num.to_s + '=' + @links.join(",") + '&' end if @tips.size > 0 temp << '&tool_tips_set' + set_num.to_s + '=' + @tips.join(",") + '&' end end return temp.join("\r\n") end end class Bar3d < Bar def initialize(alpha, color) super(alpha,color) @var = 'bar_3d' end end class BarFade < Bar def initialize(alpha, color) super(alpha, color) @var = 'bar_fade' end end class BarOutline < Bar def initialize(alpha, color, outline_color) super(alpha, color) @var = 'filled_bar' @outline_color = outline_color end def _get_variable_list values = [] values << @alpha values << @color values << @outline_color if @_key values << @key values << @key_size end return values end end class BarGlass < BarOutline def initialize(alpha, color, outline_color) super(alpha, color, outline_color) @var = 'bar_glass' end end class BarSketch < BarOutline def initialize(alpha, offset, color, outline_color) super(alpha, color, outline_color) @var = 'bar_sketch' @offset = offset end def _get_variable_list values = [] values << @alpha values << @offset values << @color values << @outline_color if @_key values << @key values << @key_size end return values end end class Candle def initialize(high, open, close, low) @out = [] @out << high @out << open @out << close @out << low end def toString return '[' + @out.join(",") + ']' end end class Hlc def initialize(high, low, close) @out = [high, low, close] end def toString return '[' + @out.join(",") + ']' end end class Point def initialize(x,y,size_px) @out = [x,y,size_px] end def toString return '[' + @out.join(',') + ']' end end $open_flash_chart_seqno = nil def _ofc(width, height, url, use_swfobject, base="/", set_wmode_transparent=false) url = CGI::escape(url) out = [] protocol = 'http' if request.env["HTTPS"] == 'on' protocol = 'https' end obj_id = 'chart' div_name = 'flashcontent' if !$open_flash_chart_seqno $open_flash_chart_seqno = 1 out << '<script type="text/javascript" src="' + base + 'javascripts/swfobject.js"></script>' else $open_flash_chart_seqno += 1 obj_id += "_#{$open_flash_chart_seqno}" div_name += "_#{$open_flash_chart_seqno}" end if use_swfobject out << '<div id="' + div_name + '"></div>' out << '<script type="text/javascript">' out << 'var so = new SWFObject("' + base + 'open-flash-chart.swf", "' + obj_id + '","' + width.to_s + '","' + height.to_s + '", "9", "#FFFFFF");' out << 'so.addVariable("data", "' + url + '");' out << 'so.addParam("wmode", "transparent");' if set_wmode_transparent out << 'so.addParam("allowScriptAccess", "sameDomain");' out << 'so.write("' + div_name + '");' out << '</script>' out << '<noscript>' end out << '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="' + protocol + '://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" ' out << 'width="' + width.to_s + '" height="' + height.to_s + '" id="ie_' + obj_id + '" align="middle">' out << '<param name="allowScriptAccess" value="sameDomain" />' out << '<param name="movie" value="' + base + 'open-flash-chart.swf?' + width.to_s + '&height=' + height.to_s + '&data=' + url + '" />' out << '<param name="quality" value="high" />' out << '<param name="bgcolor" value="#FFFFFF" />' out << '<param name="wmode" value="transparent" />' if set_wmode_transparent out << '<embed src="' + base + 'open-flash-chart.swf?data=' + url + '" quality="high" bgcolor="#FFFFFF" width="' + width.to_s + '" height="' + height.to_s + '" name="' + obj_id + '" align="middle" allowScriptAccess="sameDomain" ' out << 'type="application/x-shockwave-flash" pluginpage="' + protocol + '://ww.macromedia.com/go/getflashplayer" id="' + obj_id + '"/>' out << '</object>' if use_swfobject out << '</noscript>' end return out.join("\n") end def open_flash_chart_object_str(width, height, url, use_swfobject=true, base='/', set_wmode_transparent=false) return _ofc(width, height, url, use_swfobject, base, set_wmode_transparent) end def open_flash_chart_object(width, height, url, use_swfobject=true, base='/', set_wmode_transparent=false) return _ofc(width, height, url, use_swfobject, base, set_wmode_transparent) end
25.786885
231
0.573517
d5a61085351e5c74f52333041831947513bc26d4
35,789
require "forwardable" require "hamster/immutable" require "hamster/enumerable" module Hamster def self.vector(*items) items.empty? ? EmptyVector : Vector.new(items.freeze) end # A `Vector` is an ordered, integer-indexed collection of objects. Like `Array`, # `Vector` indexing starts at 0. Also like `Array`, negative indexes count back # from the end of the `Vector`. # # `Vector`'s interface is modeled after that of `Array`, minus all the methods # which do destructive updates. Some methods which modify `Array`s destructively # (like {#insert} or {#delete_at}) are included, but they return new `Vectors` # and leave the existing one unchanged. # # = Creating New Vectors # # Hamster.vector('a', 'b', 'c') # Hamster::Vector.new([:first, :second, :third]) # Hamster::Vector[1, 2, 3, 4, 5] # # = Retrieving Items from Vectors # # require 'hamster/vector' # vector = Hamster.vector(1, 2, 3, 4, 5) # vector[0] # => 1 # vector[-1] # => 5 # vector[0,3] # => Hamster::Vector[1, 2, 3] # vector[1..-1] # => Hamster::Vector[2, 3, 4, 5] # vector.first # => 1 # vector.last # => 5 # # = Creating Modified Vectors # # vector.add(6) # => Hamster::Vector[1, 2, 3, 4, 5, 6] # vector.insert(1, :a, :b) # => Hamster::Vector[1, :a, :b, 2, 3, 4, 5] # vector.delete_at(2) # => Hamster::Vector[1, 2, 4, 5] # vector + [6, 7] # => Hamster::Vector[1, 2, 3, 4, 5, 6, 7] # # Other `Array`-like methods like {#select}, {#map}, {#shuffle}, {#uniq}, {#reverse}, # {#rotate}, {#flatten}, {#sort}, {#sort_by}, {#take}, {#drop}, {#take_while}, # {#drop_while}, {#fill}, {#product}, and {#transpose} are also supported. # class Vector extend Forwardable include Immutable include Enumerable # @private BLOCK_SIZE = 32 # @private INDEX_MASK = BLOCK_SIZE - 1 # @private BITS_PER_LEVEL = 5 # Return the number of items in this `Vector` # @return [Integer] attr_reader :size def_delegator :self, :size, :length class << self # Create a new `Vector` populated with the given items. # @return [Vector] def [](*items) new(items.freeze) end # Return an empty `Vector`. If used on a subclass, returns an empty instance # of that class. # # @return [Vector] def empty @empty ||= self.new end # "Raw" allocation of a new `Vector`. Used internally to create a new # instance quickly after building a modified trie. # # @return [Vector] # @private def alloc(root, size, levels) obj = allocate obj.instance_variable_set(:@root, root) obj.instance_variable_set(:@size, size) obj.instance_variable_set(:@levels, levels) obj end end def initialize(items=[].freeze) items = items.to_a if items.size <= 32 items = items.dup.freeze if !items.frozen? @root, @size, @levels = items, items.size, 0 else root, size, levels = items, items.size, 0 while root.size > 32 root = root.each_slice(32).to_a levels += 1 end @root, @size, @levels = root.freeze, size, levels end end # Return `true` if this `Vector` contains no items. # # @return [Boolean] def empty? @size == 0 end def_delegator :self, :empty?, :null? # Return the first item in the `Vector`. If the vector is empty, return `nil`. # # @return [Object] def first get(0) end def_delegator :self, :first, :head # Return the last item in the `Vector`. If the vector is empty, return `nil`. # # @return [Object] def last get(-1) end # Return a new `Vector` with `item` added after the last occupied position. # # @param item [Object] The object to insert at the end of the vector # @return [Vector] def add(item) update_root(@size, item) end def_delegator :self, :add, :<< def_delegator :self, :add, :conj def_delegator :self, :add, :conjoin def_delegator :self, :add, :push # Return a new `Vector` with the item at `index` replaced by `item`. If the # `item` argument is missing, but an optional code block is provided, it will # be passed the existing item and what the block returns will replace it. # # @param index [Integer] The index to update # @param item [Object] The object to insert into that position # @return [Vector] def set(index, item = yield(get(index))) raise IndexError if @size == 0 index += @size if index < 0 raise IndexError if index > @size || index < 0 update_root(index, item) end # Retrieve the item at `index`. If there is none (either the provided index # is too high or too low), return `nil`. # # @param index [Integer] The index to retrieve # @return [Object] def get(index) return nil if @size == 0 index += @size if index < 0 return nil if index >= @size || index < 0 leaf_node_for(@root, @levels * BITS_PER_LEVEL, index)[index & INDEX_MASK] end def_delegator :self, :get, :at # Retrieve the value at `index`, or use the provided default value or block, # or otherwise raise an `IndexError`. # # @overload fetch(index) # Retrieve the value at the given index, or raise an `IndexError` if it is # not found. # @param index [Integer] The index to look up # @overload fetch(index) { |index| ... } # Retrieve the value at the given index, or call the optional # code block (with the non-existent index) and get its return value. # @yield [index] The index which does not exist # @yieldreturn [Object] Object to return instead # @param index [Integer] The index to look up # @overload fetch(index, default) # Retrieve the value at the given index, or else return the provided # `default` value. # @param index [Integer] The index to look up # @param default [Object] Object to return if the key is not found # # @return [Object] def fetch(index, default = (missing_default = true)) if index >= -@size && index < @size get(index) elsif block_given? yield(index) elsif !missing_default default else raise IndexError, "index #{index} outside of vector bounds" end end # Element reference. Return the item at a specific index, or a specified, # contiguous range of items (as a new `Vector`). # # @overload vector[index] # Return the item at `index`. # @param index [Integer] The index to retrieve. # @overload vector[start, length] # Return a subvector starting at index `start` and continuing for `length` elements. # @param start [Integer] The index to start retrieving items from. # @param length [Integer] The number of items to retrieve. # @overload vector[range] # Return a subvector specified by the given `range` of indices. # @param range [Range] The range of indices to retrieve. # # @return [Object] def [](arg, length = (missing_length = true)) if missing_length if arg.is_a?(Range) from, to = arg.begin, arg.end from += @size if from < 0 to += @size if to < 0 to += 1 if !arg.exclude_end? length = to - from length = 0 if length < 0 subsequence(from, length) else get(arg) end else arg += @size if arg < 0 subsequence(arg, length) end end def_delegator :self, :[], :slice # Return a new `Vector` with the given values inserted before the element at `index`. # # @param index [Integer] The index where the new items should go # @param items [Array] The items to add # @return [Vector] def insert(index, *items) raise IndexError if index < -@size index += @size if index < 0 if index < @size suffix = flatten_suffix(@root, @levels * BITS_PER_LEVEL, index, []) suffix.unshift(*items) elsif index == @size suffix = items else suffix = Array.new(index - @size, nil).concat(items) index = @size end replace_suffix(index, suffix) end # Return a new `Vector` with the element at `index` removed. If the given `index` # does not exist, return `self`. # # @param index [Integer] The index to remove # @return [Vector] def delete_at(index) return self if index >= @size || index < -@size index += @size if index < 0 suffix = flatten_suffix(@root, @levels * BITS_PER_LEVEL, index, []) replace_suffix(index, suffix.tap { |a| a.shift }) end # Return a new `Vector` with the last element removed. If empty, just return `self`. # @return [Vector] def pop return self if @size == 0 replace_suffix(@size-1, []) end # Return a new `Vector` with `obj` inserted before the first element, moving # the other elements upwards. # @param obj [Object] The value to prepend # @return [Vector] def unshift(obj) insert(0, obj) end # Return a new `Vector` with the first element removed. If empty, just return `self`. # @return [Vector] def shift delete_at(0) end # Call the given block once for each item in the vector, passing each # item from first to last successively to the block. # # @return [self] def each(&block) return to_enum unless block_given? traverse_depth_first(@root, @levels, &block) self end # Call the given block once for each item in the vector, passing each # item starting from the last, and counting back to the first, successively to # the block. # # @return [self] def reverse_each(&block) return enum_for(:reverse_each) unless block_given? reverse_traverse_depth_first(@root, @levels, &block) self end # Return a new `Vector` containing all elements for which the given block returns # true. # # @return [Vector] def filter return enum_for(:filter) unless block_given? reduce(self.class.empty) { |vector, item| yield(item) ? vector.add(item) : vector } end # Return a new `Vector` with all items which are equal to `obj` removed. # `#==` is used for checking equality. # # @param obj [Object] The object to remove (every occurrence) # @return [Vector] def delete(obj) filter { |item| item != obj } end # Invoke the given block once for each item in the vector, and return a new # `Vector` containing the values returned by the block. # # @return [Vector] def map return enum_for(:map) if not block_given? return self if empty? self.class.new(super) end def_delegator :self, :map, :collect # Return a new `Vector` with the same elements as this one, but randomly permuted. # # @return [Vector] def shuffle self.class.new(((array = to_a).frozen? ? array.shuffle : array.shuffle!).freeze) end # Return a new `Vector` with no duplicate elements, as determined by `#hash` and # `#eql?`. For each group of equivalent elements, only the first will be retained. # # @return [Vector] def uniq self.class.new(((array = to_a).frozen? ? array.uniq : array.uniq!).freeze) end # Return a new `Vector` with the same elements as this one, but in reverse order. # # @return [Vector] def reverse self.class.new(((array = to_a).frozen? ? array.reverse : array.reverse!).freeze) end # Return a new `Vector` with the same elements, but rotated so that the one at # index `count` is the first element of the new vector. If `count` is positive, # the elements will be shifted left, and those shifted past the lowest position # will be moved to the end. If `count` is negative, the elements will be shifted # right, and those shifted past the last position will be moved to the beginning. # # @param count [Integer] The number of positions to shift items by # @return [Vector] def rotate(count = 1) return self if (count % @size) == 0 self.class.new(((array = to_a).frozen? ? array.rotate(count) : array.rotate!(count)).freeze) end # Return a new `Vector` with all nested vectors and arrays recursively "flattened # out", that is, their elements inserted into the new `Vector` in the place where # the nested array/vector originally was. If an optional `level` argument is # provided, the flattening will only be done recursively that number of times. # A `level` of 0 means not to flatten at all, 1 means to only flatten nested # arrays/vectors which are directly contained within this `Vector`. # # @param level [Integer] The depth to which flattening should be applied # @return [Vector] def flatten(level = nil) return self if level == 0 self.class.new(((array = to_a).frozen? ? array.flatten(level) : array.flatten!(level)).freeze) end # Return a new `Vector` built by concatenating this one with `other`. `other` # can be any object which is convertible to an `Array` using `#to_a`. # # @param other [Enumerable] The collection to concatenate onto this vector # @return [Vector] def +(other) other = other.to_a other = other.dup if other.frozen? replace_suffix(@size, other) end def_delegator :self, :+, :concat # `others` should be arrays and/or vectors. The corresponding elements from this # `Vector` and each of `others` (that is, the elements with the same indices) # will be gathered into arrays. # # If an optional block is provided, each such array will be passed successively # to the block. Otherwise, a new `Vector` of all those arrays will be returned. # # @param others [Array] The arrays/vectors to zip together with this one # @return [Vector, nil] def zip(*others) if block_given? super else self.class.new(super) end end # Return a new `Vector` with the same items, but sorted. The sort order will # be determined by comparing items using `#<=>`, or if an optional code block # is provided, by using it as a comparator. The block should accept 2 parameters, # and should return 0, 1, or -1 if the first parameter is equal to, greater than, # or less than the second parameter (respectively). # # @return [Vector] def sort self.class.new(super) end # Return a new `Vector` with the same items, but sorted. The sort order will be # determined by mapping the items through the given block to obtain sort keys, # and then sorting the keys according to their natural sort order. # # @return [Vector] def sort_by self.class.new(super) end # Drop the first `n` elements and return the rest in a new `Vector`. # @param n [Integer] The number of elements to remove # @return [Vector] def drop(n) self.class.new(super) end # Return only the first `n` elements in a new `Vector`. # @param n [Integer] The number of elements to retain # @return [Vector] def take(n) self.class.new(super) end # Drop elements up to, but not including, the first element for which the # block returns `nil` or `false`. Gather the remaining elements into a new # `Vector`. If no block is given, an `Enumerator` is returned instead. # # @return [Vector, Enumerator] def drop_while return enum_for(:drop_while) if not block_given? self.class.new(super) end # Gather elements up to, but not including, the first element for which the # block returns `nil` or `false`, and return them in a new `Vector`. If no block # is given, an `Enumerator` is returned instead. # # @return [Vector, Enumerator] def take_while return enum_for(:take_while) if not block_given? self.class.new(super) end # Repetition. Return a new `Vector` built by concatenating `times` copies # of this one together. # # @param times [Integer] The number of times to repeat the elements in this vector # @return [Vector] def *(times) return self.class.empty if times == 0 return self if times == 1 result = (to_a * times) result.is_a?(Array) ? self.class.new(result) : result end # Replace a range of indexes with the given object. # # @overload fill(obj) # Return a new `Vector` of the same size, with every index set to `obj`. # @overload fill(obj, start) # Return a new `Vector` with all indexes from `start` to the end of the # vector set to `obj`. # @overload fill(obj, start, length) # Return a new `Vector` with `length` indexes, beginning from `start`, # set to `obj`. # # @return [Vector] def fill(obj, index = 0, length = nil) raise IndexError if index < -@size index += @size if index < 0 length ||= @size - index # to the end of the array, if no length given if index < @size suffix = flatten_suffix(@root, @levels * BITS_PER_LEVEL, index, []) suffix.fill(obj, 0, length) elsif index == @size suffix = Array.new(length, obj) else suffix = Array.new(index - @size, nil).concat(Array.new(length, obj)) index = @size end replace_suffix(index, suffix) end # When invoked with a block, yields all combinations of length `n` of items # from the `Vector`, and then returns `self`. There is no guarantee about # which order the combinations will be yielded in. # # If no block is given, an `Enumerator` is returned instead. # # @return [self, Enumerator] def combination(n) return enum_for(:combination, n) if not block_given? return self if n < 0 || @size < n if n == 0 yield [] elsif n == 1 each { |item| yield [item] } elsif n == @size yield self.to_a else combos = lambda do |result,index,remaining| while @size - index > remaining if remaining == 1 yield result.dup << get(index) else combos[result.dup << get(index), index+1, remaining-1] end index += 1 end index.upto(@size-1) { |i| result << get(i) } yield result end combos[[], 0, n] end self end # When invoked with a block, yields all repeated combinations of length `n` of # items from the `Vector`, and then returns `self`. A "repeated combination" is # one in which any item from the `Vector` can appear consecutively any number of # times. # # There is no guarantee about which order the combinations will be yielded in. # # If no block is given, an `Enumerator` is returned instead. # # @return [self, Enumerator] def repeated_combination(n) return enum_for(:repeated_combination, n) if not block_given? if n < 0 # yield nothing elsif n == 0 yield [] elsif n == 1 each { |item| yield [item] } elsif @size == 0 # yield nothing else combos = lambda do |result,index,remaining| while index < @size-1 if remaining == 1 yield result.dup << get(index) else combos[result.dup << get(index), index, remaining-1] end index += 1 end item = get(index) remaining.times { result << item } yield result end combos[[], 0, n] end self end # Yields all permutations of length `n` of items from the `Vector`, and then # returns `self`. If no length `n` is specified, permutations of all elements # will be yielded. # # There is no guarantee about which order the permutations will be yielded in. # # If no block is given, an `Enumerator` is returned instead. # # @return [self, Enumerator] def permutation(n = @size) return enum_for(:permutation, n) if not block_given? if n < 0 || @size < n # yield nothing elsif n == 0 yield [] elsif n == 1 each { |item| yield [item] } else used, result = [], [] perms = lambda do |index| 0.upto(@size-1) do |i| if !used[i] result[index] = get(i) if index < n-1 used[i] = true perms[index+1] used[i] = false else yield result.dup end end end end perms[0] end self end # When invoked with a block, yields all repeated permutations of length `n` of # items from the `Vector`, and then returns `self`. A "repeated permutation" is # one where any item from the `Vector` can appear any number of times, and in # any position (not just consecutively) # # If no length `n` is specified, permutations of all elements will be yielded. # There is no guarantee about which order the permutations will be yielded in. # # If no block is given, an `Enumerator` is returned instead. # # @return [self, Enumerator] def repeated_permutation(n = @size) return enum_for(:repeated_permutation, n) if not block_given? if n < 0 # yield nothing elsif n == 0 yield [] elsif n == 1 each { |item| yield [item] } else result = [] perms = lambda do |index| 0.upto(@size-1) do |i| result[index] = get(i) if index < n-1 perms[index+1] else yield result.dup end end end perms[0] end self end # With one or more vector or array arguments, return the cartesian product of # this vector's elements and those of each argument; with no arguments, return the # result of multiplying all this vector's items together. # # @overload product(*vectors) # Return a `Vector` of all combinations of elements from this `Vector` and each # of the given vectors or arrays. The length of the returned `Vector` is the product # of `self.size` and the size of each argument vector or array. # @overload product # Return the result of multiplying all the items in this `Vector` together. # # @return [Vector] def product(*vectors) # if no vectors passed, return "product" as in result of multiplying all items return super if vectors.empty? vectors.unshift(self) if vectors.any?(&:empty?) return block_given? ? self : [] end counters = Array.new(vectors.size, 0) bump_counters = lambda do i = vectors.size-1 counters[i] += 1 while counters[i] == vectors[i].size counters[i] = 0 i -= 1 return true if i == -1 # we are done counters[i] += 1 end false # not done yet end build_array = lambda do array = [] counters.each_with_index { |index,i| array << vectors[i][index] } array end if block_given? while true yield build_array[] return self if bump_counters[] end else result = [] while true result << build_array[] return result if bump_counters[] end end end # Assume all elements are vectors or arrays and transpose the rows and columns. # In other words, take the first element of each nested vector/array and gather # them together into a new `Vector`. Do likewise for the second, third, and so on # down to the end of each nested vector/array. Gather all the resulting `Vectors` # into a new `Vector` and return it. # # This operation is closely related to {#zip}. The result is almost the same as # calling {#zip} on the first nested vector/array with the others supplied as # arguments. # # @return [Vector] def transpose return self.class.empty if empty? result = Array.new(first.size) { [] } 0.upto(@size-1) do |i| source = get(i) if source.size != result.size raise IndexError, "element size differs (#{source.size} should be #{result.size})" end 0.upto(result.size-1) do |j| result[j].push(source[j]) end end result.map! { |a| self.class.new(a) } self.class.new(result) end # By using binary search, finds a value from this `Vector` which meets the # condition defined by the provided block. Behavior is just like `Array#bsearch`. # See `Array#bsearch` for details. # # @return [Object] def bsearch low, high, result = 0, @size, nil while low < high mid = (low + ((high - low) >> 1)) val = get(mid) v = yield val if v.is_a? Numeric if v == 0 return val elsif v > 0 high = mid else low = mid + 1 end elsif v == true result = val high = mid elsif !v low = mid + 1 else raise TypeError, "wrong argument type #{v.class} (must be numeric, true, false, or nil)" end end result end # Return an empty `Vector` instance, of the same class as this one. Useful if you # have multiple subclasses of `Vector` and want to treat them polymorphically. # # @return [Vector] def clear self.class.empty end # Return a randomly chosen item from this `Vector`. If the vector is empty, return `nil`. # # @return [Object] def sample get(rand(@size)) end # Return a new `Vector` with only the elements at the given `indices`, in the # order specified by `indices`. If any of the `indices` do not exist, `nil`s will # appear in their places. # # @param indices [Array] The indices to retrieve and gather into a new `Vector` # @return [Vector] def values_at(*indices) self.class.new(indices.map { |i| get(i) }.freeze) end # Return the index of the last element which is equal to the provided object, # or for which the provided block returns true. # # @overload rindex(obj) # Return the index of the last element in this `Vector` which is `#==` to `obj`. # @overload rindex { |item| ... } # Return the index of the last element in this `Vector` for which the block # returns true. (Iteration starts from the last element, counts back, and # stops as soon as a matching element is found.) # # @return [Index] def rindex(obj = (missing_arg = true)) i = @size - 1 if missing_arg if block_given? reverse_each { |item| return i if yield item; i -= 1 } nil else enum_for(:rindex) end else reverse_each { |item| return i if item == obj; i -= 1 } nil end end # Assumes all elements are nested, indexable collections, and searches through them, # comparing `obj` with the first element of each nested collection. Return the # first nested collection which matches, or `nil` if none is found. # # @param obj [Object] The object to search for # @return [Object] def assoc(obj) each { |array| return array if obj == array[0] } nil end # Assumes all elements are nested, indexable collections, and searches through them, # comparing `obj` with the second element of each nested collection. Return the # first nested collection which matches, or `nil` if none is found. # # @param obj [Object] The object to search for # @return [Object] def rassoc(obj) each { |array| return array if obj == array[1] } nil end # Return an `Array` with the same elements, in the same order. The returned # `Array` may or may not be frozen. # # @return [Array] def to_a if @levels == 0 @root else flatten_node(@root, @levels * BITS_PER_LEVEL, []) end end # Return true if `other` has the same type and contents as this `Vector`. # # @param other [Object] The collection to compare with # @return [Boolean] def eql?(other) return true if other.equal?(self) return false unless instance_of?(other.class) && @size == other.size @root.eql?(other.instance_variable_get(:@root)) end # See `Object#hash`. # @return [Integer] def hash reduce(0) { |hash, item| (hash << 5) - hash + item.hash } end # @return [::Array] # @private def marshal_dump to_a end # @private def marshal_load(array) initialize(array.freeze) end private def traverse_depth_first(node, level, &block) return node.each(&block) if level == 0 node.each { |child| traverse_depth_first(child, level - 1, &block) } end def reverse_traverse_depth_first(node, level, &block) return node.reverse_each(&block) if level == 0 node.reverse_each { |child| reverse_traverse_depth_first(child, level - 1, &block) } end def leaf_node_for(node, bitshift, index) while bitshift > 0 node = node[(index >> bitshift) & INDEX_MASK] bitshift -= BITS_PER_LEVEL end node end def update_root(index, item) root, levels = @root, @levels while index >= (1 << (BITS_PER_LEVEL * (levels + 1))) root = [root].freeze levels += 1 end root = update_leaf_node(root, levels * BITS_PER_LEVEL, index, item) self.class.alloc(root, @size > index ? @size : index + 1, levels) end def update_leaf_node(node, bitshift, index, item) slot_index = (index >> bitshift) & INDEX_MASK if bitshift > 0 old_child = node[slot_index] || [] item = update_leaf_node(old_child, bitshift - BITS_PER_LEVEL, index, item) end node.dup.tap { |n| n[slot_index] = item }.freeze end def flatten_range(node, bitshift, from, to) from_slot = (from >> bitshift) & INDEX_MASK to_slot = (to >> bitshift) & INDEX_MASK if bitshift == 0 # are we at the bottom? node.slice(from_slot, to_slot-from_slot+1) elsif from_slot == to_slot flatten_range(node[from_slot], bitshift - BITS_PER_LEVEL, from, to) else # the following bitmask can be used to pick out the part of the from/to indices # which will be used to direct path BELOW this node mask = ((1 << bitshift) - 1) result = [] if from & mask == 0 flatten_node(node[from_slot], bitshift - BITS_PER_LEVEL, result) else result.concat(flatten_range(node[from_slot], bitshift - BITS_PER_LEVEL, from, from | mask)) end (from_slot+1).upto(to_slot-1) do |slot_index| flatten_node(node[slot_index], bitshift - BITS_PER_LEVEL, result) end if to & mask == mask flatten_node(node[to_slot], bitshift - BITS_PER_LEVEL, result) else result.concat(flatten_range(node[to_slot], bitshift - BITS_PER_LEVEL, to & ~mask, to)) end result end end def flatten_node(node, bitshift, result) if bitshift == 0 result.concat(node) elsif bitshift == BITS_PER_LEVEL node.each { |a| result.concat(a) } else bitshift -= BITS_PER_LEVEL node.each { |a| flatten_node(a, bitshift, result) } end result end def subsequence(from, length) return nil if from > @size || from < 0 || length < 0 length = @size - from if @size < from + length return self.class.empty if length == 0 self.class.new(flatten_range(@root, @levels * BITS_PER_LEVEL, from, from + length - 1)) end def flatten_suffix(node, bitshift, from, result) from_slot = (from >> bitshift) & INDEX_MASK if bitshift == 0 if from_slot == 0 result.concat(node) else result.concat(node.slice(from_slot, 32)) # entire suffix of node. excess length is ignored by #slice end else mask = ((1 << bitshift) - 1) if from & mask == 0 from_slot.upto(node.size-1) do |i| flatten_node(node[i], bitshift - BITS_PER_LEVEL, result) end elsif child = node[from_slot] flatten_suffix(child, bitshift - BITS_PER_LEVEL, from, result) (from_slot+1).upto(node.size-1) do |i| flatten_node(node[i], bitshift - BITS_PER_LEVEL, result) end end result end end def replace_suffix(from, suffix) # new suffix can go directly after existing elements raise IndexError if from > @size root, levels = @root, @levels if (from >> (BITS_PER_LEVEL * (@levels + 1))) != 0 # index where new suffix goes doesn't fall within current tree # we will need to deepen tree root = [root].freeze levels += 1 end new_size = from + suffix.size root = replace_node_suffix(root, levels * BITS_PER_LEVEL, from, suffix) if !suffix.empty? levels.times { suffix = suffix.each_slice(32).to_a } root.concat(suffix) while root.size > 32 root = root.each_slice(32).to_a levels += 1 end else while root.size == 1 && levels > 0 root = root[0] levels -= 1 end end self.class.alloc(root.freeze, new_size, levels) end def replace_node_suffix(node, bitshift, from, suffix) from_slot = (from >> bitshift) & INDEX_MASK if bitshift == 0 if from_slot == 0 suffix.shift(32) else node.take(from_slot).concat(suffix.shift(32 - from_slot)) end else mask = ((1 << bitshift) - 1) if from & mask == 0 if from_slot == 0 new_node = suffix.shift(32 * (1 << bitshift)) while bitshift != 0 new_node = new_node.each_slice(32).to_a bitshift -= BITS_PER_LEVEL end new_node else result = node.take(from_slot) remainder = suffix.shift((32 - from_slot) * (1 << bitshift)) while bitshift != 0 remainder = remainder.each_slice(32).to_a bitshift -= BITS_PER_LEVEL end result.concat(remainder) end elsif child = node[from_slot] result = node.take(from_slot) result.push(replace_node_suffix(child, bitshift - BITS_PER_LEVEL, from, suffix)) remainder = suffix.shift((31 - from_slot) * (1 << bitshift)) while bitshift != 0 remainder = remainder.each_slice(32).to_a bitshift -= BITS_PER_LEVEL end result.concat(remainder) else raise "Shouldn't happen" end end end end # The canonical empty `Vector`. Returned by `Hamster.vector` and `Vector[]` when # invoked with no arguments; also returned by `Vector.empty`. Prefer using this # one rather than creating many empty vectors using `Vector.new`. # EmptyVector = Hamster::Vector.empty end
32.80385
110
0.599709
030e590765a4d5d39cf6ae5eabce29c04bb9be2d
2,824
# Copyright:: 2019, The Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'spec_helper' describe 'ibmc_sp_firmware' do include_context 'ibmc data_bag context' platform 'ubuntu' step_into :ibmc_sp_firmware context 'get' do recipe do ibmc_sp_firmware 'test' do action :get end end it do subcmd = IbmcCookbook::Const::Subcmd::GET_SP.to_cmd is_expected.to run_execute(subcmd) end end context 'upgrade' do image_uri = 'image uri' signature_uri = 'uri' parameter = 'param' mode = 'Auto' active_method = 'active method' context 'with parameters' do recipe do ibmc_sp_firmware 'test' do image_uri image_uri signature_uri signature_uri parameter parameter mode mode active_method active_method action :upgrade end end it do arg = build_optional_arg_str( '-i': image_uri, '-si': signature_uri, '-PARM': parameter, '-M': mode, '-ACT': active_method ) subcmd = IbmcCookbook::Const::Subcmd::UPGRADE_SP.to_cmd(arg) is_expected.to run_execute(subcmd) end end context 'with wrong mode' do recipe do ibmc_sp_firmware 'test' do image_uri image_uri signature_uri signature_uri parameter parameter mode 'wrong mode' active_method active_method action :upgrade end end it 'raises ValidationFailed' do expect { chef_run }.to raise_error(Chef::Exceptions::ValidationFailed) end end context 'without parameters' do recipe do ibmc_sp_firmware 'test' do action :upgrade end end it 'raises ValidationFailed' do expect { chef_run }.to raise_error(Chef::Exceptions::ValidationFailed) end end end context 'enable' do recipe do ibmc_sp_firmware 'enable' do action :enable end end it do subcmd = IbmcCookbook::Const::Subcmd::SET_SP_INFO.to_cmd('-S True') is_expected.to run_execute(subcmd) subcmd = IbmcCookbook::Const::Subcmd::SYS_POWER_CTRL.to_cmd('ForceRestart') is_expected.to run_execute(subcmd) end end end
25.214286
81
0.640227
286d097190490f212666e1e5e272d2acc4efeaca
1,400
require 'spec_helper' describe 'omnibus-supermarket::app' do platform 'ubuntu', '18.04' automatic_attributes['memory']['total'] = '16000MB' it 'creates /var/opt/supermarket/etc/env' do expect(chef_run).to create_file('/var/opt/supermarket/etc/env').with( owner: 'supermarket', group: 'supermarket', mode: '0600' ) end it 'creates sitemap files with the correct permissions' do files = ['/opt/supermarket/embedded/service/supermarket/public/sitemap.xml.gz', '/opt/supermarket/embedded/service/supermarket/public/sitemap1.xml.gz'] files.each do |file| expect(chef_run).to create_file(file) .with(owner: 'supermarket', group: 'supermarket', mode: '0664') end end it 'links the env file' do expect(chef_run.link( '/opt/supermarket/embedded/service/supermarket/.env.production' )).to link_to('/var/opt/supermarket/etc/env') end it 'creates /var/opt/supermarket/etc/database.yml' do expect(chef_run).to create_file( '/var/opt/supermarket/etc/database.yml' ).with( owner: 'supermarket', group: 'supermarket', mode: '0600' ) end it 'symlinks database.yml' do expect(chef_run.link('/opt/supermarket/embedded/service/supermarket/config/database.yml')) .to link_to('/var/opt/supermarket/etc/database.yml') end end
29.787234
94
0.655714
262ff1bc9a3aaaa442619d71346099d9b42f1eea
1,384
module Ingestors class Ingestor def initialize super @messages = Array.new @ingested = 0 @processed = 0 @added = 0 @updated = 0 @rejected = 0 @token = '' end # accessor methods attr_reader :messages attr_reader :ingested attr_reader :processed attr_reader :added attr_reader :updated attr_reader :rejected attr_accessor :token # methods def read (url) raise 'Method not yet implemented' end def write (user, provider) raise 'Method not yet implemented' end def convert_description (input) return input if input.nil? return input if input == ActionController::Base.helpers.strip_tags(input) return ReverseMarkdown.convert(input, tag_border: '').strip end def process_url(row, header) row[header].to_s.lstrip unless row[header].nil? end def process_description (row, header) return nil if row[header].nil? desc = row[header] desc.gsub!(/""/, '"') desc.gsub!(/\A""|""\Z/, '') desc.gsub!(/\A"|"\Z/, '') convert_description desc end def process_array (row, header) row[header].to_s.lstrip.split(/[;]/).reject(&:empty?).compact unless row[header].nil? end def get_column(row, header) row[header].to_s.lstrip unless row[header].nil? end end end
22.322581
91
0.617052
1a2d2b78616561686a611157a25e73c50465de11
846
require 'test_helper' class UsersControllerTest < ActionDispatch::IntegrationTest setup do @user = users(:one) end test "should get index" do get users_url, as: :json assert_response :success end test "should create user" do assert_difference('User.count') do post users_url, params: { user: { name: @user.name, sig_rec: @user.sig_rec } }, as: :json end assert_response 201 end test "should show user" do get user_url(@user), as: :json assert_response :success end test "should update user" do patch user_url(@user), params: { user: { name: @user.name, sig_rec: @user.sig_rec } }, as: :json assert_response 200 end test "should destroy user" do assert_difference('User.count', -1) do delete user_url(@user), as: :json end assert_response 204 end end
21.692308
100
0.666667
6a54db1abbd4ed75cb6fe2282e5a9792c595c6a9
502
cask 'kollaborate-transfer' do version '1.4.3.1' sha256 '65ba2983e9f39c39895dc7613cc7c2c27c6aa75a789c0aae2cb7b6bcc55f55b6' # digitalrebellion.com was verified as official when first introduced to the cask url "http://www.digitalrebellion.com/download/kollabtransfer?version=#{version.no_dots}" name 'Kollaborate Transfer' homepage 'https://www.kollaborate.tv/resources' app 'Kollaborate Transfer.app' zap delete: '~/Library/Preferences/com.digitalrebellion.KollabTransfer.plist' end
35.857143
90
0.796813
615f3f868ac71ce8fff55464211c496f37894ad7
2,906
# This file is copied to spec/ when you run 'rails generate rspec:install' ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) # Prevent database truncation if the environment is production abort("The Rails environment is running in production mode!") if Rails.env.production? require 'spec_helper' require 'rspec/rails' # Add additional requires below this line. Rails is not loaded until this point! # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are # run as spec files by default. This means that files in spec/support that end # in _spec.rb will both be required and run as specs, causing the specs to be # run twice. It is recommended that you do not name files matching this glob to # end with _spec.rb. You can configure this pattern with the --pattern # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. # # The following line is provided for convenience purposes. It has the downside # of increasing the boot-up time by auto-requiring all files in the support # directory. Alternatively, in the individual `*_spec.rb` files, manually # require only the support files necessary. # # Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } # Checks for pending migration and applies them before tests are run. # If you are not using ActiveRecord, you can remove this line. ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true # RSpec Rails can automatically mix in different behaviours to your tests # based on their file location, for example enabling you to call `get` and # `post` in specs under `spec/controllers`. # # You can disable this behaviour by removing the line below, and instead # explicitly tag your specs with their type, e.g.: # # RSpec.describe UsersController, :type => :controller do # # ... # end # # The different available types are documented in the features, such as in # https://relishapp.com/rspec/rspec-rails/docs config.infer_spec_type_from_file_location! # Filter lines from Rails gems in backtraces. config.filter_rails_from_backtrace! # arbitrary gems may also be filtered via: # config.filter_gems_from_backtrace("gem name") end Shoulda::Matchers.configure do |config| config.integrate do |with| # Choose a test framework: with.test_framework :rspec # Or, choose the following (which implies all of the above): with.library :rails end end
42.735294
86
0.746731
18542434981460502d660e3dbe498cfba04aab20
380
ActiveAdmin.register Item do permit_params :id, :name, :subcategory_id config.sort_order = 'id_asc' form do |f| f.semantic_errors(*f.object.errors.keys) f.inputs do f.input :name f.input :subcategory, as: :ajax_select, data: { search_fields: [:name], url: '/admin/subcategories/filter', limit: Subcategory::AJAX_LIMIT } end f.actions end end
25.333333
146
0.684211
18e5f84f202022269bc97ebaf1473dc32a8de6ee
381
require "bundler/setup" require "tn_congress" require "pry" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
23.8125
66
0.753281
086df6a9338165d40803e4889d2a97fc0b242eba
7,945
require File.dirname(__FILE__) + '/spec_helper' describe Sunlight::Legislator do before(:each) do Sunlight::Base.api_key = 'the_api_key' @example_hash = {"webform"=>"https://forms.house.gov/wyr/welcome.shtml", "title"=>"Rep", "nickname"=>"", "eventful_id"=>"P0-001-000016482-0", "district"=>"4", "congresspedia_url"=>"http://www.sourcewatch.org/index.php?title=Carolyn_McCarthy", "fec_id"=>"H6NY04112", "middlename"=>"", "gender"=>"F", "congress_office"=>"106 Cannon House Office Building", "lastname"=>"McCarthy", "crp_id"=>"N00001148", "bioguide_id"=>"M000309", "name_suffix"=>"", "phone"=>"202-225-5516", "firstname"=>"Carolyn", "govtrack_id"=>"400257", "fax"=>"202-225-5758", "website"=>"http://carolynmccarthy.house.gov/", "votesmart_id"=>"693", "sunlight_old_id"=>"fakeopenID252", "party"=>"D", "email"=>"", "state"=>"NY"} @jan = Sunlight::Legislator.new({"firstname" => "Jan", "district" => "Senior Seat", "title" => "Sen"}) @bob = Sunlight::Legislator.new({"firstname" => "Bob", "district" => "Junior Seat", "title" => "Sen"}) @tom = Sunlight::Legislator.new({"firstname" => "Tom", "district" => "4", "title" => "Rep"}) @example_legislators = {:senior_senator => @jan, :junior_senator => @bob, :representative => @tom} end describe "#initialize" do it "should create an object from a JSON parser-generated hash" do carolyn = Sunlight::Legislator.new(@example_hash) carolyn.should be_an_instance_of(Sunlight::Legislator) carolyn.firstname.should eql("Carolyn") end end describe "#youtube_id" do it "should return blank if youtube_url is nil" do @jan.youtube_id.should be nil end it "should return jansmith if youtube_url is http://www.youtube.com/jansmith" do @jan.youtube_url = "http://www.youtube.com/jansmith" @jan.youtube_id.should eql("jansmith") end it "should return jansmith if youtube_url is http://www.youtube.com/user/jansmith" do @jan.youtube_url = "http://www.youtube.com/user/jansmith" @jan.youtube_id.should eql("jansmith") end end describe "#committees" do it "should return an array of Committees with subarrays for subcommittees" do @example_committee = {"chamber" => "Joint", "id" => "JSPR", "name" => "Joint Committee on Printing", "members" => [{"legislator" => {"state" => "GA"}}], "subcommittees" => [{"committee" => {"chamber" => "Joint", "id" => "JSPR", "name" => "Subcommittee on Ink"}}]} Sunlight::Base.should_receive(:get_json_data).and_return({"response" => {"committees" => [{"committee" => @example_committee}]}}) carolyn = Sunlight::Legislator.new(@example_hash) comms = carolyn.committees comms.should be_an_instance_of(Array) comms[0].should be_an_instance_of(Sunlight::Committee) end it "should return nil if no committees are found" do Sunlight::Base.should_receive(:get_json_data).and_return(nil) carolyn = Sunlight::Legislator.new(@example_hash) comms = carolyn.committees comms.should be_nil end end describe "#all_for" do it "should return nil when junk is passed in" do legislators = Sunlight::Legislator.all_for(:bleh => 'blah') legislators.should be(nil) end it "should return hash when valid lat/long are passed in" do Sunlight::Legislator.should_receive(:all_in_district).and_return(@example_legislators) legislators = Sunlight::Legislator.all_for(:latitude => 33.876145, :longitude => -84.453789) legislators[:senior_senator].firstname.should eql('Jan') end it "should return hash when valid address is passed in" do Sunlight::Legislator.should_receive(:all_in_district).and_return(@example_legislators) legislators = Sunlight::Legislator.all_for(:address => "123 Fake St Anytown USA") legislators[:junior_senator].firstname.should eql('Bob') end end describe "#all_in_district" do it "should return has when valid District object is passed in" do Sunlight::Legislator.should_receive(:all_where).exactly(3).times.and_return([@jan]) legislators = Sunlight::Legislator.all_in_district(Sunlight::District.new("NJ", "7")) legislators.should be_an_instance_of(Hash) legislators[:senior_senator].firstname.should eql('Jan') end end describe "#all_where" do it "should return array when valid parameters passed in" do Sunlight::Legislator.should_receive(:get_json_data).and_return({"response"=>{"legislators"=>[{"legislator"=>{"state"=>"GA"}}]}}) legislators = Sunlight::Legislator.all_where(:firstname => "Susie") legislators.first.state.should eql('GA') end it "should return nil when unknown parameters passed in" do Sunlight::Legislator.should_receive(:get_json_data).and_return(nil) legislators = Sunlight::Legislator.all_where(:blah => "Blech") legislators.should be(nil) end end describe "#all_in_zipcode" do it "should return array when valid parameters passed in" do Sunlight::Legislator.should_receive(:get_json_data).and_return({"response"=>{"legislators"=>[{"legislator"=>{"state"=>"GA"}}]}}) legislators = Sunlight::Legislator.all_in_zipcode(:zip => "30339") legislators.first.state.should eql('GA') end it "should return nil when unknown parameters passed in" do Sunlight::Legislator.should_receive(:get_json_data).and_return(nil) legislators = Sunlight::Legislator.all_in_zipcode(:blah => "Blech") legislators.should be(nil) end end describe "#search_by_name" do it "should return array when probable match passed in with no threshold" do Sunlight::Legislator.should_receive(:get_json_data).and_return({"response"=>{"results"=>[{"result"=>{"score"=>"0.91", "legislator"=>{"firstname"=>"Edward"}}}]}}) legislators = Sunlight::Legislator.search_by_name("Teddy Kennedey") legislators.first.fuzzy_score.should eql(0.91) legislators.first.firstname.should eql('Edward') end it "should return an array when probable match passed in is over supplied threshold" do Sunlight::Legislator.should_receive(:get_json_data).and_return({"response"=>{"results"=>[{"result"=>{"score"=>"0.91", "legislator"=>{"firstname"=>"Edward"}}}]}}) legislators = Sunlight::Legislator.search_by_name("Teddy Kennedey", 0.9) legislators.first.fuzzy_score.should eql(0.91) legislators.first.firstname.should eql('Edward') end it "should return nil when probable match passed in but underneath supplied threshold" do Sunlight::Legislator.should_receive(:get_json_data).and_return({"response"=>{"results"=>[{"result"=>{"score"=>"0.91", "legislator"=>{"firstname"=>"Edward"}}}]}}) legislators = Sunlight::Legislator.search_by_name("Teddy Kennedey", 0.92) legislators.should be(nil) end it "should return nil when no probable match at all" do Sunlight::Legislator.should_receive(:get_json_data).and_return({"response"=>{"results"=>[]}}) legislators = Sunlight::Legislator.search_by_name("923jkfkj elkji") legislators.should be(nil) end it "should return nil on bad data" do Sunlight::Legislator.should_receive(:get_json_data).and_return(nil) legislators = Sunlight::Legislator.search_by_name("923jkfkj elkji","lkjd") legislators.should be(nil) end end end
41.815789
695
0.639773
282128ed46046c7c6932199fd0f928284b1c9959
265
require 'rails_helper' RSpec.describe "themes/show", type: :view do before(:each) do @theme = assign(:theme, Theme.create!( :title => "Title" )) end it "renders attributes in <p>" do render expect(rendered).to match(/Title/) end end
17.666667
44
0.626415
79d8f2dd0c735b61f1e46178010f50a6f1153bd7
1,275
# coding: utf-8 require File.expand_path('../lib/corefines/version', __FILE__) Gem::Specification.new do |s| s.name = 'corefines' s.version = Corefines::VERSION s.author = 'Jakub Jirutka' s.email = '[email protected]' s.homepage = 'https://github.com/jirutka/corefines' s.license = 'MIT' s.summary = 'A collection of refinements for Ruby core classes.' s.description = <<-EOS Corefines is a collection of general purpose refinements for extending the core capabilities of Ruby's built-in classes. It also provides a compatibility mode for older Ruby versions and alternative Ruby implementations that don't support refinements (yet). EOS begin s.files = `git ls-files -z -- */* {CHANGELOG,LICENSE,Rakefile,README}*`.split("\x0") rescue s.files = Dir['**/*'] end s.require_paths = ['lib'] s.required_ruby_version = '>= 1.9.3' s.add_development_dependency 'asciidoctor', '~> 1.5.0' # needed for yard s.add_development_dependency 'codeclimate-test-reporter', '~> 1.0' s.add_development_dependency 'rake', '~> 12.0' s.add_development_dependency 'rspec', '~> 3.1' s.add_development_dependency 'simplecov', '~> 0.9' s.add_development_dependency 'yard', '~> 0.9' end
34.459459
94
0.672941
38e977c6bd1308055d70456f984bb4a1575650ba
562
<% module_namespacing do -%> class CreateAuthenticationProviders < ActiveRecord::Migration[5.1] def change create_table "authentication_providers", :force => true do |t| t.string "name" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end add_index "authentication_providers", ["name"], :name => "index_name_on_authentication_providers" <% providers.each do |provider| -%> AuthenticationProvider.create(name: '<%= provider %>') <% end -%> end end <% end -%>
33.058824
101
0.637011
bb536825d6bfdb5901f0c1faf89f9370bd83d2f3
1,085
class NXOS < Oxidized::Model prompt /^(\r?[\w.@_()-]+[#]\s?)$/ comment '! ' def filter(cfg) cfg.gsub! /\r\n?/, "\n" cfg.gsub! prompt, '' end cmd :secret do |cfg| cfg.gsub! /^(snmp-server community).*/, '\\1 <configuration removed>' cfg.gsub! /^(snmp-server user (\S+) (\S+) auth (\S+)) (\S+) (priv) (\S+)/, '\\1 <configuration removed> ' cfg.gsub! /(password \d+) (\S+).*/, '\\1 <secret hidden>' cfg.gsub! /^(radius-server key).*/, '\\1 <secret hidden>' cfg end cmd 'show version' do |cfg| cfg = filter cfg cfg = cfg.each_line.take_while { |line| not line.match(/uptime/i) } comment cfg.join "" end cmd 'show inventory' do |cfg| cfg = filter cfg comment cfg end cmd 'show running-config' do |cfg| cfg = filter cfg cfg.gsub! /^(show run.*)$/, '! \1' cfg.gsub! /^!Time:[^\n]*\n/, '' cfg.gsub! /^[\w.@_()-]+[#].*$/, '' cfg end cfg :ssh, :telnet do post_login 'terminal length 0' pre_logout 'exit' end cfg :telnet do username /^login:/ password /^Password:/ end end
23.085106
109
0.541935
0899a5cc966fedeca4b58c622ee6592dfb61f239
1,101
class Vt < Formula # Tan_2015: "https://doi.org/10.1093/bioinformatics/btv112" desc "Toolset for short variant discovery from NGS data" homepage "https://genome.sph.umich.edu/wiki/Vt" url "https://github.com/atks/vt/archive/0.5772.tar.gz" sha256 "b147520478a2f7c536524511e48133d0360e88282c7159821813738ccbda97e7" license "MIT" revision 2 head "https://github.com/atks/vt.git" livecheck do url :stable strategy :github_latest end bottle do root_url "https://archive.org/download/brewsci/bottles-bio" sha256 cellar: :any, sierra: "43c34b6bf2d3209088a1e6ce61e37844ef3bbf08b871861214714ce10b18f707" sha256 cellar: :any, x86_64_linux: "a2f0c3b7e3078719d39b7d257d964f19d327e3a3638c9e1397d804588da811f6" end depends_on "gcc" if OS.mac? # Fix error: static_assert failed uses_from_macos "zlib" fails_with :clang # Fix error: static_assert failed def install system "make" system "test/test.sh" bin.install "vt" pkgshare.install "test" end test do assert_match "multi_partition", shell_output("#{bin}/vt 2>&1") end end
28.230769
105
0.737511
39402360b9ad36a01b19ac947a86924cf3cc03ed
160
class CreateMaterials < ActiveRecord::Migration[6.1] def change create_table :materials do |t| t.string :name t.timestamps end end end
16
52
0.66875
b9ea95df407a5a6c1ba084fca99ca3e7cd7916ca
73,970
# frozen_string_literal: true # WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE require 'seahorse/client/plugins/content_length.rb' require 'aws-sdk-core/plugins/credentials_configuration.rb' require 'aws-sdk-core/plugins/logging.rb' require 'aws-sdk-core/plugins/param_converter.rb' require 'aws-sdk-core/plugins/param_validator.rb' require 'aws-sdk-core/plugins/user_agent.rb' require 'aws-sdk-core/plugins/helpful_socket_errors.rb' require 'aws-sdk-core/plugins/retry_errors.rb' require 'aws-sdk-core/plugins/global_configuration.rb' require 'aws-sdk-core/plugins/regional_endpoint.rb' require 'aws-sdk-core/plugins/endpoint_discovery.rb' require 'aws-sdk-core/plugins/endpoint_pattern.rb' require 'aws-sdk-core/plugins/response_paging.rb' require 'aws-sdk-core/plugins/stub_responses.rb' require 'aws-sdk-core/plugins/idempotency_token.rb' require 'aws-sdk-core/plugins/jsonvalue_converter.rb' require 'aws-sdk-core/plugins/client_metrics_plugin.rb' require 'aws-sdk-core/plugins/client_metrics_send_plugin.rb' require 'aws-sdk-core/plugins/transfer_encoding.rb' require 'aws-sdk-core/plugins/http_checksum.rb' require 'aws-sdk-core/plugins/signature_v4.rb' require 'aws-sdk-core/plugins/protocols/json_rpc.rb' Aws::Plugins::GlobalConfiguration.add_identifier(:ssoadmin) module Aws::SSOAdmin # An API client for SSOAdmin. To construct a client, you need to configure a `:region` and `:credentials`. # # client = Aws::SSOAdmin::Client.new( # region: region_name, # credentials: credentials, # # ... # ) # # For details on configuring region and credentials see # the [developer guide](/sdk-for-ruby/v3/developer-guide/setup-config.html). # # See {#initialize} for a full list of supported configuration options. class Client < Seahorse::Client::Base include Aws::ClientStubs @identifier = :ssoadmin set_api(ClientApi::API) add_plugin(Seahorse::Client::Plugins::ContentLength) add_plugin(Aws::Plugins::CredentialsConfiguration) add_plugin(Aws::Plugins::Logging) add_plugin(Aws::Plugins::ParamConverter) add_plugin(Aws::Plugins::ParamValidator) add_plugin(Aws::Plugins::UserAgent) add_plugin(Aws::Plugins::HelpfulSocketErrors) add_plugin(Aws::Plugins::RetryErrors) add_plugin(Aws::Plugins::GlobalConfiguration) add_plugin(Aws::Plugins::RegionalEndpoint) add_plugin(Aws::Plugins::EndpointDiscovery) add_plugin(Aws::Plugins::EndpointPattern) add_plugin(Aws::Plugins::ResponsePaging) add_plugin(Aws::Plugins::StubResponses) add_plugin(Aws::Plugins::IdempotencyToken) add_plugin(Aws::Plugins::JsonvalueConverter) add_plugin(Aws::Plugins::ClientMetricsPlugin) add_plugin(Aws::Plugins::ClientMetricsSendPlugin) add_plugin(Aws::Plugins::TransferEncoding) add_plugin(Aws::Plugins::HttpChecksum) add_plugin(Aws::Plugins::SignatureV4) add_plugin(Aws::Plugins::Protocols::JsonRpc) # @overload initialize(options) # @param [Hash] options # @option options [required, Aws::CredentialProvider] :credentials # Your AWS credentials. This can be an instance of any one of the # following classes: # # * `Aws::Credentials` - Used for configuring static, non-refreshing # credentials. # # * `Aws::SharedCredentials` - Used for loading static credentials from a # shared file, such as `~/.aws/config`. # # * `Aws::AssumeRoleCredentials` - Used when you need to assume a role. # # * `Aws::AssumeRoleWebIdentityCredentials` - Used when you need to # assume a role after providing credentials via the web. # # * `Aws::SSOCredentials` - Used for loading credentials from AWS SSO using an # access token generated from `aws login`. # # * `Aws::ProcessCredentials` - Used for loading credentials from a # process that outputs to stdout. # # * `Aws::InstanceProfileCredentials` - Used for loading credentials # from an EC2 IMDS on an EC2 instance. # # * `Aws::ECSCredentials` - Used for loading credentials from # instances running in ECS. # # * `Aws::CognitoIdentityCredentials` - Used for loading credentials # from the Cognito Identity service. # # When `:credentials` are not configured directly, the following # locations will be searched for credentials: # # * `Aws.config[:credentials]` # * The `:access_key_id`, `:secret_access_key`, and `:session_token` options. # * ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'] # * `~/.aws/credentials` # * `~/.aws/config` # * EC2/ECS IMDS instance profile - When used by default, the timeouts # are very aggressive. Construct and pass an instance of # `Aws::InstanceProfileCredentails` or `Aws::ECSCredentials` to # enable retries and extended timeouts. # # @option options [required, String] :region # The AWS region to connect to. The configured `:region` is # used to determine the service `:endpoint`. When not passed, # a default `:region` is searched for in the following locations: # # * `Aws.config[:region]` # * `ENV['AWS_REGION']` # * `ENV['AMAZON_REGION']` # * `ENV['AWS_DEFAULT_REGION']` # * `~/.aws/credentials` # * `~/.aws/config` # # @option options [String] :access_key_id # # @option options [Boolean] :active_endpoint_cache (false) # When set to `true`, a thread polling for endpoints will be running in # the background every 60 secs (default). Defaults to `false`. # # @option options [Boolean] :adaptive_retry_wait_to_fill (true) # Used only in `adaptive` retry mode. When true, the request will sleep # until there is sufficent client side capacity to retry the request. # When false, the request will raise a `RetryCapacityNotAvailableError` and will # not retry instead of sleeping. # # @option options [Boolean] :client_side_monitoring (false) # When `true`, client-side metrics will be collected for all API requests from # this client. # # @option options [String] :client_side_monitoring_client_id ("") # Allows you to provide an identifier for this client which will be attached to # all generated client side metrics. Defaults to an empty string. # # @option options [String] :client_side_monitoring_host ("127.0.0.1") # Allows you to specify the DNS hostname or IPv4 or IPv6 address that the client # side monitoring agent is running on, where client metrics will be published via UDP. # # @option options [Integer] :client_side_monitoring_port (31000) # Required for publishing client metrics. The port that the client side monitoring # agent is running on, where client metrics will be published via UDP. # # @option options [Aws::ClientSideMonitoring::Publisher] :client_side_monitoring_publisher (Aws::ClientSideMonitoring::Publisher) # Allows you to provide a custom client-side monitoring publisher class. By default, # will use the Client Side Monitoring Agent Publisher. # # @option options [Boolean] :convert_params (true) # When `true`, an attempt is made to coerce request parameters into # the required types. # # @option options [Boolean] :correct_clock_skew (true) # Used only in `standard` and adaptive retry modes. Specifies whether to apply # a clock skew correction and retry requests with skewed client clocks. # # @option options [Boolean] :disable_host_prefix_injection (false) # Set to true to disable SDK automatically adding host prefix # to default service endpoint when available. # # @option options [String] :endpoint # The client endpoint is normally constructed from the `:region` # option. You should only configure an `:endpoint` when connecting # to test or custom endpoints. This should be a valid HTTP(S) URI. # # @option options [Integer] :endpoint_cache_max_entries (1000) # Used for the maximum size limit of the LRU cache storing endpoints data # for endpoint discovery enabled operations. Defaults to 1000. # # @option options [Integer] :endpoint_cache_max_threads (10) # Used for the maximum threads in use for polling endpoints to be cached, defaults to 10. # # @option options [Integer] :endpoint_cache_poll_interval (60) # When :endpoint_discovery and :active_endpoint_cache is enabled, # Use this option to config the time interval in seconds for making # requests fetching endpoints information. Defaults to 60 sec. # # @option options [Boolean] :endpoint_discovery (false) # When set to `true`, endpoint discovery will be enabled for operations when available. # # @option options [Aws::Log::Formatter] :log_formatter (Aws::Log::Formatter.default) # The log formatter. # # @option options [Symbol] :log_level (:info) # The log level to send messages to the `:logger` at. # # @option options [Logger] :logger # The Logger instance to send log messages to. If this option # is not set, logging will be disabled. # # @option options [Integer] :max_attempts (3) # An integer representing the maximum number attempts that will be made for # a single request, including the initial attempt. For example, # setting this value to 5 will result in a request being retried up to # 4 times. Used in `standard` and `adaptive` retry modes. # # @option options [String] :profile ("default") # Used when loading credentials from the shared credentials file # at HOME/.aws/credentials. When not specified, 'default' is used. # # @option options [Proc] :retry_backoff # A proc or lambda used for backoff. Defaults to 2**retries * retry_base_delay. # This option is only used in the `legacy` retry mode. # # @option options [Float] :retry_base_delay (0.3) # The base delay in seconds used by the default backoff function. This option # is only used in the `legacy` retry mode. # # @option options [Symbol] :retry_jitter (:none) # A delay randomiser function used by the default backoff function. # Some predefined functions can be referenced by name - :none, :equal, :full, # otherwise a Proc that takes and returns a number. This option is only used # in the `legacy` retry mode. # # @see https://www.awsarchitectureblog.com/2015/03/backoff.html # # @option options [Integer] :retry_limit (3) # The maximum number of times to retry failed requests. Only # ~ 500 level server errors and certain ~ 400 level client errors # are retried. Generally, these are throttling errors, data # checksum errors, networking errors, timeout errors, auth errors, # endpoint discovery, and errors from expired credentials. # This option is only used in the `legacy` retry mode. # # @option options [Integer] :retry_max_delay (0) # The maximum number of seconds to delay between retries (0 for no limit) # used by the default backoff function. This option is only used in the # `legacy` retry mode. # # @option options [String] :retry_mode ("legacy") # Specifies which retry algorithm to use. Values are: # # * `legacy` - The pre-existing retry behavior. This is default value if # no retry mode is provided. # # * `standard` - A standardized set of retry rules across the AWS SDKs. # This includes support for retry quotas, which limit the number of # unsuccessful retries a client can make. # # * `adaptive` - An experimental retry mode that includes all the # functionality of `standard` mode along with automatic client side # throttling. This is a provisional mode that may change behavior # in the future. # # # @option options [String] :secret_access_key # # @option options [String] :session_token # # @option options [Boolean] :simple_json (false) # Disables request parameter conversion, validation, and formatting. # Also disable response data type conversions. This option is useful # when you want to ensure the highest level of performance by # avoiding overhead of walking request parameters and response data # structures. # # When `:simple_json` is enabled, the request parameters hash must # be formatted exactly as the DynamoDB API expects. # # @option options [Boolean] :stub_responses (false) # Causes the client to return stubbed responses. By default # fake responses are generated and returned. You can specify # the response data to return or errors to raise by calling # {ClientStubs#stub_responses}. See {ClientStubs} for more information. # # ** Please note ** When response stubbing is enabled, no HTTP # requests are made, and retries are disabled. # # @option options [Boolean] :validate_params (true) # When `true`, request parameters are validated before # sending the request. # # @option options [URI::HTTP,String] :http_proxy A proxy to send # requests through. Formatted like 'http://proxy.com:123'. # # @option options [Float] :http_open_timeout (15) The number of # seconds to wait when opening a HTTP session before raising a # `Timeout::Error`. # # @option options [Integer] :http_read_timeout (60) The default # number of seconds to wait for response data. This value can # safely be set per-request on the session. # # @option options [Float] :http_idle_timeout (5) The number of # seconds a connection is allowed to sit idle before it is # considered stale. Stale connections are closed and removed # from the pool before making a request. # # @option options [Float] :http_continue_timeout (1) The number of # seconds to wait for a 100-continue response before sending the # request body. This option has no effect unless the request has # "Expect" header set to "100-continue". Defaults to `nil` which # disables this behaviour. This value can safely be set per # request on the session. # # @option options [Boolean] :http_wire_trace (false) When `true`, # HTTP debug output will be sent to the `:logger`. # # @option options [Boolean] :ssl_verify_peer (true) When `true`, # SSL peer certificates are verified when establishing a # connection. # # @option options [String] :ssl_ca_bundle Full path to the SSL # certificate authority bundle file that should be used when # verifying peer certificates. If you do not pass # `:ssl_ca_bundle` or `:ssl_ca_directory` the the system default # will be used if available. # # @option options [String] :ssl_ca_directory Full path of the # directory that contains the unbundled SSL certificate # authority files for verifying peer certificates. If you do # not pass `:ssl_ca_bundle` or `:ssl_ca_directory` the the # system default will be used if available. # def initialize(*args) super end # @!group API Operations # Attaches an IAM managed policy ARN to a permission set. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :permission_set_arn # The ARN of the PermissionSet that the managed policy should be # attached to. # # @option params [required, String] :managed_policy_arn # The IAM managed policy ARN to be attached to a permission set. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.attach_managed_policy_to_permission_set({ # instance_arn: "InstanceArn", # required # permission_set_arn: "PermissionSetArn", # required # managed_policy_arn: "ManagedPolicyArn", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/AttachManagedPolicyToPermissionSet AWS API Documentation # # @overload attach_managed_policy_to_permission_set(params = {}) # @param [Hash] params ({}) def attach_managed_policy_to_permission_set(params = {}, options = {}) req = build_request(:attach_managed_policy_to_permission_set, params) req.send_request(options) end # Assigns access to a principal for a specified AWS account using a # specified permission set. # # <note markdown="1"> The term *principal* here refers to a user or group that is defined in # AWS SSO. # # </note> # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :target_id # The identifier for the chosen target. # # @option params [required, String] :target_type # The entity type for which the assignment will be created. # # @option params [required, String] :permission_set_arn # The ARN of the permission set that the admin wants to grant the # principal access to. # # @option params [required, String] :principal_type # The entity type for which the assignment will be created. # # @option params [required, String] :principal_id # The identifier of the principal. # # @return [Types::CreateAccountAssignmentResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::CreateAccountAssignmentResponse#account_assignment_creation_status #account_assignment_creation_status} => Types::AccountAssignmentOperationStatus # # @example Request syntax with placeholder values # # resp = client.create_account_assignment({ # instance_arn: "InstanceArn", # required # target_id: "TargetId", # required # target_type: "AWS_ACCOUNT", # required, accepts AWS_ACCOUNT # permission_set_arn: "PermissionSetArn", # required # principal_type: "USER", # required, accepts USER, GROUP # principal_id: "PrincipalId", # required # }) # # @example Response structure # # resp.account_assignment_creation_status.status #=> String, one of "IN_PROGRESS", "FAILED", "SUCCEEDED" # resp.account_assignment_creation_status.request_id #=> String # resp.account_assignment_creation_status.failure_reason #=> String # resp.account_assignment_creation_status.target_id #=> String # resp.account_assignment_creation_status.target_type #=> String, one of "AWS_ACCOUNT" # resp.account_assignment_creation_status.permission_set_arn #=> String # resp.account_assignment_creation_status.principal_type #=> String, one of "USER", "GROUP" # resp.account_assignment_creation_status.principal_id #=> String # resp.account_assignment_creation_status.created_date #=> Time # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/CreateAccountAssignment AWS API Documentation # # @overload create_account_assignment(params = {}) # @param [Hash] params ({}) def create_account_assignment(params = {}, options = {}) req = build_request(:create_account_assignment, params) req.send_request(options) end # Creates a permission set within a specified SSO instance. # # @option params [required, String] :name # The name of the PermissionSet. # # @option params [String] :description # The description of the PermissionSet. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [String] :session_duration # The length of time that the application user sessions are valid in the # ISO-8601 standard. # # @option params [String] :relay_state # Used to redirect users within the application during the federation # authentication process. # # @option params [Array<Types::Tag>] :tags # The tags to attach to the new PermissionSet. # # @return [Types::CreatePermissionSetResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::CreatePermissionSetResponse#permission_set #permission_set} => Types::PermissionSet # # @example Request syntax with placeholder values # # resp = client.create_permission_set({ # name: "PermissionSetName", # required # description: "PermissionSetDescription", # instance_arn: "InstanceArn", # required # session_duration: "Duration", # relay_state: "RelayState", # tags: [ # { # key: "TagKey", # value: "TagValue", # }, # ], # }) # # @example Response structure # # resp.permission_set.name #=> String # resp.permission_set.permission_set_arn #=> String # resp.permission_set.description #=> String # resp.permission_set.created_date #=> Time # resp.permission_set.session_duration #=> String # resp.permission_set.relay_state #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/CreatePermissionSet AWS API Documentation # # @overload create_permission_set(params = {}) # @param [Hash] params ({}) def create_permission_set(params = {}, options = {}) req = build_request(:create_permission_set, params) req.send_request(options) end # Deletes a principal's access from a specified AWS account using a # specified permission set. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :target_id # The identifier for the chosen target. # # @option params [required, String] :target_type # The entity type for which the assignment will be deleted. # # @option params [required, String] :permission_set_arn # The ARN of the permission set that will be used to remove access. # # @option params [required, String] :principal_type # The entity type for which the assignment will be deleted. # # @option params [required, String] :principal_id # The identifier of the principal. # # @return [Types::DeleteAccountAssignmentResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::DeleteAccountAssignmentResponse#account_assignment_deletion_status #account_assignment_deletion_status} => Types::AccountAssignmentOperationStatus # # @example Request syntax with placeholder values # # resp = client.delete_account_assignment({ # instance_arn: "InstanceArn", # required # target_id: "TargetId", # required # target_type: "AWS_ACCOUNT", # required, accepts AWS_ACCOUNT # permission_set_arn: "PermissionSetArn", # required # principal_type: "USER", # required, accepts USER, GROUP # principal_id: "PrincipalId", # required # }) # # @example Response structure # # resp.account_assignment_deletion_status.status #=> String, one of "IN_PROGRESS", "FAILED", "SUCCEEDED" # resp.account_assignment_deletion_status.request_id #=> String # resp.account_assignment_deletion_status.failure_reason #=> String # resp.account_assignment_deletion_status.target_id #=> String # resp.account_assignment_deletion_status.target_type #=> String, one of "AWS_ACCOUNT" # resp.account_assignment_deletion_status.permission_set_arn #=> String # resp.account_assignment_deletion_status.principal_type #=> String, one of "USER", "GROUP" # resp.account_assignment_deletion_status.principal_id #=> String # resp.account_assignment_deletion_status.created_date #=> Time # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/DeleteAccountAssignment AWS API Documentation # # @overload delete_account_assignment(params = {}) # @param [Hash] params ({}) def delete_account_assignment(params = {}, options = {}) req = build_request(:delete_account_assignment, params) req.send_request(options) end # Deletes the inline policy from a specified permission set. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :permission_set_arn # The ARN of the permission set that will be used to remove access. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.delete_inline_policy_from_permission_set({ # instance_arn: "InstanceArn", # required # permission_set_arn: "PermissionSetArn", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/DeleteInlinePolicyFromPermissionSet AWS API Documentation # # @overload delete_inline_policy_from_permission_set(params = {}) # @param [Hash] params ({}) def delete_inline_policy_from_permission_set(params = {}, options = {}) req = build_request(:delete_inline_policy_from_permission_set, params) req.send_request(options) end # Deletes the specified permission set. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :permission_set_arn # The ARN of the permission set that should be deleted. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.delete_permission_set({ # instance_arn: "InstanceArn", # required # permission_set_arn: "PermissionSetArn", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/DeletePermissionSet AWS API Documentation # # @overload delete_permission_set(params = {}) # @param [Hash] params ({}) def delete_permission_set(params = {}, options = {}) req = build_request(:delete_permission_set, params) req.send_request(options) end # Describes the status of the assignment creation request. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :account_assignment_creation_request_id # The identifier that is used to track the request operation progress. # # @return [Types::DescribeAccountAssignmentCreationStatusResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::DescribeAccountAssignmentCreationStatusResponse#account_assignment_creation_status #account_assignment_creation_status} => Types::AccountAssignmentOperationStatus # # @example Request syntax with placeholder values # # resp = client.describe_account_assignment_creation_status({ # instance_arn: "InstanceArn", # required # account_assignment_creation_request_id: "UUId", # required # }) # # @example Response structure # # resp.account_assignment_creation_status.status #=> String, one of "IN_PROGRESS", "FAILED", "SUCCEEDED" # resp.account_assignment_creation_status.request_id #=> String # resp.account_assignment_creation_status.failure_reason #=> String # resp.account_assignment_creation_status.target_id #=> String # resp.account_assignment_creation_status.target_type #=> String, one of "AWS_ACCOUNT" # resp.account_assignment_creation_status.permission_set_arn #=> String # resp.account_assignment_creation_status.principal_type #=> String, one of "USER", "GROUP" # resp.account_assignment_creation_status.principal_id #=> String # resp.account_assignment_creation_status.created_date #=> Time # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/DescribeAccountAssignmentCreationStatus AWS API Documentation # # @overload describe_account_assignment_creation_status(params = {}) # @param [Hash] params ({}) def describe_account_assignment_creation_status(params = {}, options = {}) req = build_request(:describe_account_assignment_creation_status, params) req.send_request(options) end # Describes the status of the assignment deletion request. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :account_assignment_deletion_request_id # The identifier that is used to track the request operation progress. # # @return [Types::DescribeAccountAssignmentDeletionStatusResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::DescribeAccountAssignmentDeletionStatusResponse#account_assignment_deletion_status #account_assignment_deletion_status} => Types::AccountAssignmentOperationStatus # # @example Request syntax with placeholder values # # resp = client.describe_account_assignment_deletion_status({ # instance_arn: "InstanceArn", # required # account_assignment_deletion_request_id: "UUId", # required # }) # # @example Response structure # # resp.account_assignment_deletion_status.status #=> String, one of "IN_PROGRESS", "FAILED", "SUCCEEDED" # resp.account_assignment_deletion_status.request_id #=> String # resp.account_assignment_deletion_status.failure_reason #=> String # resp.account_assignment_deletion_status.target_id #=> String # resp.account_assignment_deletion_status.target_type #=> String, one of "AWS_ACCOUNT" # resp.account_assignment_deletion_status.permission_set_arn #=> String # resp.account_assignment_deletion_status.principal_type #=> String, one of "USER", "GROUP" # resp.account_assignment_deletion_status.principal_id #=> String # resp.account_assignment_deletion_status.created_date #=> Time # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/DescribeAccountAssignmentDeletionStatus AWS API Documentation # # @overload describe_account_assignment_deletion_status(params = {}) # @param [Hash] params ({}) def describe_account_assignment_deletion_status(params = {}, options = {}) req = build_request(:describe_account_assignment_deletion_status, params) req.send_request(options) end # Gets the details of the permission set. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :permission_set_arn # The ARN of the permission set. # # @return [Types::DescribePermissionSetResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::DescribePermissionSetResponse#permission_set #permission_set} => Types::PermissionSet # # @example Request syntax with placeholder values # # resp = client.describe_permission_set({ # instance_arn: "InstanceArn", # required # permission_set_arn: "PermissionSetArn", # required # }) # # @example Response structure # # resp.permission_set.name #=> String # resp.permission_set.permission_set_arn #=> String # resp.permission_set.description #=> String # resp.permission_set.created_date #=> Time # resp.permission_set.session_duration #=> String # resp.permission_set.relay_state #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/DescribePermissionSet AWS API Documentation # # @overload describe_permission_set(params = {}) # @param [Hash] params ({}) def describe_permission_set(params = {}, options = {}) req = build_request(:describe_permission_set, params) req.send_request(options) end # Describes the status for the given permission set provisioning # request. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :provision_permission_set_request_id # The identifier that is provided by the ProvisionPermissionSet call to # retrieve the current status of the provisioning workflow. # # @return [Types::DescribePermissionSetProvisioningStatusResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::DescribePermissionSetProvisioningStatusResponse#permission_set_provisioning_status #permission_set_provisioning_status} => Types::PermissionSetProvisioningStatus # # @example Request syntax with placeholder values # # resp = client.describe_permission_set_provisioning_status({ # instance_arn: "InstanceArn", # required # provision_permission_set_request_id: "UUId", # required # }) # # @example Response structure # # resp.permission_set_provisioning_status.status #=> String, one of "IN_PROGRESS", "FAILED", "SUCCEEDED" # resp.permission_set_provisioning_status.request_id #=> String # resp.permission_set_provisioning_status.account_id #=> String # resp.permission_set_provisioning_status.permission_set_arn #=> String # resp.permission_set_provisioning_status.failure_reason #=> String # resp.permission_set_provisioning_status.created_date #=> Time # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/DescribePermissionSetProvisioningStatus AWS API Documentation # # @overload describe_permission_set_provisioning_status(params = {}) # @param [Hash] params ({}) def describe_permission_set_provisioning_status(params = {}, options = {}) req = build_request(:describe_permission_set_provisioning_status, params) req.send_request(options) end # Detaches the attached IAM managed policy ARN from the specified # permission set. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :permission_set_arn # The ARN of the PermissionSet from which the policy should be detached. # # @option params [required, String] :managed_policy_arn # The IAM managed policy ARN to be attached to a permission set. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.detach_managed_policy_from_permission_set({ # instance_arn: "InstanceArn", # required # permission_set_arn: "PermissionSetArn", # required # managed_policy_arn: "ManagedPolicyArn", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/DetachManagedPolicyFromPermissionSet AWS API Documentation # # @overload detach_managed_policy_from_permission_set(params = {}) # @param [Hash] params ({}) def detach_managed_policy_from_permission_set(params = {}, options = {}) req = build_request(:detach_managed_policy_from_permission_set, params) req.send_request(options) end # Obtains the inline policy assigned to the permission set. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :permission_set_arn # The ARN of the permission set. # # @return [Types::GetInlinePolicyForPermissionSetResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::GetInlinePolicyForPermissionSetResponse#inline_policy #inline_policy} => String # # @example Request syntax with placeholder values # # resp = client.get_inline_policy_for_permission_set({ # instance_arn: "InstanceArn", # required # permission_set_arn: "PermissionSetArn", # required # }) # # @example Response structure # # resp.inline_policy #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/GetInlinePolicyForPermissionSet AWS API Documentation # # @overload get_inline_policy_for_permission_set(params = {}) # @param [Hash] params ({}) def get_inline_policy_for_permission_set(params = {}, options = {}) req = build_request(:get_inline_policy_for_permission_set, params) req.send_request(options) end # Lists the status of the AWS account assignment creation requests for a # specified SSO instance. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [Integer] :max_results # The maximum number of results to display for the assignment. # # @option params [String] :next_token # The pagination token for the list API. Initially the value is null. # Use the output of previous API calls to make subsequent calls. # # @option params [Types::OperationStatusFilter] :filter # Filters results based on the passed attribute value. # # @return [Types::ListAccountAssignmentCreationStatusResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListAccountAssignmentCreationStatusResponse#account_assignments_creation_status #account_assignments_creation_status} => Array&lt;Types::AccountAssignmentOperationStatusMetadata&gt; # * {Types::ListAccountAssignmentCreationStatusResponse#next_token #next_token} => String # # The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}. # # @example Request syntax with placeholder values # # resp = client.list_account_assignment_creation_status({ # instance_arn: "InstanceArn", # required # max_results: 1, # next_token: "Token", # filter: { # status: "IN_PROGRESS", # accepts IN_PROGRESS, FAILED, SUCCEEDED # }, # }) # # @example Response structure # # resp.account_assignments_creation_status #=> Array # resp.account_assignments_creation_status[0].status #=> String, one of "IN_PROGRESS", "FAILED", "SUCCEEDED" # resp.account_assignments_creation_status[0].request_id #=> String # resp.account_assignments_creation_status[0].created_date #=> Time # resp.next_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/ListAccountAssignmentCreationStatus AWS API Documentation # # @overload list_account_assignment_creation_status(params = {}) # @param [Hash] params ({}) def list_account_assignment_creation_status(params = {}, options = {}) req = build_request(:list_account_assignment_creation_status, params) req.send_request(options) end # Lists the status of the AWS account assignment deletion requests for a # specified SSO instance. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [Integer] :max_results # The maximum number of results to display for the assignment. # # @option params [String] :next_token # The pagination token for the list API. Initially the value is null. # Use the output of previous API calls to make subsequent calls. # # @option params [Types::OperationStatusFilter] :filter # Filters results based on the passed attribute value. # # @return [Types::ListAccountAssignmentDeletionStatusResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListAccountAssignmentDeletionStatusResponse#account_assignments_deletion_status #account_assignments_deletion_status} => Array&lt;Types::AccountAssignmentOperationStatusMetadata&gt; # * {Types::ListAccountAssignmentDeletionStatusResponse#next_token #next_token} => String # # The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}. # # @example Request syntax with placeholder values # # resp = client.list_account_assignment_deletion_status({ # instance_arn: "InstanceArn", # required # max_results: 1, # next_token: "Token", # filter: { # status: "IN_PROGRESS", # accepts IN_PROGRESS, FAILED, SUCCEEDED # }, # }) # # @example Response structure # # resp.account_assignments_deletion_status #=> Array # resp.account_assignments_deletion_status[0].status #=> String, one of "IN_PROGRESS", "FAILED", "SUCCEEDED" # resp.account_assignments_deletion_status[0].request_id #=> String # resp.account_assignments_deletion_status[0].created_date #=> Time # resp.next_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/ListAccountAssignmentDeletionStatus AWS API Documentation # # @overload list_account_assignment_deletion_status(params = {}) # @param [Hash] params ({}) def list_account_assignment_deletion_status(params = {}, options = {}) req = build_request(:list_account_assignment_deletion_status, params) req.send_request(options) end # Lists the assignee of the specified AWS account with the specified # permission set. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :account_id # The identifier of the AWS account from which to list the assignments. # # @option params [required, String] :permission_set_arn # The ARN of the permission set from which to list assignments. # # @option params [Integer] :max_results # The maximum number of results to display for the assignment. # # @option params [String] :next_token # The pagination token for the list API. Initially the value is null. # Use the output of previous API calls to make subsequent calls. # # @return [Types::ListAccountAssignmentsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListAccountAssignmentsResponse#account_assignments #account_assignments} => Array&lt;Types::AccountAssignment&gt; # * {Types::ListAccountAssignmentsResponse#next_token #next_token} => String # # The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}. # # @example Request syntax with placeholder values # # resp = client.list_account_assignments({ # instance_arn: "InstanceArn", # required # account_id: "TargetId", # required # permission_set_arn: "PermissionSetArn", # required # max_results: 1, # next_token: "Token", # }) # # @example Response structure # # resp.account_assignments #=> Array # resp.account_assignments[0].account_id #=> String # resp.account_assignments[0].permission_set_arn #=> String # resp.account_assignments[0].principal_type #=> String, one of "USER", "GROUP" # resp.account_assignments[0].principal_id #=> String # resp.next_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/ListAccountAssignments AWS API Documentation # # @overload list_account_assignments(params = {}) # @param [Hash] params ({}) def list_account_assignments(params = {}, options = {}) req = build_request(:list_account_assignments, params) req.send_request(options) end # Lists all the AWS accounts where the specified permission set is # provisioned. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :permission_set_arn # The ARN of the PermissionSet from which the associated AWS accounts # will be listed. # # @option params [String] :provisioning_status # The permission set provisioning status for an AWS account. # # @option params [Integer] :max_results # The maximum number of results to display for the PermissionSet. # # @option params [String] :next_token # The pagination token for the list API. Initially the value is null. # Use the output of previous API calls to make subsequent calls. # # @return [Types::ListAccountsForProvisionedPermissionSetResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListAccountsForProvisionedPermissionSetResponse#account_ids #account_ids} => Array&lt;String&gt; # * {Types::ListAccountsForProvisionedPermissionSetResponse#next_token #next_token} => String # # The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}. # # @example Request syntax with placeholder values # # resp = client.list_accounts_for_provisioned_permission_set({ # instance_arn: "InstanceArn", # required # permission_set_arn: "PermissionSetArn", # required # provisioning_status: "LATEST_PERMISSION_SET_PROVISIONED", # accepts LATEST_PERMISSION_SET_PROVISIONED, LATEST_PERMISSION_SET_NOT_PROVISIONED # max_results: 1, # next_token: "Token", # }) # # @example Response structure # # resp.account_ids #=> Array # resp.account_ids[0] #=> String # resp.next_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/ListAccountsForProvisionedPermissionSet AWS API Documentation # # @overload list_accounts_for_provisioned_permission_set(params = {}) # @param [Hash] params ({}) def list_accounts_for_provisioned_permission_set(params = {}, options = {}) req = build_request(:list_accounts_for_provisioned_permission_set, params) req.send_request(options) end # Lists the SSO instances that the caller has access to. # # @option params [Integer] :max_results # The maximum number of results to display for the instance. # # @option params [String] :next_token # The pagination token for the list API. Initially the value is null. # Use the output of previous API calls to make subsequent calls. # # @return [Types::ListInstancesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListInstancesResponse#instances #instances} => Array&lt;Types::InstanceMetadata&gt; # * {Types::ListInstancesResponse#next_token #next_token} => String # # The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}. # # @example Request syntax with placeholder values # # resp = client.list_instances({ # max_results: 1, # next_token: "Token", # }) # # @example Response structure # # resp.instances #=> Array # resp.instances[0].instance_arn #=> String # resp.instances[0].identity_store_id #=> String # resp.next_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/ListInstances AWS API Documentation # # @overload list_instances(params = {}) # @param [Hash] params ({}) def list_instances(params = {}, options = {}) req = build_request(:list_instances, params) req.send_request(options) end # Lists the IAM managed policy that is attached to a specified # permission set. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :permission_set_arn # The ARN of the PermissionSet whose managed policies will be listed. # # @option params [Integer] :max_results # The maximum number of results to display for the PermissionSet. # # @option params [String] :next_token # The pagination token for the list API. Initially the value is null. # Use the output of previous API calls to make subsequent calls. # # @return [Types::ListManagedPoliciesInPermissionSetResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListManagedPoliciesInPermissionSetResponse#attached_managed_policies #attached_managed_policies} => Array&lt;Types::AttachedManagedPolicy&gt; # * {Types::ListManagedPoliciesInPermissionSetResponse#next_token #next_token} => String # # The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}. # # @example Request syntax with placeholder values # # resp = client.list_managed_policies_in_permission_set({ # instance_arn: "InstanceArn", # required # permission_set_arn: "PermissionSetArn", # required # max_results: 1, # next_token: "Token", # }) # # @example Response structure # # resp.attached_managed_policies #=> Array # resp.attached_managed_policies[0].name #=> String # resp.attached_managed_policies[0].arn #=> String # resp.next_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/ListManagedPoliciesInPermissionSet AWS API Documentation # # @overload list_managed_policies_in_permission_set(params = {}) # @param [Hash] params ({}) def list_managed_policies_in_permission_set(params = {}, options = {}) req = build_request(:list_managed_policies_in_permission_set, params) req.send_request(options) end # Lists the status of the permission set provisioning requests for a # specified SSO instance. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [Integer] :max_results # The maximum number of results to display for the assignment. # # @option params [String] :next_token # The pagination token for the list API. Initially the value is null. # Use the output of previous API calls to make subsequent calls. # # @option params [Types::OperationStatusFilter] :filter # Filters results based on the passed attribute value. # # @return [Types::ListPermissionSetProvisioningStatusResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListPermissionSetProvisioningStatusResponse#permission_sets_provisioning_status #permission_sets_provisioning_status} => Array&lt;Types::PermissionSetProvisioningStatusMetadata&gt; # * {Types::ListPermissionSetProvisioningStatusResponse#next_token #next_token} => String # # The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}. # # @example Request syntax with placeholder values # # resp = client.list_permission_set_provisioning_status({ # instance_arn: "InstanceArn", # required # max_results: 1, # next_token: "Token", # filter: { # status: "IN_PROGRESS", # accepts IN_PROGRESS, FAILED, SUCCEEDED # }, # }) # # @example Response structure # # resp.permission_sets_provisioning_status #=> Array # resp.permission_sets_provisioning_status[0].status #=> String, one of "IN_PROGRESS", "FAILED", "SUCCEEDED" # resp.permission_sets_provisioning_status[0].request_id #=> String # resp.permission_sets_provisioning_status[0].created_date #=> Time # resp.next_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/ListPermissionSetProvisioningStatus AWS API Documentation # # @overload list_permission_set_provisioning_status(params = {}) # @param [Hash] params ({}) def list_permission_set_provisioning_status(params = {}, options = {}) req = build_request(:list_permission_set_provisioning_status, params) req.send_request(options) end # Lists the PermissionSets in an SSO instance. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [String] :next_token # The pagination token for the list API. Initially the value is null. # Use the output of previous API calls to make subsequent calls. # # @option params [Integer] :max_results # The maximum number of results to display for the assignment. # # @return [Types::ListPermissionSetsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListPermissionSetsResponse#permission_sets #permission_sets} => Array&lt;String&gt; # * {Types::ListPermissionSetsResponse#next_token #next_token} => String # # The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}. # # @example Request syntax with placeholder values # # resp = client.list_permission_sets({ # instance_arn: "InstanceArn", # required # next_token: "Token", # max_results: 1, # }) # # @example Response structure # # resp.permission_sets #=> Array # resp.permission_sets[0] #=> String # resp.next_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/ListPermissionSets AWS API Documentation # # @overload list_permission_sets(params = {}) # @param [Hash] params ({}) def list_permission_sets(params = {}, options = {}) req = build_request(:list_permission_sets, params) req.send_request(options) end # Lists all the permission sets that are provisioned to a specified AWS # account. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :account_id # The identifier of the AWS account from which to list the assignments. # # @option params [String] :provisioning_status # The status object for the permission set provisioning operation. # # @option params [Integer] :max_results # The maximum number of results to display for the assignment. # # @option params [String] :next_token # The pagination token for the list API. Initially the value is null. # Use the output of previous API calls to make subsequent calls. # # @return [Types::ListPermissionSetsProvisionedToAccountResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListPermissionSetsProvisionedToAccountResponse#next_token #next_token} => String # * {Types::ListPermissionSetsProvisionedToAccountResponse#permission_sets #permission_sets} => Array&lt;String&gt; # # The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}. # # @example Request syntax with placeholder values # # resp = client.list_permission_sets_provisioned_to_account({ # instance_arn: "InstanceArn", # required # account_id: "AccountId", # required # provisioning_status: "LATEST_PERMISSION_SET_PROVISIONED", # accepts LATEST_PERMISSION_SET_PROVISIONED, LATEST_PERMISSION_SET_NOT_PROVISIONED # max_results: 1, # next_token: "Token", # }) # # @example Response structure # # resp.next_token #=> String # resp.permission_sets #=> Array # resp.permission_sets[0] #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/ListPermissionSetsProvisionedToAccount AWS API Documentation # # @overload list_permission_sets_provisioned_to_account(params = {}) # @param [Hash] params ({}) def list_permission_sets_provisioned_to_account(params = {}, options = {}) req = build_request(:list_permission_sets_provisioned_to_account, params) req.send_request(options) end # Lists the tags that are attached to a specified resource. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :resource_arn # The ARN of the resource with the tags to be listed. # # @option params [String] :next_token # The pagination token for the list API. Initially the value is null. # Use the output of previous API calls to make subsequent calls. # # @return [Types::ListTagsForResourceResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ListTagsForResourceResponse#tags #tags} => Array&lt;Types::Tag&gt; # * {Types::ListTagsForResourceResponse#next_token #next_token} => String # # The returned {Seahorse::Client::Response response} is a pageable response and is Enumerable. For details on usage see {Aws::PageableResponse PageableResponse}. # # @example Request syntax with placeholder values # # resp = client.list_tags_for_resource({ # instance_arn: "InstanceArn", # required # resource_arn: "GeneralArn", # required # next_token: "Token", # }) # # @example Response structure # # resp.tags #=> Array # resp.tags[0].key #=> String # resp.tags[0].value #=> String # resp.next_token #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/ListTagsForResource AWS API Documentation # # @overload list_tags_for_resource(params = {}) # @param [Hash] params ({}) def list_tags_for_resource(params = {}, options = {}) req = build_request(:list_tags_for_resource, params) req.send_request(options) end # The process by which a specified permission set is provisioned to the # specified target. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :permission_set_arn # The ARN of the permission set. # # @option params [String] :target_id # The identifier for the chosen target. # # @option params [required, String] :target_type # The entity type for which the assignment will be created. # # @return [Types::ProvisionPermissionSetResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::ProvisionPermissionSetResponse#permission_set_provisioning_status #permission_set_provisioning_status} => Types::PermissionSetProvisioningStatus # # @example Request syntax with placeholder values # # resp = client.provision_permission_set({ # instance_arn: "InstanceArn", # required # permission_set_arn: "PermissionSetArn", # required # target_id: "TargetId", # target_type: "AWS_ACCOUNT", # required, accepts AWS_ACCOUNT, ALL_PROVISIONED_ACCOUNTS # }) # # @example Response structure # # resp.permission_set_provisioning_status.status #=> String, one of "IN_PROGRESS", "FAILED", "SUCCEEDED" # resp.permission_set_provisioning_status.request_id #=> String # resp.permission_set_provisioning_status.account_id #=> String # resp.permission_set_provisioning_status.permission_set_arn #=> String # resp.permission_set_provisioning_status.failure_reason #=> String # resp.permission_set_provisioning_status.created_date #=> Time # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/ProvisionPermissionSet AWS API Documentation # # @overload provision_permission_set(params = {}) # @param [Hash] params ({}) def provision_permission_set(params = {}, options = {}) req = build_request(:provision_permission_set, params) req.send_request(options) end # Attaches an IAM inline policy to a permission set. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :permission_set_arn # The ARN of the permission set. # # @option params [required, String] :inline_policy # The IAM inline policy to attach to a PermissionSet. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.put_inline_policy_to_permission_set({ # instance_arn: "InstanceArn", # required # permission_set_arn: "PermissionSetArn", # required # inline_policy: "PermissionSetPolicyDocument", # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/PutInlinePolicyToPermissionSet AWS API Documentation # # @overload put_inline_policy_to_permission_set(params = {}) # @param [Hash] params ({}) def put_inline_policy_to_permission_set(params = {}, options = {}) req = build_request(:put_inline_policy_to_permission_set, params) req.send_request(options) end # Associates a set of tags with a specified resource. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :resource_arn # The ARN of the resource with the tags to be listed. # # @option params [required, Array<Types::Tag>] :tags # A set of key-value pairs that are used to manage the resource. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.tag_resource({ # instance_arn: "InstanceArn", # required # resource_arn: "GeneralArn", # required # tags: [ # required # { # key: "TagKey", # value: "TagValue", # }, # ], # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/TagResource AWS API Documentation # # @overload tag_resource(params = {}) # @param [Hash] params ({}) def tag_resource(params = {}, options = {}) req = build_request(:tag_resource, params) req.send_request(options) end # Disassociates a set of tags from a specified resource. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :resource_arn # The ARN of the resource with the tags to be listed. # # @option params [required, Array<String>] :tag_keys # The keys of tags that are attached to the resource. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.untag_resource({ # instance_arn: "InstanceArn", # required # resource_arn: "GeneralArn", # required # tag_keys: ["TagKey"], # required # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/UntagResource AWS API Documentation # # @overload untag_resource(params = {}) # @param [Hash] params ({}) def untag_resource(params = {}, options = {}) req = build_request(:untag_resource, params) req.send_request(options) end # Updates an existing permission set. # # @option params [required, String] :instance_arn # The ARN of the SSO instance under which the operation will be # executed. For more information about ARNs, see [Amazon Resource Names # (ARNs) and AWS Service # Namespaces](/general/latest/gr/aws-arns-and-namespaces.html) in the # *AWS General Reference*. # # @option params [required, String] :permission_set_arn # The ARN of the permission set. # # @option params [String] :description # The description of the PermissionSet. # # @option params [String] :session_duration # The length of time that the application user sessions are valid for in # the ISO-8601 standard. # # @option params [String] :relay_state # Used to redirect users within the application during the federation # authentication process. # # @return [Struct] Returns an empty {Seahorse::Client::Response response}. # # @example Request syntax with placeholder values # # resp = client.update_permission_set({ # instance_arn: "InstanceArn", # required # permission_set_arn: "PermissionSetArn", # required # description: "PermissionSetDescription", # session_duration: "Duration", # relay_state: "RelayState", # }) # # @see http://docs.aws.amazon.com/goto/WebAPI/sso-admin-2020-07-20/UpdatePermissionSet AWS API Documentation # # @overload update_permission_set(params = {}) # @param [Hash] params ({}) def update_permission_set(params = {}, options = {}) req = build_request(:update_permission_set, params) req.send_request(options) end # @!endgroup # @param params ({}) # @api private def build_request(operation_name, params = {}) handlers = @handlers.for(operation_name) context = Seahorse::Client::RequestContext.new( operation_name: operation_name, operation: config.api.operation(operation_name), client: self, params: params, config: config) context[:gem_name] = 'aws-sdk-ssoadmin' context[:gem_version] = '1.0.0' Seahorse::Client::Request.new(handlers, context) end # @api private # @deprecated def waiter_names [] end class << self # @api private attr_reader :identifier # @api private def errors_module Errors end end end end
45.52
199
0.685467
d58bedf96435a167a9ca7278a431417d0f05e6ff
4,763
if ENV["CI"] require "codeclimate-test-reporter" CodeClimate::TestReporter.start end require "simplecov" SimpleCov.start do add_filter "/spec" add_filter "/vendor" end require "twiruby" # This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause this # file to always be loaded, without a need to explicitly require it in any files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need it. # # The `.rspec` file also contains a few flags that are not defaults but that # users commonly want. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. =begin # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run :focus config.run_all_when_everything_filtered = true # Limits the available syntax to the non-monkey patched syntax that is recommended. # For more details, see: # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching config.disable_monkey_patching! # This setting enables warnings. It's recommended, but in some cases may # be too noisy due to issues in dependencies. config.warnings = true # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed =end end require "webmock/rspec" WebMock.disable_net_connect!(:allow => "codeclimate.com") def stub_get(path) stub_request(:get, "#{TwiRuby::REST::BASE_URL}#{path}") end def stub_post(path) stub_request(:post, "#{TwiRuby::REST::BASE_URL}#{path}") end def fixtures(file) File.read("#{File.expand_path("../fixtures", __FILE__)}/#{file}") end
40.364407
129
0.741549
393f2afbfb0558333b04849928b29e76fcfdcef3
674
require "mini_magick" module Mosaic module Transform class << self def to_greyscale(input, output) convert "-colorspace Gray #{input} #{output}" end def resize(input, output, dimensions, opts) suffix = opts[:ignore_aspect_ratio] ? '!' : '' convert "#{input} -resize #{dimensions}#{suffix} #{output}" end def transcode(input, output) convert "#{input} #{output}" end private def convert(str) $logger.debug "#{self.class}.convert: Running 'convert #{str}'" MiniMagick::Tool::Convert.new do |tool| tool.merge! str.split end end end end end
22.466667
71
0.580119
282f1ee1f446ebb99154deec631e54c0d62a3b69
176
class Calculator def add(a, b, c = 0) a + b + c end def multiply(a, b) a * b end def subtract(a, b) a - b end def divide(a, b) a / b end end
9.777778
22
0.488636
79af9c37378f47546a9a0d3ed5f54d63a7be51ca
21,227
# frozen_string_literal: true module API module Helpers include Gitlab::Utils include Helpers::Pagination include Helpers::PaginationStrategies SUDO_HEADER = "HTTP_SUDO" GITLAB_SHARED_SECRET_HEADER = "Gitlab-Shared-Secret" SUDO_PARAM = :sudo API_USER_ENV = 'gitlab.api.user' API_EXCEPTION_ENV = 'gitlab.api.exception' API_RESPONSE_STATUS_CODE = 'gitlab.api.response_status_code' def declared_params(options = {}) options = { include_parent_namespaces: false }.merge(options) declared(params, options).to_h.symbolize_keys end def check_unmodified_since!(last_modified) if_unmodified_since = Time.parse(headers['If-Unmodified-Since']) rescue nil if if_unmodified_since && last_modified && last_modified > if_unmodified_since render_api_error!('412 Precondition Failed', 412) end end def destroy_conditionally!(resource, last_updated: nil) last_updated ||= resource.updated_at check_unmodified_since!(last_updated) status 204 body false if block_given? yield resource else resource.destroy end end def job_token_authentication? initial_current_user && @current_authenticated_job.present? # rubocop:disable Gitlab/ModuleWithInstanceVariables end # Returns the job associated with the token provided for # authentication, if any def current_authenticated_job @current_authenticated_job end # rubocop:disable Gitlab/ModuleWithInstanceVariables # We can't rewrite this with StrongMemoize because `sudo!` would # actually write to `@current_user`, and `sudo?` would immediately # call `current_user` again which reads from `@current_user`. # We should rewrite this in a way that using StrongMemoize is possible def current_user return @current_user if defined?(@current_user) @current_user = initial_current_user Gitlab::I18n.locale = @current_user&.preferred_language sudo! validate_access_token!(scopes: scopes_registered_for_endpoint) unless sudo? save_current_user_in_env(@current_user) if @current_user @current_user end # rubocop:enable Gitlab/ModuleWithInstanceVariables def save_current_user_in_env(user) env[API_USER_ENV] = { user_id: user.id, username: user.username } end def sudo? initial_current_user != current_user end def user_group @group ||= find_group!(params[:id]) end def user_project @project ||= find_project!(params[:id]) end def available_labels_for(label_parent, params = { include_ancestor_groups: true, only_group_labels: true }) if label_parent.is_a?(Project) params.delete(:only_group_labels) params[:project_id] = label_parent.id else params[:group_id] = label_parent.id end LabelsFinder.new(current_user, params).execute end def find_user(id) UserFinder.new(id).find_by_id_or_username end # rubocop: disable CodeReuse/ActiveRecord def find_project(id) projects = Project.without_deleted if id.is_a?(Integer) || id =~ /^\d+$/ projects.find_by(id: id) elsif id.include?("/") projects.find_by_full_path(id) end end # rubocop: enable CodeReuse/ActiveRecord def find_project!(id) project = find_project(id) if can?(current_user, :read_project, project) project else not_found!('Project') end end # rubocop: disable CodeReuse/ActiveRecord def find_group(id) if id.to_s =~ /^\d+$/ Group.find_by(id: id) else Group.find_by_full_path(id) end end # rubocop: enable CodeReuse/ActiveRecord def find_group!(id) group = find_group(id) if can?(current_user, :read_group, group) group else not_found!('Group') end end def check_namespace_access(namespace) return namespace if can?(current_user, :read_namespace, namespace) not_found!('Namespace') end # rubocop: disable CodeReuse/ActiveRecord def find_namespace(id) if id.to_s =~ /^\d+$/ Namespace.find_by(id: id) else Namespace.find_by_full_path(id) end end # rubocop: enable CodeReuse/ActiveRecord def find_namespace!(id) check_namespace_access(find_namespace(id)) end def find_namespace_by_path(path) Namespace.find_by_full_path(path) end def find_namespace_by_path!(path) check_namespace_access(find_namespace_by_path(path)) end def find_branch!(branch_name) if Gitlab::GitRefValidator.validate(branch_name) user_project.repository.find_branch(branch_name) || not_found!('Branch') else render_api_error!('The branch refname is invalid', 400) end end def find_tag!(tag_name) if Gitlab::GitRefValidator.validate(tag_name) user_project.repository.find_tag(tag_name) || not_found!('Tag') else render_api_error!('The tag refname is invalid', 400) end end # rubocop: disable CodeReuse/ActiveRecord def find_project_issue(iid, project_id = nil) project = project_id ? find_project!(project_id) : user_project ::IssuesFinder.new(current_user, project_id: project.id).find_by!(iid: iid) end # rubocop: enable CodeReuse/ActiveRecord # rubocop: disable CodeReuse/ActiveRecord def find_project_merge_request(iid) MergeRequestsFinder.new(current_user, project_id: user_project.id).find_by!(iid: iid) end # rubocop: enable CodeReuse/ActiveRecord def find_project_commit(id) user_project.commit_by(oid: id) end # rubocop: disable CodeReuse/ActiveRecord def find_merge_request_with_access(iid, access_level = :read_merge_request) merge_request = user_project.merge_requests.find_by!(iid: iid) authorize! access_level, merge_request merge_request end # rubocop: enable CodeReuse/ActiveRecord def find_build!(id) user_project.builds.find(id.to_i) end def find_job!(id) user_project.processables.find(id.to_i) end def authenticate! unauthorized! unless current_user end def authenticate_non_get! authenticate! unless %w[GET HEAD].include?(route.request_method) end def authenticate_by_gitlab_shell_token! input = params['secret_token'] input ||= Base64.decode64(headers[GITLAB_SHARED_SECRET_HEADER]) if headers.key?(GITLAB_SHARED_SECRET_HEADER) input&.chomp! unauthorized! unless Devise.secure_compare(secret_token, input) end def authenticated_with_can_read_all_resources! authenticate! forbidden! unless current_user.can_read_all_resources? end def authenticated_as_admin! authenticate! forbidden! unless current_user.admin? end def authorize!(action, subject = :global, reason = nil) forbidden!(reason) unless can?(current_user, action, subject) end def authorize_push_project authorize! :push_code, user_project end def authorize_admin_tag authorize! :admin_tag, user_project end def authorize_admin_project authorize! :admin_project, user_project end def authorize_admin_group authorize! :admin_group, user_group end def authorize_read_builds! authorize! :read_build, user_project end def authorize_read_build_trace!(build) authorize! :read_build_trace, build end def authorize_read_job_artifacts!(build) authorize! :read_job_artifacts, build end def authorize_destroy_artifacts! authorize! :destroy_artifacts, user_project end def authorize_update_builds! authorize! :update_build, user_project end def require_repository_enabled!(subject = :global) not_found!("Repository") unless user_project.feature_available?(:repository, current_user) end def require_gitlab_workhorse! verify_workhorse_api! unless env['HTTP_GITLAB_WORKHORSE'].present? forbidden!('Request should be executed via GitLab Workhorse') end end def verify_workhorse_api! Gitlab::Workhorse.verify_api_request!(request.headers) rescue => e Gitlab::ErrorTracking.track_exception(e) forbidden! end def require_pages_enabled! not_found! unless user_project.pages_available? end def require_pages_config_enabled! not_found! unless Gitlab.config.pages.enabled end def can?(object, action, subject = :global) Ability.allowed?(object, action, subject) end # Checks the occurrences of required attributes, each attribute must be present in the params hash # or a Bad Request error is invoked. # # Parameters: # keys (required) - A hash consisting of keys that must be present def required_attributes!(keys) keys.each do |key| bad_request_missing_attribute!(key) unless params[key].present? end end def attributes_for_keys(keys, custom_params = nil) params_hash = custom_params || params attrs = {} keys.each do |key| if params_hash[key].present? || (params_hash.key?(key) && params_hash[key] == false) attrs[key] = params_hash[key] end end permitted_attrs = ActionController::Parameters.new(attrs).permit! permitted_attrs.to_h end # rubocop: disable CodeReuse/ActiveRecord def filter_by_iid(items, iid) items.where(iid: iid) end # rubocop: enable CodeReuse/ActiveRecord # rubocop: disable CodeReuse/ActiveRecord def filter_by_title(items, title) items.where(title: title) end # rubocop: enable CodeReuse/ActiveRecord def filter_by_search(items, text) items.search(text) end def order_options_with_tie_breaker order_options = { params[:order_by] => params[:sort] } order_options['id'] ||= params[:sort] || 'asc' order_options end # error helpers def forbidden!(reason = nil) message = ['403 Forbidden'] message << "- #{reason}" if reason render_api_error!(message.join(' '), 403) end def bad_request!(reason = nil) message = ['400 Bad request'] message << "- #{reason}" if reason render_api_error!(message.join(' '), 400) end def bad_request_missing_attribute!(attribute) bad_request!("\"#{attribute}\" not given") end def not_found!(resource = nil) message = ["404"] message << resource if resource message << "Not Found" render_api_error!(message.join(' '), 404) end def check_sha_param!(params, merge_request) if params[:sha] && merge_request.diff_head_sha != params[:sha] render_api_error!("SHA does not match HEAD of source branch: #{merge_request.diff_head_sha}", 409) end end def unauthorized! render_api_error!('401 Unauthorized', 401) end def not_allowed!(message = nil) render_api_error!(message || '405 Method Not Allowed', :method_not_allowed) end def not_acceptable! render_api_error!('406 Not Acceptable', 406) end def service_unavailable! render_api_error!('503 Service Unavailable', 503) end def conflict!(message = nil) render_api_error!(message || '409 Conflict', 409) end def unprocessable_entity!(message = nil) render_api_error!(message || '422 Unprocessable Entity', :unprocessable_entity) end def file_too_large! render_api_error!('413 Request Entity Too Large', 413) end def not_modified! render_api_error!('304 Not Modified', 304) end def no_content! render_api_error!('204 No Content', 204) end def created! render_api_error!('201 Created', 201) end def accepted! render_api_error!('202 Accepted', 202) end def render_validation_error!(model) if model.errors.any? render_api_error!(model_error_messages(model) || '400 Bad Request', 400) end end def model_error_messages(model) model.errors.messages end def render_spam_error! render_api_error!({ error: 'Spam detected' }, 400) end def render_api_error!(message, status) # grape-logging doesn't pass the status code, so this is a # workaround for getting that information in the loggers: # https://github.com/aserafin/grape_logging/issues/71 env[API_RESPONSE_STATUS_CODE] = Rack::Utils.status_code(status) error!({ 'message' => message }, status, header) end def handle_api_exception(exception) if report_exception?(exception) define_params_for_grape_middleware Gitlab::ErrorTracking.with_context(current_user) do Gitlab::ErrorTracking.track_exception(exception) end end # This is used with GrapeLogging::Loggers::ExceptionLogger env[API_EXCEPTION_ENV] = exception # lifted from https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb#L60 trace = exception.backtrace message = ["\n#{exception.class} (#{exception.message}):\n"] message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code) message << " " << trace.join("\n ") message = message.join API.logger.add Logger::FATAL, message response_message = if Rails.env.test? message else '500 Internal Server Error' end rack_response({ 'message' => response_message }.to_json, 500) end # project helpers # rubocop: disable CodeReuse/ActiveRecord def reorder_projects(projects) projects.reorder(order_options_with_tie_breaker) end # rubocop: enable CodeReuse/ActiveRecord def project_finder_params project_finder_params_ce.merge(project_finder_params_ee) end # file helpers def present_disk_file!(path, filename, content_type = 'application/octet-stream') filename ||= File.basename(path) header['Content-Disposition'] = ActionDispatch::Http::ContentDisposition.format(disposition: 'attachment', filename: filename) header['Content-Transfer-Encoding'] = 'binary' content_type content_type # Support download acceleration case headers['X-Sendfile-Type'] when 'X-Sendfile' header['X-Sendfile'] = path body '' # to avoid an error from API::APIGuard::ResponseCoercerMiddleware else sendfile path end end def present_carrierwave_file!(file, supports_direct_download: true) return not_found! unless file&.exists? if file.file_storage? present_disk_file!(file.path, file.filename) elsif supports_direct_download && file.class.direct_download_enabled? redirect(file.url) else header(*Gitlab::Workhorse.send_url(file.url)) status :ok body '' # to avoid an error from API::APIGuard::ResponseCoercerMiddleware end end def track_event(action = action_name, **args) category = args.delete(:category) || self.options[:for].name raise "invalid category" unless category ::Gitlab::Tracking.event(category, action.to_s, **args) rescue => error Gitlab::AppLogger.warn( "Tracking event failed for action: #{action}, category: #{category}, message: #{error.message}" ) end def increment_counter(event_name) feature_name = "usage_data_#{event_name}" return unless Feature.enabled?(feature_name) Gitlab::UsageDataCounters.count(event_name) rescue => error Gitlab::AppLogger.warn("Redis tracking event failed for event: #{event_name}, message: #{error.message}") end # @param event_name [String] the event name # @param values [Array|String] the values counted def increment_unique_values(event_name, values) return unless values.present? feature_flag = "usage_data_#{event_name}" return unless Feature.enabled?(feature_flag, default_enabled: true) Gitlab::UsageDataCounters::HLLRedisCounter.track_event(event_name, values: values) rescue => error Gitlab::AppLogger.warn("Redis tracking event failed for event: #{event_name}, message: #{error.message}") end def with_api_params(&block) yield({ api: true, request: request }) end protected def project_finder_params_visibility_ce finder_params = {} finder_params[:min_access_level] = params[:min_access_level] if params[:min_access_level] finder_params[:visibility_level] = Gitlab::VisibilityLevel.level_value(params[:visibility]) if params[:visibility] finder_params[:owned] = true if params[:owned].present? finder_params[:non_public] = true if params[:membership].present? finder_params[:starred] = true if params[:starred].present? finder_params[:archived] = archived_param unless params[:archived].nil? finder_params end def project_finder_params_ce finder_params = project_finder_params_visibility_ce finder_params[:with_issues_enabled] = true if params[:with_issues_enabled].present? finder_params[:with_merge_requests_enabled] = true if params[:with_merge_requests_enabled].present? finder_params[:without_deleted] = true finder_params[:search] = params[:search] if params[:search] finder_params[:search_namespaces] = true if params[:search_namespaces].present? finder_params[:user] = params.delete(:user) if params[:user] finder_params[:custom_attributes] = params[:custom_attributes] if params[:custom_attributes] finder_params[:id_after] = sanitize_id_param(params[:id_after]) if params[:id_after] finder_params[:id_before] = sanitize_id_param(params[:id_before]) if params[:id_before] finder_params[:last_activity_after] = params[:last_activity_after] if params[:last_activity_after] finder_params[:last_activity_before] = params[:last_activity_before] if params[:last_activity_before] finder_params[:repository_storage] = params[:repository_storage] if params[:repository_storage] finder_params end # Overridden in EE def project_finder_params_ee {} end private # rubocop:disable Gitlab/ModuleWithInstanceVariables def initial_current_user return @initial_current_user if defined?(@initial_current_user) begin @initial_current_user = Gitlab::Auth::UniqueIpsLimiter.limit_user! { find_current_user! } rescue Gitlab::Auth::UnauthorizedError unauthorized! end end # rubocop:enable Gitlab/ModuleWithInstanceVariables def sudo! return unless sudo_identifier unauthorized! unless initial_current_user unless initial_current_user.admin? forbidden!('Must be admin to use sudo') end unless access_token forbidden!('Must be authenticated using an OAuth or Personal Access Token to use sudo') end validate_access_token!(scopes: [:sudo]) sudoed_user = find_user(sudo_identifier) not_found!("User with ID or username '#{sudo_identifier}'") unless sudoed_user @current_user = sudoed_user # rubocop:disable Gitlab/ModuleWithInstanceVariables end def sudo_identifier @sudo_identifier ||= params[SUDO_PARAM] || env[SUDO_HEADER] end def secret_token Gitlab::Shell.secret_token end def send_git_blob(repository, blob) env['api.format'] = :txt content_type 'text/plain' header['Content-Disposition'] = ActionDispatch::Http::ContentDisposition.format(disposition: 'inline', filename: blob.name) # Let Workhorse examine the content and determine the better content disposition header[Gitlab::Workhorse::DETECT_HEADER] = "true" header(*Gitlab::Workhorse.send_git_blob(repository, blob)) end def send_git_archive(repository, **kwargs) header(*Gitlab::Workhorse.send_git_archive(repository, **kwargs)) end def send_artifacts_entry(file, entry) header(*Gitlab::Workhorse.send_artifacts_entry(file, entry)) end # The Grape Error Middleware only has access to `env` but not `params` nor # `request`. We workaround this by defining methods that returns the right # values. def define_params_for_grape_middleware self.define_singleton_method(:request) { ActionDispatch::Request.new(env) } self.define_singleton_method(:params) { request.params.symbolize_keys } end # We could get a Grape or a standard Ruby exception. We should only report anything that # is clearly an error. def report_exception?(exception) return true unless exception.respond_to?(:status) exception.status == 500 end def archived_param return 'only' if params[:archived] params[:archived] end def ip_address env["action_dispatch.remote_ip"].to_s || request.ip end def sanitize_id_param(id) id.present? ? id.to_i : nil end end end API::Helpers.prepend_if_ee('EE::API::Helpers')
29.813202
132
0.690677
39e8b5d110dc075253a2fb69c9f01ff2ce851acc
338
cask 'djv' do version '1.1.0' sha256 'b922fc5d94e57d436779aa912d3f07746f541124149d5f4d8198d4ef0e2e8fd5' url "http://downloads.sourceforge.net/project/djv/djv-stable/#{version}/djv-#{version}-OSX-64.dmg" name 'DJV' name 'DJV Imaging' homepage 'http://djv.sourceforge.net' license :bsd app "djv-#{version}-OSX-64.app" end
26
100
0.730769
384e5a54ecae6c62d3197ee8f89f0c22c435d728
83
class Lab < ApplicationRecord has_many :schedules def to_s name end end
10.375
29
0.710843
ffc2e947087fe128f805c243bff2819ca8d7e992
428
module Channel9 module Instruction # jmp label # --- # Unconditionally jumps to the label specified. # # Takes no inputs and produces no outputs. class JMP < Base attr :to def initialize(stream, to) super(stream) @to = to end def arguments [@to] end def run(environment) environment.context.set_pos(@to) end end end end
17.12
51
0.563084
f7aa8d4a8bcb6282f8178a51123b0e7295f46ec6
512
class ContestConfig < ActiveRecord::Base ###################################### ############ Validations ############# ###################################### validates :description, :length=>{:maximum=>254},:allow_nil=>true ###################################### ############ Accessibility ########### ###################################### attr_accessible :lang,:welcome_note,:upload_hint,:winning_eligibility,:prizes, :inappropriate_content,:entry_format,:email_body,:description end
34.133333
80
0.451172
5df1e2804afbe6995d03c7de02e12ccba8915fff
807
# frozen_string_literal: true class ProjectRolesController < ApplicationController include CurrentProject before_action :authorize_project_admin! def create user = User.find(params[:user_id]) role = UserProjectRole.where(user: user, project: current_project).first_or_initialize role.role_id = params[:role_id].presence if role.role_id role.save! user.update!(access_request_pending: false) elsif role.persisted? role.destroy! end role_name = (role.role.try(:display_name) || 'None') Rails.logger.info( "#{current_user.name_and_email} set the role #{role_name} to #{user.name} on project #{current_project.name}" ) if request.xhr? render plain: "Saved!" else redirect_back_or "/", notice: "Saved!" end end end
26.032258
115
0.695167
f85ace95fddc7e0cf2910380e71dbbae2f5a3b26
20,135
# frozen_string_literal: true # Please do not make direct changes to this file! # This generator is maintained by the community around simple_form-bootstrap: # https://github.com/heartcombo/simple_form-bootstrap # All future development, tests, and organization should happen there. # Background history: https://github.com/heartcombo/simple_form/issues/1561 # Uncomment this and change the path if necessary to include your own # components. # See https://github.com/heartcombo/simple_form#custom-components # to know more about custom components. # Dir[Rails.root.join('lib/components/**/*.rb')].each { |f| require f } # Use this setup block to configure all options available in SimpleForm. SimpleForm.setup do |config| # Default class for buttons config.button_class = 'btn btn-primary' # Define the default class of the input wrapper of the boolean input. config.boolean_label_class = 'form-check-label' # How the label text should be generated altogether with the required text. config.label_text = lambda { |label, required, explicit_label| "#{label} #{required}" } # Define the way to render check boxes / radio buttons with labels. config.boolean_style = :inline # You can wrap each item in a collection of radio/check boxes with a tag config.item_wrapper_tag = :div # Defines if the default input wrapper class should be included in radio # collection wrappers. config.include_default_input_wrapper_class = false # CSS class to add for error notification helper. config.error_notification_class = 'alert alert-danger' # Method used to tidy up errors. Specify any Rails Array method. # :first lists the first message for each field. # :to_sentence to list all errors for each field. config.error_method = :to_sentence # add validation classes to `input_field` config.input_field_error_class = 'is-invalid' config.input_field_valid_class = 'is-valid' # vertical forms # # vertical default_wrapper config.wrappers :vertical_form, tag: 'div', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.use :placeholder b.optional :maxlength b.optional :minlength b.optional :pattern b.optional :min_max b.optional :readonly b.use :label b.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid' b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' } b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end # vertical input for boolean config.wrappers :vertical_boolean, tag: 'fieldset', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.optional :readonly b.wrapper :form_check_wrapper, tag: 'div', class: 'form-check' do |bb| bb.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid' bb.use :label, class: 'form-check-label' bb.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' } bb.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end end # vertical input for radio buttons and check boxes config.wrappers :vertical_collection, item_wrapper_class: 'form-check', item_label_class: 'form-check-label', tag: 'fieldset', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.optional :readonly b.wrapper :legend_tag, tag: 'legend', class: 'col-form-label pt-0' do |ba| ba.use :label_text end b.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid' b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback d-block' } b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end # vertical input for inline radio buttons and check boxes config.wrappers :vertical_collection_inline, item_wrapper_class: 'form-check form-check-inline', item_label_class: 'form-check-label', tag: 'fieldset', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.optional :readonly b.wrapper :legend_tag, tag: 'legend', class: 'col-form-label pt-0' do |ba| ba.use :label_text end b.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid' b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback d-block' } b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end # vertical file input config.wrappers :vertical_file, tag: 'div', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.use :placeholder b.optional :maxlength b.optional :minlength b.optional :readonly b.use :label b.use :input, class: 'form-control-file', error_class: 'is-invalid', valid_class: 'is-valid' b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' } b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end # vertical multi select config.wrappers :vertical_multi_select, tag: 'div', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.optional :readonly b.use :label b.wrapper tag: 'div', class: 'd-flex flex-row justify-content-between align-items-center' do |ba| ba.use :input, class: 'form-control mx-1', error_class: 'is-invalid', valid_class: 'is-valid' end b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback d-block' } b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end # vertical range input config.wrappers :vertical_range, tag: 'div', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.use :placeholder b.optional :readonly b.optional :step b.use :label b.use :input, class: 'form-control-range', error_class: 'is-invalid', valid_class: 'is-valid' b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback d-block' } b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end # horizontal forms # # horizontal default_wrapper config.wrappers :horizontal_form, tag: 'div', class: 'form-group row', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.use :placeholder b.optional :maxlength b.optional :minlength b.optional :pattern b.optional :min_max b.optional :readonly b.use :label, class: 'col-sm-3 col-form-label' b.wrapper :grid_wrapper, tag: 'div', class: 'col-sm-9' do |ba| ba.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid' ba.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' } ba.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end end # horizontal input for boolean config.wrappers :horizontal_boolean, tag: 'div', class: 'form-group row', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.optional :readonly b.wrapper tag: 'label', class: 'col-sm-3' do |ba| ba.use :label_text end b.wrapper :grid_wrapper, tag: 'div', class: 'col-sm-9' do |wr| wr.wrapper :form_check_wrapper, tag: 'div', class: 'form-check' do |bb| bb.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid' bb.use :label, class: 'form-check-label' bb.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback d-block' } bb.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end end end # horizontal input for radio buttons and check boxes config.wrappers :horizontal_collection, item_wrapper_class: 'form-check', item_label_class: 'form-check-label', tag: 'div', class: 'form-group row', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.optional :readonly b.use :label, class: 'col-sm-3 col-form-label pt-0' b.wrapper :grid_wrapper, tag: 'div', class: 'col-sm-9' do |ba| ba.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid' ba.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback d-block' } ba.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end end # horizontal input for inline radio buttons and check boxes config.wrappers :horizontal_collection_inline, item_wrapper_class: 'form-check form-check-inline', item_label_class: 'form-check-label', tag: 'div', class: 'form-group row', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.optional :readonly b.use :label, class: 'col-sm-3 col-form-label pt-0' b.wrapper :grid_wrapper, tag: 'div', class: 'col-sm-9' do |ba| ba.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid' ba.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback d-block' } ba.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end end # horizontal file input config.wrappers :horizontal_file, tag: 'div', class: 'form-group row', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.use :placeholder b.optional :maxlength b.optional :minlength b.optional :readonly b.use :label, class: 'col-sm-3 col-form-label' b.wrapper :grid_wrapper, tag: 'div', class: 'col-sm-9' do |ba| ba.use :input, error_class: 'is-invalid', valid_class: 'is-valid' ba.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback d-block' } ba.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end end # horizontal multi select config.wrappers :horizontal_multi_select, tag: 'div', class: 'form-group row', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.optional :readonly b.use :label, class: 'col-sm-3 col-form-label' b.wrapper :grid_wrapper, tag: 'div', class: 'col-sm-9' do |ba| ba.wrapper tag: 'div', class: 'd-flex flex-row justify-content-between align-items-center' do |bb| bb.use :input, class: 'form-control mx-1', error_class: 'is-invalid', valid_class: 'is-valid' end ba.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback d-block' } ba.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end end # horizontal range input config.wrappers :horizontal_range, tag: 'div', class: 'form-group row', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.use :placeholder b.optional :readonly b.optional :step b.use :label, class: 'col-sm-3 col-form-label' b.wrapper :grid_wrapper, tag: 'div', class: 'col-sm-9' do |ba| ba.use :input, class: 'form-control-range', error_class: 'is-invalid', valid_class: 'is-valid' ba.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback d-block' } ba.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end end # inline forms # # inline default_wrapper config.wrappers :inline_form, tag: 'span', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.use :placeholder b.optional :maxlength b.optional :minlength b.optional :pattern b.optional :min_max b.optional :readonly b.use :label, class: 'sr-only' b.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid' b.use :error, wrap_with: { tag: 'div', class: 'invalid-feedback' } b.optional :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end # inline input for boolean config.wrappers :inline_boolean, tag: 'span', class: 'form-check mb-2 mr-sm-2', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.optional :readonly b.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid' b.use :label, class: 'form-check-label' b.use :error, wrap_with: { tag: 'div', class: 'invalid-feedback' } b.optional :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end # bootstrap custom forms # # custom input for boolean config.wrappers :custom_boolean, tag: 'fieldset', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.optional :readonly b.wrapper :form_check_wrapper, tag: 'div', class: 'custom-control custom-checkbox' do |bb| bb.use :input, class: 'custom-control-input', error_class: 'is-invalid', valid_class: 'is-valid' bb.use :label, class: 'custom-control-label' bb.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' } bb.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end end # custom input switch for boolean config.wrappers :custom_boolean_switch, tag: 'fieldset', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.optional :readonly b.wrapper :form_check_wrapper, tag: 'div', class: 'custom-control custom-switch' do |bb| bb.use :input, class: 'custom-control-input', error_class: 'is-invalid', valid_class: 'is-valid' bb.use :label, class: 'custom-control-label' bb.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' } bb.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end end # custom input for radio buttons and check boxes config.wrappers :custom_collection, item_wrapper_class: 'custom-control', item_label_class: 'custom-control-label', tag: 'fieldset', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.optional :readonly b.wrapper :legend_tag, tag: 'legend', class: 'col-form-label pt-0' do |ba| ba.use :label_text end b.use :input, class: 'custom-control-input', error_class: 'is-invalid', valid_class: 'is-valid' b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback d-block' } b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end # custom input for inline radio buttons and check boxes config.wrappers :custom_collection_inline, item_wrapper_class: 'custom-control custom-control-inline', item_label_class: 'custom-control-label', tag: 'fieldset', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.optional :readonly b.wrapper :legend_tag, tag: 'legend', class: 'col-form-label pt-0' do |ba| ba.use :label_text end b.use :input, class: 'custom-control-input', error_class: 'is-invalid', valid_class: 'is-valid' b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback d-block' } b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end # custom file input config.wrappers :custom_file, tag: 'div', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.use :placeholder b.optional :maxlength b.optional :minlength b.optional :readonly b.use :label b.wrapper :custom_file_wrapper, tag: 'div', class: 'custom-file' do |ba| ba.use :input, class: 'custom-file-input', error_class: 'is-invalid', valid_class: 'is-valid' ba.use :label, class: 'custom-file-label' ba.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' } end b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end # custom multi select config.wrappers :custom_multi_select, tag: 'div', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.optional :readonly b.use :label b.wrapper tag: 'div', class: 'd-flex flex-row justify-content-between align-items-center' do |ba| ba.use :input, class: 'custom-select mx-1', error_class: 'is-invalid', valid_class: 'is-valid' end b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback d-block' } b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end # custom range input config.wrappers :custom_range, tag: 'div', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.use :placeholder b.optional :readonly b.optional :step b.use :label b.use :input, class: 'custom-range', error_class: 'is-invalid', valid_class: 'is-valid' b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback d-block' } b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end # Input Group - custom component # see example app and config at https://github.com/heartcombo/simple_form-bootstrap # config.wrappers :input_group, tag: 'div', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| # b.use :html5 # b.use :placeholder # b.optional :maxlength # b.optional :minlength # b.optional :pattern # b.optional :min_max # b.optional :readonly # b.use :label # b.wrapper :input_group_tag, tag: 'div', class: 'input-group' do |ba| # ba.optional :prepend # ba.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid' # ba.optional :append # end # b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback d-block' } # b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } # end # Floating Labels form # # floating labels default_wrapper config.wrappers :floating_labels_form, tag: 'div', class: 'form-label-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.use :placeholder b.optional :maxlength b.optional :minlength b.optional :pattern b.optional :min_max b.optional :readonly b.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid' b.use :label b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' } b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end # custom multi select config.wrappers :floating_labels_select, tag: 'div', class: 'form-label-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b| b.use :html5 b.optional :readonly b.use :input, class: 'custom-select', error_class: 'is-invalid', valid_class: 'is-valid' b.use :label b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' } b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' } end # The default wrapper to be used by the FormBuilder. config.default_wrapper = :vertical_form # Custom wrappers for input types. This should be a hash containing an input # type as key and the wrapper that will be used for all inputs with specified type. config.wrapper_mappings = { boolean: :vertical_boolean, check_boxes: :vertical_collection, date: :vertical_multi_select, datetime: :vertical_multi_select, file: :vertical_file, radio_buttons: :vertical_collection, range: :vertical_range, time: :vertical_multi_select } # enable custom form wrappers # config.wrapper_mappings = { # boolean: :custom_boolean, # check_boxes: :custom_collection, # date: :custom_multi_select, # datetime: :custom_multi_select, # file: :custom_file, # radio_buttons: :custom_collection, # range: :custom_range, # time: :custom_multi_select # } end
46.394009
258
0.677825
fffbe5eca14a07ca9df65a1c9aa3006b69e158f4
1,693
module Fog module Storage class InternetArchive class Real require 'fog/internet_archive/parsers/storage/get_bucket_location' # Get location constraint for an S3 bucket # # @param bucket_name [String] name of bucket to get location constraint for # # @return [Excon::Response] response: # * body [Hash]: # * LocationConstraint [String] - Location constraint of the bucket # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketGETlocation.html def get_bucket_location(bucket_name) request({ :expects => 200, :headers => {}, :host => "#{bucket_name}.#{@host}", :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::InternetArchive::GetBucketLocation.new, :query => {'location' => nil} }) end end class Mock # :nodoc:all def get_bucket_location(bucket_name) response = Excon::Response.new if bucket = self.data[:buckets][bucket_name] location_constraint = case bucket['LocationConstraint'] when 'us-east-1' nil when 'eu-east-1' 'EU' else bucket['LocationConstraint'] end response.status = 200 response.body = {'LocationConstraint' => location_constraint } else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end
28.694915
95
0.541051
62ee0d57d541a08d21a00f3befb72efb90b22597
6,266
# # Author:: Vasundhara Jagdale (<[email protected]>) # Copyright:: Copyright 2015-2016, Chef Software, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "chef/provider/package" require "chef/resource/cab_package" require "chef/mixin/shell_out" class Chef class Provider class Package class Cab < Chef::Provider::Package include Chef::Mixin::ShellOut provides :cab_package, os: "windows" def load_current_resource @current_resource = Chef::Resource::CabPackage.new(new_resource.name) current_resource.source(new_resource.source) new_resource.version(package_version) current_resource.version(installed_version) current_resource end def install_package(name, version) dism_command("/Add-Package /PackagePath:\"#{@new_resource.source}\"") end def remove_package(name, version) dism_command("/Remove-Package /PackagePath:\"#{@new_resource.source}\"") end def dism_command(command) shellout = Mixlib::ShellOut.new("dism.exe /Online /English #{command} /NoRestart", { :timeout => @new_resource.timeout }) with_os_architecture(nil) do shellout.run_command end end def installed_version stdout = dism_command("/Get-PackageInfo /PackagePath:\"#{@new_resource.source}\"").stdout package_info = parse_dism_get_package_info(stdout) # e.g. Package_for_KB2975719~31bf3856ad364e35~amd64~~6.3.1.8 package = split_package_identity(package_info["package_information"]["package_identity"]) # Search for just the package name to catch a different version being installed Chef::Log.debug("#{@new_resource} searching for installed package #{package['name']}") found_packages = installed_packages.select { |p| p["package_identity"] =~ /^#{package['name']}~/ } if found_packages.length == 0 nil elsif found_packages.length == 1 stdout = dism_command("/Get-PackageInfo /PackageName:\"#{found_packages.first["package_identity"]}\"").stdout find_version(stdout) else # Presuming this won't happen, otherwise we need to handle it raise Chef::Exceptions::Package, "Found multiple packages installed matching name #{package['name']}, found: #{found_packages.length} matches" end end def package_version Chef::Log.debug("#{@new_resource} getting product version for package at #{@new_resource.source}") stdout = dism_command("/Get-PackageInfo /PackagePath:\"#{@new_resource.source}\"").stdout find_version(stdout) end def find_version(stdout) package_info = parse_dism_get_package_info(stdout) package = split_package_identity(package_info["package_information"]["package_identity"]) package["version"] end # returns a hash of package state information given the output of dism /get-packages # expected keys: package_identity def parse_dism_get_packages(text) packages = Array.new text.each_line do |line| key, value = line.split(":") if line.start_with?("Package Identity") unless key.nil? || value.nil? package = Hash.new package[key.downcase.strip.tr(" ", "_")] = value.strip.chomp packages << package end end packages end # returns a hash of package information given the output of dism /get-packageinfo def parse_dism_get_package_info(text) package_data = Hash.new errors = Array.new in_section = false section_headers = [ "Package information", "Custom Properties", "Features" ] text.each_line do |line| if line =~ /Error: (.*)/ errors << $1.strip elsif section_headers.any? { |header| line =~ /^(#{header})/ } in_section = $1.downcase.tr(" ", "_") elsif line =~ /(.*) ?: (.*)/ v = $2 # has to be first or the gsub below replaces this variable k = $1.downcase.strip.tr(" ", "_") if in_section package_data[in_section] = Hash.new unless package_data[in_section] package_data[in_section][k] = v else package_data[k] = v end end end unless errors.empty? if errors.include?("0x80070003") || errors.include?("0x80070002") raise Chef::Exceptions::Package, "DISM: The system cannot find the path or file specified." elsif errors.include?("740") raise Chef::Exceptions::Package, "DISM: Error 740: Elevated permissions are required to run DISM." else raise Chef::Exceptions::Package, "Unknown errors encountered parsing DISM output: #{errors}" end end package_data end def split_package_identity(identity) data = Hash.new data["name"], data["publisher"], data["arch"], data["resource_id"], data["version"] = identity.split("~") data end def installed_packages @packages ||= begin output = dism_command("/Get-Packages").stdout packages = parse_dism_get_packages(output) packages end end end end end end
41.496689
155
0.605809
7ab7c43a1f7902c34a86db6f5eee351d94591fbd
1,411
class DeviseCreateBystanders < ActiveRecord::Migration def change create_table(:bystanders) do |t| ## Database authenticatable t.string :name, null: false t.string :email, null: false t.string :encrypted_password, null: false, default: "" ## Recoverable t.string :reset_password_token t.datetime :reset_password_sent_at ## Rememberable t.datetime :remember_created_at ## Trackable t.integer :sign_in_count, default: 0, null: false t.datetime :current_sign_in_at t.datetime :last_sign_in_at t.string :current_sign_in_ip t.string :last_sign_in_ip ## Confirmable t.string :confirmation_token t.datetime :confirmed_at t.datetime :confirmation_sent_at t.string :unconfirmed_email # Only if using reconfirmable ## Lockable # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts # t.string :unlock_token # Only if unlock strategy is :email or :both # t.datetime :locked_at t.timestamps null: false end add_index :bystanders, :email, unique: true add_index :bystanders, :reset_password_token, unique: true add_index :bystanders, :confirmation_token, unique: true # add_index :bystanders, :unlock_token, unique: true end end
32.068182
104
0.65769
034d3343300185f948e7427f2219088dffed637c
37
module Trove VERSION = "0.0.1" end
9.25
19
0.648649
abe66f3e5c5baf6e2eba69845e254cc980ac0191
1,996
require 'spec_helper' require 'database_cleaner' ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) require 'rspec/rails' # Prevent database truncation if the environment is production abort("The Rails environment is running in production mode!") if Rails.env.production? ActiveRecord::Migration.maintain_test_schema! Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } RSpec.configure do |config| # add `FactoryBot` methods config.include FactoryBot::Syntax::Methods # start by truncating all the tables but then use the faster transaction strategy the rest of the time. config.before(:suite) do DatabaseCleaner.clean_with(:truncation) DatabaseCleaner.strategy = :transaction end # start the transaction strategy as examples are run config.around(:each) do |example| DatabaseCleaner.cleaning do example.run end end config.include RequestSpecHelper, type: :request # RSpec Rails can automatically mix in different behaviours to your tests # based on their file location, for example enabling you to call `get` and # `post` in specs under `spec/controllers`. # # You can disable this behaviour by removing the line below, and instead # explicitly tag your specs with their type, e.g.: # # RSpec.describe UsersController, :type => :controller do # # ... # end # # The different available types are documented in the features, such as in # https://relishapp.com/rspec/rspec-rails/docs config.infer_spec_type_from_file_location! # Filter lines from Rails gems in backtraces. config.filter_rails_from_backtrace! # arbitrary gems may also be filtered via: # config.filter_gems_from_backtrace("gem name") end # configure shoulda matchers to use rspec as the test framework and full matcher libraries for rails Shoulda::Matchers.configure do |config| config.integrate do |with| with.test_framework :rspec with.library :rails end end
31.1875
105
0.741483
b90d703527a1dcf51f7b2ab73690116f2f1be291
1,373
# frozen_string_literal: true module ModelToGraphql module Generators class BelongsToRelationResolverGenerator < GraphQL::Schema::Resolver class << self attr_accessor :relation end def resolve(path: [], lookahead: nil) model_class = relation_model_class(relation, object) foreign_key = object.send("#{relation.name}_id") unscoped = false relation_unscoped_proc = ModelToGraphql.config_options[:is_relation_unscoped] unless relation_unscoped_proc.nil? unscoped = relation_unscoped_proc.call(relation) end ModelToGraphql::Loaders::RecordLoader.for(model_class, unscoped: unscoped).load(foreign_key&.to_s) end def relation_model_class(relation, object) self.class.relation_model_class(relation, object) end def relation self.class.relation end # Resolve the model class of a polymorphic relation def self.relation_model_class(relation, object) if relation.polymorphic? object.send("#{relation.name}_type").constantize else relation.klass end end def self.build(relation, return_type) Class.new(BelongsToRelationResolverGenerator) do type(return_type, null: true) self.relation = relation end end end end end
28.020408
106
0.667881
5d93bed88d759e200cf35013ef3c54eec5f627a7
460
module VimeoMe2 module UserMethods module Videos # Get a list of albums for the current user. # @param [Object] Arguments passed to http_request (optional keys include: headers, query) def get_video_list(**args) get("/videos", **args) end # Get one album by it's ID # @param [String] album_id The Id of the album. def get_video(video_id) get("/videos/#{video_id}") end end end end
23
96
0.619565
261579dce5d749fad892cba56b79cbd0b7266e37
4,637
# frozen_string_literal: true require "abstract_unit" require "action_dispatch/testing/assertions/response" module ActionDispatch module Assertions class ResponseAssertionsTest < ActiveSupport::TestCase include ResponseAssertions FakeResponse = Struct.new(:response_code, :location, :body) do def initialize(*) super self.location ||= "http://test.example.com/posts" self.body ||= "" end [:successful, :not_found, :redirection, :server_error].each do |sym| define_method("#{sym}?") do sym == response_code end end end def setup @controller = nil @request = nil end def test_assert_response_predicate_methods [:success, :missing, :redirect, :error].each do |sym| @response = FakeResponse.new RESPONSE_PREDICATES[sym].to_s.sub(/\?/, "").to_sym assert_response sym assert_raises(Minitest::Assertion) { assert_response :unauthorized } end end def test_assert_response_integer @response = FakeResponse.new 400 assert_response 400 assert_raises(Minitest::Assertion) { assert_response :unauthorized } assert_raises(Minitest::Assertion) { assert_response 500 } end def test_assert_response_sym_status @response = FakeResponse.new 401 assert_response :unauthorized assert_raises(Minitest::Assertion) { assert_response :ok } assert_raises(Minitest::Assertion) { assert_response :success } end def test_assert_response_sym_typo @response = FakeResponse.new 200 assert_raises(ArgumentError) { assert_response :succezz } end def test_error_message_shows_404_when_404_asserted_for_success @response = ActionDispatch::Response.new @response.status = 404 error = assert_raises(Minitest::Assertion) { assert_response :success } expected = "Expected response to be a <2XX: success>,"\ " but was a <404: Not Found>" assert_match expected, error.message end def test_error_message_shows_404_when_asserted_for_200 @response = ActionDispatch::Response.new @response.status = 404 error = assert_raises(Minitest::Assertion) { assert_response 200 } expected = "Expected response to be a <200: OK>,"\ " but was a <404: Not Found>" assert_match expected, error.message end def test_error_message_shows_302_redirect_when_302_asserted_for_success @response = ActionDispatch::Response.new @response.status = 302 @response.location = "http://test.host/posts/redirect/1" error = assert_raises(Minitest::Assertion) { assert_response :success } expected = "Expected response to be a <2XX: success>,"\ " but was a <302: Found>" \ " redirect to <http://test.host/posts/redirect/1>" assert_match expected, error.message end def test_error_message_shows_302_redirect_when_302_asserted_for_301 @response = ActionDispatch::Response.new @response.status = 302 @response.location = "http://test.host/posts/redirect/2" error = assert_raises(Minitest::Assertion) { assert_response 301 } expected = "Expected response to be a <301: Moved Permanently>,"\ " but was a <302: Found>" \ " redirect to <http://test.host/posts/redirect/2>" assert_match expected, error.message end def test_error_message_shows_short_response_body @response = ActionDispatch::Response.new @response.status = 400 @response.body = "not too long" error = assert_raises(Minitest::Assertion) { assert_response 200 } expected = "Expected response to be a <200: OK>,"\ " but was a <400: Bad Request>" \ "\nResponse body: not too long" assert_match expected, error.message end def test_error_message_does_not_show_long_response_body @response = ActionDispatch::Response.new @response.status = 400 @response.body = "not too long" * 50 error = assert_raises(Minitest::Assertion) { assert_response 200 } expected = "Expected response to be a <200: OK>,"\ " but was a <400: Bad Request>" assert_match expected, error.message end end end end
32.65493
89
0.623895
ff4b4c0ddabf3a2a50841eb9b995e8a5a25d3f01
859
Rhinobook::Engine.routes.draw do devise_for :users, class_name: "Rhinoart::User", module: :devise, :controllers => { :sessions => "rhinoart/sessions", :passwords => "rhinoart/passwords" } scope "(:locale)", locale: /ru|en/ do root :to => 'books#index' resources :books do resources :domains resources :chapters get 'reorder_pages' end resources :chapters, only: :nil do resources :pages, on: :collection end resources :statuses, only: :destroy do post 'set_new_status/:statusable_id/:statusable_type/:locale' => 'statuses#set_new_status', on: :collection, as: :set_new_status, via: :js end resources :temp_contents, only: [:index, :create] end #API namespace :api do scope :v1 do resources :temp_contents, only: [:show] end end end
26.030303
150
0.633295
bf56c584b7edb97b01c600e570709b8f96d96c5d
1,331
class ReviewsController < ApplicationController before_action :authenticate_user! before_action :find_review, only: [:edit, :update, :destroy ] before_action :find_product, except: :create def new @review = Review.new end def create @review = Review.new(review_params) @review.user_id = current_user.id @review.product_id = find_product.id if @review.save redirect_to product_path(find_product) else @errors = @review.errors.full_messages render :new end end def edit end def update respond_to do |format| if @review.update(review_params) format.html { redirect_to @product, notice: 'Review was successfully updated.' } format.json { render :show, status: :ok, location: @review } else format.html { render :edit } format.json { render json: @review.errors, status: :unprocessable_entity } end end end def destroy @review.destroy respond_to do |format| format.html { redirect_to @product, notice: 'Review was successfully deleted.' } format.json { head :no_content } end end private def review_params params.require(:review).permit(:user_id, :product_id, :rating, :comment) end def find_product @product = Product.find_by(id: params[:product_id]) end def find_review @review = Review.find_by(id: params[:id]) end end
22.559322
86
0.712998
ab88e552c08b82da0f29dc2e92bd994866537a12
1,158
require 'spec_helper' describe HideAncestry::ModelManage::CustomAncestryUpdater do include_examples 'Monkeys subtree' let(:some_monkey) { build :monkey } context 'calls in callback' do it do expect(described_class).to receive(:call).with some_monkey some_monkey.save end end describe 'init custom ancestry columns' do context '#hide_ancestry' do it 'in general case' do expect(some_monkey.hide_ancestry).to be_nil some_monkey.save expect(some_monkey.hide_ancestry) .to eq "#{some_monkey.id}" end it 'if node has #parent' do some_monkey.parent = child some_monkey.save expect(some_monkey.hide_ancestry) .to eq(some_monkey.ancestry + "/#{some_monkey.id}") end it 'if node has #fired_parent' do some_monkey.parent = parent some_monkey.save HideAncestry::ModelManage::Hide.call(parent) expect(some_monkey.reload.hide_ancestry) .to eq "#{grandparent.id}/#{parent.id}/#{some_monkey.id}" expect(some_monkey.ancestry) .to eq "#{grandparent.id}" end end end end
25.173913
65
0.651986
791e3b77cb91a4a1ff34551e123ee305d70d5ceb
3,847
class Gocr < Formula desc "Optical Character Recognition (OCR), converts images back to text" homepage "http://jocr.sourceforge.net/" url "https://www-e.uni-magdeburg.de/jschulen/ocr/gocr-0.50.tar.gz" sha256 "bc261244f887419cba6d962ec1ad58eefd77176885093c4a43061e7fd565f5b5" bottle do cellar :any_skip_relocation rebuild 1 sha256 "0e3df7c5f1304de66cb85b98b12612ed99e43177b37c02605892b02c947f0ef0" => :sierra sha256 "3b3a0351d949f3f798dc973e0f31a283b8df3f73d1c7f251c7f15229ceb2fb20" => :el_capitan sha256 "94207525e139ef275415f46ff50baab26fef6a2ba52ca71a6a00aa3035ced71c" => :yosemite sha256 "467ce3a1411e022f44b60691bf71bf8a7b86ba234b21dad23cc1f2b258d92e9b" => :mavericks end option "with-lib", "Install library and headers" depends_on "netpbm" => :optional depends_on "jpeg" => :optional # Edit makefile to install libs per developer documentation patch :DATA if build.with? "lib" def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" # --mandir doesn't work correctly; fix broken Makefile inreplace "man/Makefile" do |s| s.change_make_var! "mandir", "/share/man" end system "make", "libs" if build.with? "lib" system "make", "install" end test do system "#{bin}/gocr", "-h" end end __END__ diff --git a/src/Makefile.in b/src/Makefile.in index bf4181f..883fec2 --- a/src/Makefile.in +++ b/src/Makefile.in @@ -10,7 +10,7 @@ PROGRAM = gocr$(EXEEXT) PGMASCLIB = Pgm2asc #LIBPGMASCLIB = lib$(PGMASCLIB).a # ToDo: need a better pgm2asc.h for lib users -#INCLUDEFILES = gocr.h +INCLUDEFILES = pgm2asc.h output.h list.h unicode.h gocr.h pnm.h # avoid german compiler messages LANG=C @@ -39,8 +39,8 @@ LIBOBJS=pgm2asc.o \ #VPATH = @srcdir@ bindir = @bindir@ # lib removed for simplification -#libdir = @libdir@ -#includedir = @includedir@ +libdir = @libdir@ +includedir = /include/gocr CC=@CC@ # lib removed for simplification @@ -89,7 +89,8 @@ $(PROGRAM): $(LIBOBJS) gocr.o $(CC) -o $@ $(LDFLAGS) gocr.o $(LIBOBJS) $(LIBS) # if test -r $(PROGRAM); then cp $@ ../bin; fi -libs: lib$(PGMASCLIB).a lib$(PGMASCLIB).@[email protected] +#libs: lib$(PGMASCLIB).a lib$(PGMASCLIB).@[email protected] +libs: lib$(PGMASCLIB).a #lib$(PGMASCLIB).@[email protected]: $(LIBOBJS) # $(CC) -fPIC -shared -Wl,-h$@ -o $@ $(LIBOBJS) @@ -109,17 +110,17 @@ $(LIBOBJS): Makefile # PHONY = don't look at file clean, -rm = start rm and ignore errors .PHONY : clean proper install uninstall install: all - #$(INSTALL) -d $(DESTDIR)$(bindir) $(DESTDIR)$(libdir) $(DESTDIR)$(includedir) - $(INSTALL) -d $(DESTDIR)$(bindir) + $(INSTALL) -d $(DESTDIR)$(bindir) $(DESTDIR)$(libdir) $(DESTDIR)$(includedir) + #$(INSTALL) -d $(DESTDIR)$(bindir) $(INSTALL) $(PROGRAM) $(DESTDIR)$(bindir) $(INSTALL) ../bin/gocr.tcl $(DESTDIR)$(bindir) # better X11/bin? if test -f lib$(PGMASCLIB).a; then\ $(INSTALL) lib$(PGMASCLIB).a $(DESTDIR)$(libdir);\ $(INSTALL) lib$(PGMASCLIB).@[email protected] $(DESTDIR)$(libdir);\ $(INSTALL) lib$(PGMASCLIB).so $(DESTDIR)$(libdir);\ + $(INSTALL) $(INCLUDEFILES) $(DESTDIR)$(includedir);\ + $(INSTALL) ../include/config.h $(DESTDIR)$(includedir);\ fi - # ToDo: not sure that the link will be installed correctly - #$(INSTALL) $(INCLUDEFILES) $(DESTDIR)$(includedir) # directories are not removed uninstall: @@ -129,7 +130,8 @@ uninstall: -rm -f $(DESTDIR)$(libdir)/lib$(PGMASCLIB).@[email protected] -rm -f $(DESTDIR)$(libdir)/lib$(PGMASCLIB).so # ToDo: set to old version.so ? - #for X in $(INCLUDEFILES); do rm -f $(DESTDIR)$(includedir)/$$X; done + for X in $(INCLUDEFILES); do rm -f $(DESTDIR)$(includedir)/$$X; done + -rm -f $(DESTDIR)$(includedir)/config.h clean: -rm -f *.o *~
34.972727
92
0.669613
f80a481c4b9eef465c7af33bf6af599e61c3d155
2,465
# Copyright (C) 2010 Tom Verbeure, Simon Tokumine # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module GData module Client class FusionTables < Base SERVICE_URL = "https://tables.googlelabs.com/api/query" DATATYPES = %w(number string location datetime) def initialize(options = {}) options[:clientlogin_service] ||= 'fusiontables' options[:headers] = { 'Content-Type' => 'application/x-www-form-urlencoded' } super(options) end def sql_encode(sql) "sql=" + CGI::escape(sql) end def sql_get(sql) resp = self.get(SERVICE_URL + "?" + sql_encode(sql)) end def sql_post(sql) resp = self.post(SERVICE_URL, sql_encode(sql)) end def sql_put(sql) resp = self.put(SERVICE_URL, sql_encode(sql)) end # Overrides auth_handler= so if the authentication changes, # the session cookie is cleared. def auth_handler=(handler) @session_cookie = nil return super(handler) end # Overrides make_request to handle 500 redirects with a session cookie. def make_request(method, url, body = '', retries = 10) begin response = super(method, url, body) rescue GData::Client::ServerError => e if e.response.status_code == 500 and retries > 0 sleep_time = 11 - retries sleep sleep_time # <= Fusion tables has rate of 5 calls per second. Be nice, get longer @session_cookie = e.response.headers['set-cookie'] return self.make_request(method, url, body, retries - 1) else return e.response end end end # Custom prepare_headers to include the session cookie if it exists def prepare_headers if @session_cookie @headers['cookie'] = @session_cookie end super end end end end
32.012987
99
0.63002
79ab4231bea9c25db276132eb1350e6a93f9abc5
760
# frozen_string_literal: true Gem::Specification.new do |spec| spec.name = "example" spec.version = "0.9.3" spec.summary = "Automated dependency management" spec.description = "Core logic for updating a GitHub repos dependencies" spec.author = "Dependabot" spec.email = "[email protected]" spec.homepage = "https://github.com/hmarr/example" spec.license = "MIT" spec.require_path = "lib" spec.files = Dir["CHANGELOG.md", "LICENSE.txt", "README.md", "lib/**/*", "helpers/**/*"] spec.required_ruby_version = ">= 2.4.0" spec.required_rubygems_version = ">= 2.6.11" spec.add_dependency 'business', '1.0.0' spec.add_dependency 'statesman', '= 1.0.0' end
33.043478
75
0.621053
ff3fda88f87650fde950c60360dd6d7b901951ed
2,609
require 'spec_helper' describe Atreides::Site do describe "validation" do before do @site = Factory.create(:site) end it "should be valid and create a site" do site = Atreides::Site.new(:name => "www-2") site.valid?.should eql(true) site.save.should eql(true) site.lang.should eql(I18n.locale) end it "should not be valid with non-unique name" do site = Atreides::Site.new(:name => @site.name) site.save.should eql(false) site.valid?.should eql(false) site.errors[:name].nil?.should eql(false) end it "should not be valid without a name" do site = Atreides::Site.new() site.save.should eql(false) site.valid?.should eql(false) site.errors[:name].nil?.should eql(false) end it "should not be valid with an unknown lang" do site = Atreides::Site.new(:lang => :jp) site.save.should eql(false) site.valid?.should eql(false) site.errors[:lang].nil?.should eql(false) end end describe "site scoping" do before do @site_www = Atreides::Site.default @post_www = Factory.create(:post, :site => @site_www) @page_www = Factory.create(:page, :site => @site_www) @feature_www = Factory.create(:feature, :site => @site_www) @site_blog = Factory.create(:site) @post_blog = Factory.create(:post, :site => @site_blog) @page_blog = Factory.create(:page, :site => @site_blog) @feature_blog = Factory.create(:feature, :site => @site_blog) end it "should include different posts for different sites" do # Not empty? [@site_www.posts, @site_www.pages, @site_www.features, @site_blog.posts, @site_blog.pages, @site_blog.features].each do |coll| coll.empty?.should eql(false) end # Positives @site_blog.posts.include?(@post_blog).should eql(true) @site_blog.pages.include?(@page_blog).should eql(true) @site_blog.features.include?(@feature_blog).should eql(true) @site_www.posts.include?(@post_www).should eql(true) @site_www.pages.include?(@page_www).should eql(true) @site_www.features.include?(@feature_www).should eql(true) # Negatives @site_blog.posts.include?(@post_www).should eql(false) @site_blog.pages.include?(@page_www).should eql(false) @site_blog.features.include?(@feature_www).should eql(false) @site_www.posts.include?(@post_blog).should eql(false) @site_www.pages.include?(@page_blog).should eql(false) @site_www.features.include?(@feature_blog).should eql(false) end end end
32.6125
132
0.65504
3399aa5406b52a11b105e50248f6f301199a0a28
1,152
# Configure Rails Environment ENV["RAILS_ENV"] = "test" require File.expand_path("../../spec/dummy/config/environment.rb", __FILE__) ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../spec/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 # Load support files Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } # 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.fixtures :all end require 'minitest/spec' FactoryGirl.definition_file_paths = %w(spec/factories) FactoryGirl.find_definitions class MiniTest::Spec include FactoryGirl::Syntax::Methods end DatabaseCleaner.strategy = :transaction class Minitest::Spec before :each do DatabaseCleaner.start end after :each do DatabaseCleaner.clean end end
27.428571
101
0.773438
f740d702d322505c9435c75f56ad45d1db3a996e
341
require 'spec_helper' describe "pending_actions/index" do before(:each) do assign(:pending_actions, [ stub_model(PendingAction), stub_model(PendingAction) ]) end it "renders a list of pending_actions" do render # Run the generator again with the --webrat flag if you want to use webrat matchers end end
21.3125
87
0.703812
386feabe94d2ab5b35f5c1f5ca83265f8c9ad954
455
class SessionsController < ApplicationController def new end def create user = User.find_by_email(params[:email]) if user && user.authenticate(params[:password]) session[:user_id] = user.id redirect_to root_url, notice: "Logged in!" else flash.now.alert = "Invalid email or password" render "new" end end def destroy session[:user_id] = nil redirect_to root_url, notice: "Logged out!" end end
21.666667
51
0.668132
ff7a75b652d5290d1d3b92768d8498206abec6b6
28,381
## # This code was generated by # \ / _ _ _| _ _ # | (_)\/(_)(_|\/| |(/_ v1.0.0 # / / # # frozen_string_literal: true module Twilio module REST class Api < Domain class V2010 < Version class AccountContext < InstanceContext class AvailablePhoneNumberCountryContext < InstanceContext class SharedCostList < ListResource ## # Initialize the SharedCostList # @param [Version] version Version that contains the resource # @param [String] account_sid The account_sid # @param [String] country_code The # [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of # the country. # @return [SharedCostList] SharedCostList def initialize(version, account_sid: nil, country_code: nil) super(version) # Path Solution @solution = {account_sid: account_sid, country_code: country_code} @uri = "/Accounts/#{@solution[:account_sid]}/AvailablePhoneNumbers/#{@solution[:country_code]}/SharedCost.json" end ## # Lists SharedCostInstance records from the API as a list. # Unlike stream(), this operation is eager and will load `limit` records into # memory before returning. # @param [String] area_code The area code of the phone numbers to read. Applies to # only phone numbers in the US and Canada. # @param [String] contains The pattern on which to match phone numbers. Valid # characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any # single digit. For examples, see [Example # 2](https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-3). If specified, this value must have at least two characters. # @param [Boolean] sms_enabled Whether the phone numbers can receive text # messages. Can be: `true` or `false`. # @param [Boolean] mms_enabled Whether the phone numbers can receive MMS messages. # Can be: `true` or `false`. # @param [Boolean] voice_enabled Whether the phone numbers can receive calls. Can # be: `true` or `false`. # @param [Boolean] exclude_all_address_required Whether to exclude phone numbers # that require an [Address](https://www.twilio.com/docs/usage/api/addresses). Can # be: `true` or `false` and the default is `false`. # @param [Boolean] exclude_local_address_required Whether to exclude phone numbers # that require a local [Address](https://www.twilio.com/docs/usage/api/addresses). # Can be: `true` or `false` and the default is `false`. # @param [Boolean] exclude_foreign_address_required Whether to exclude phone # numbers that require a foreign # [Address](https://www.twilio.com/docs/usage/api/addresses). Can be: `true` or # `false` and the default is `false`. # @param [Boolean] beta Whether to read phone numbers that are new to the Twilio # platform. Can be: `true` or `false` and the default is `true`. # @param [String] near_number Given a phone number, find a geographically close # number within `distance` miles. Distance defaults to 25 miles. Applies to only # phone numbers in the US and Canada. # @param [String] near_lat_long Given a latitude/longitude pair `lat,long` find # geographically close numbers within `distance` miles. Applies to only phone # numbers in the US and Canada. # @param [String] distance The search radius, in miles, for a `near_` query. Can # be up to `500` and the default is `25`. Applies to only phone numbers in the US # and Canada. # @param [String] in_postal_code Limit results to a particular postal code. Given # a phone number, search within the same postal code as that number. Applies to # only phone numbers in the US and Canada. # @param [String] in_region Limit results to a particular region, state, or # province. Given a phone number, search within the same region as that number. # Applies to only phone numbers in the US and Canada. # @param [String] in_rate_center Limit results to a specific rate center, or given # a phone number search within the same rate center as that number. Requires # `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. # @param [String] in_lata Limit results to a specific local access and transport # area ([LATA](http://en.wikipedia.org/wiki/Local_access_and_transport_area)). # Given a phone number, search within the same # [LATA](http://en.wikipedia.org/wiki/Local_access_and_transport_area) as that # number. Applies to only phone numbers in the US and Canada. # @param [String] in_locality Limit results to a particular locality or city. # Given a phone number, search within the same Locality as that number. # @param [Boolean] fax_enabled Whether the phone numbers can receive faxes. Can # be: `true` or `false`. # @param [Integer] limit Upper limit for the number of records to return. stream() # guarantees to never return more than limit. Default is no limit # @param [Integer] page_size Number of records to fetch per request, when # not set will use the default value of 50 records. If no page_size is defined # but a limit is defined, stream() will attempt to read the limit with the most # efficient page size, i.e. min(limit, 1000) # @return [Array] Array of up to limit results def list(area_code: :unset, contains: :unset, sms_enabled: :unset, mms_enabled: :unset, voice_enabled: :unset, exclude_all_address_required: :unset, exclude_local_address_required: :unset, exclude_foreign_address_required: :unset, beta: :unset, near_number: :unset, near_lat_long: :unset, distance: :unset, in_postal_code: :unset, in_region: :unset, in_rate_center: :unset, in_lata: :unset, in_locality: :unset, fax_enabled: :unset, limit: nil, page_size: nil) self.stream( area_code: area_code, contains: contains, sms_enabled: sms_enabled, mms_enabled: mms_enabled, voice_enabled: voice_enabled, exclude_all_address_required: exclude_all_address_required, exclude_local_address_required: exclude_local_address_required, exclude_foreign_address_required: exclude_foreign_address_required, beta: beta, near_number: near_number, near_lat_long: near_lat_long, distance: distance, in_postal_code: in_postal_code, in_region: in_region, in_rate_center: in_rate_center, in_lata: in_lata, in_locality: in_locality, fax_enabled: fax_enabled, limit: limit, page_size: page_size ).entries end ## # Streams SharedCostInstance records from the API as an Enumerable. # This operation lazily loads records as efficiently as possible until the limit # is reached. # @param [String] area_code The area code of the phone numbers to read. Applies to # only phone numbers in the US and Canada. # @param [String] contains The pattern on which to match phone numbers. Valid # characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any # single digit. For examples, see [Example # 2](https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-3). If specified, this value must have at least two characters. # @param [Boolean] sms_enabled Whether the phone numbers can receive text # messages. Can be: `true` or `false`. # @param [Boolean] mms_enabled Whether the phone numbers can receive MMS messages. # Can be: `true` or `false`. # @param [Boolean] voice_enabled Whether the phone numbers can receive calls. Can # be: `true` or `false`. # @param [Boolean] exclude_all_address_required Whether to exclude phone numbers # that require an [Address](https://www.twilio.com/docs/usage/api/addresses). Can # be: `true` or `false` and the default is `false`. # @param [Boolean] exclude_local_address_required Whether to exclude phone numbers # that require a local [Address](https://www.twilio.com/docs/usage/api/addresses). # Can be: `true` or `false` and the default is `false`. # @param [Boolean] exclude_foreign_address_required Whether to exclude phone # numbers that require a foreign # [Address](https://www.twilio.com/docs/usage/api/addresses). Can be: `true` or # `false` and the default is `false`. # @param [Boolean] beta Whether to read phone numbers that are new to the Twilio # platform. Can be: `true` or `false` and the default is `true`. # @param [String] near_number Given a phone number, find a geographically close # number within `distance` miles. Distance defaults to 25 miles. Applies to only # phone numbers in the US and Canada. # @param [String] near_lat_long Given a latitude/longitude pair `lat,long` find # geographically close numbers within `distance` miles. Applies to only phone # numbers in the US and Canada. # @param [String] distance The search radius, in miles, for a `near_` query. Can # be up to `500` and the default is `25`. Applies to only phone numbers in the US # and Canada. # @param [String] in_postal_code Limit results to a particular postal code. Given # a phone number, search within the same postal code as that number. Applies to # only phone numbers in the US and Canada. # @param [String] in_region Limit results to a particular region, state, or # province. Given a phone number, search within the same region as that number. # Applies to only phone numbers in the US and Canada. # @param [String] in_rate_center Limit results to a specific rate center, or given # a phone number search within the same rate center as that number. Requires # `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. # @param [String] in_lata Limit results to a specific local access and transport # area ([LATA](http://en.wikipedia.org/wiki/Local_access_and_transport_area)). # Given a phone number, search within the same # [LATA](http://en.wikipedia.org/wiki/Local_access_and_transport_area) as that # number. Applies to only phone numbers in the US and Canada. # @param [String] in_locality Limit results to a particular locality or city. # Given a phone number, search within the same Locality as that number. # @param [Boolean] fax_enabled Whether the phone numbers can receive faxes. Can # be: `true` or `false`. # @param [Integer] limit Upper limit for the number of records to return. stream() # guarantees to never return more than limit. Default is no limit. # @param [Integer] page_size Number of records to fetch per request, when # not set will use the default value of 50 records. If no page_size is defined # but a limit is defined, stream() will attempt to read the limit with the most # efficient page size, i.e. min(limit, 1000) # @return [Enumerable] Enumerable that will yield up to limit results def stream(area_code: :unset, contains: :unset, sms_enabled: :unset, mms_enabled: :unset, voice_enabled: :unset, exclude_all_address_required: :unset, exclude_local_address_required: :unset, exclude_foreign_address_required: :unset, beta: :unset, near_number: :unset, near_lat_long: :unset, distance: :unset, in_postal_code: :unset, in_region: :unset, in_rate_center: :unset, in_lata: :unset, in_locality: :unset, fax_enabled: :unset, limit: nil, page_size: nil) limits = @version.read_limits(limit, page_size) page = self.page( area_code: area_code, contains: contains, sms_enabled: sms_enabled, mms_enabled: mms_enabled, voice_enabled: voice_enabled, exclude_all_address_required: exclude_all_address_required, exclude_local_address_required: exclude_local_address_required, exclude_foreign_address_required: exclude_foreign_address_required, beta: beta, near_number: near_number, near_lat_long: near_lat_long, distance: distance, in_postal_code: in_postal_code, in_region: in_region, in_rate_center: in_rate_center, in_lata: in_lata, in_locality: in_locality, fax_enabled: fax_enabled, page_size: limits[:page_size], ) @version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit]) end ## # When passed a block, yields SharedCostInstance records from the API. # This operation lazily loads records as efficiently as possible until the limit # is reached. def each limits = @version.read_limits page = self.page(page_size: limits[:page_size], ) @version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit]).each {|x| yield x} end ## # Retrieve a single page of SharedCostInstance records from the API. # Request is executed immediately. # @param [String] area_code The area code of the phone numbers to read. Applies to # only phone numbers in the US and Canada. # @param [String] contains The pattern on which to match phone numbers. Valid # characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any # single digit. For examples, see [Example # 2](https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-3). If specified, this value must have at least two characters. # @param [Boolean] sms_enabled Whether the phone numbers can receive text # messages. Can be: `true` or `false`. # @param [Boolean] mms_enabled Whether the phone numbers can receive MMS messages. # Can be: `true` or `false`. # @param [Boolean] voice_enabled Whether the phone numbers can receive calls. Can # be: `true` or `false`. # @param [Boolean] exclude_all_address_required Whether to exclude phone numbers # that require an [Address](https://www.twilio.com/docs/usage/api/addresses). Can # be: `true` or `false` and the default is `false`. # @param [Boolean] exclude_local_address_required Whether to exclude phone numbers # that require a local [Address](https://www.twilio.com/docs/usage/api/addresses). # Can be: `true` or `false` and the default is `false`. # @param [Boolean] exclude_foreign_address_required Whether to exclude phone # numbers that require a foreign # [Address](https://www.twilio.com/docs/usage/api/addresses). Can be: `true` or # `false` and the default is `false`. # @param [Boolean] beta Whether to read phone numbers that are new to the Twilio # platform. Can be: `true` or `false` and the default is `true`. # @param [String] near_number Given a phone number, find a geographically close # number within `distance` miles. Distance defaults to 25 miles. Applies to only # phone numbers in the US and Canada. # @param [String] near_lat_long Given a latitude/longitude pair `lat,long` find # geographically close numbers within `distance` miles. Applies to only phone # numbers in the US and Canada. # @param [String] distance The search radius, in miles, for a `near_` query. Can # be up to `500` and the default is `25`. Applies to only phone numbers in the US # and Canada. # @param [String] in_postal_code Limit results to a particular postal code. Given # a phone number, search within the same postal code as that number. Applies to # only phone numbers in the US and Canada. # @param [String] in_region Limit results to a particular region, state, or # province. Given a phone number, search within the same region as that number. # Applies to only phone numbers in the US and Canada. # @param [String] in_rate_center Limit results to a specific rate center, or given # a phone number search within the same rate center as that number. Requires # `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. # @param [String] in_lata Limit results to a specific local access and transport # area ([LATA](http://en.wikipedia.org/wiki/Local_access_and_transport_area)). # Given a phone number, search within the same # [LATA](http://en.wikipedia.org/wiki/Local_access_and_transport_area) as that # number. Applies to only phone numbers in the US and Canada. # @param [String] in_locality Limit results to a particular locality or city. # Given a phone number, search within the same Locality as that number. # @param [Boolean] fax_enabled Whether the phone numbers can receive faxes. Can # be: `true` or `false`. # @param [String] page_token PageToken provided by the API # @param [Integer] page_number Page Number, this value is simply for client state # @param [Integer] page_size Number of records to return, defaults to 50 # @return [Page] Page of SharedCostInstance def page(area_code: :unset, contains: :unset, sms_enabled: :unset, mms_enabled: :unset, voice_enabled: :unset, exclude_all_address_required: :unset, exclude_local_address_required: :unset, exclude_foreign_address_required: :unset, beta: :unset, near_number: :unset, near_lat_long: :unset, distance: :unset, in_postal_code: :unset, in_region: :unset, in_rate_center: :unset, in_lata: :unset, in_locality: :unset, fax_enabled: :unset, page_token: :unset, page_number: :unset, page_size: :unset) params = Twilio::Values.of({ 'AreaCode' => area_code, 'Contains' => contains, 'SmsEnabled' => sms_enabled, 'MmsEnabled' => mms_enabled, 'VoiceEnabled' => voice_enabled, 'ExcludeAllAddressRequired' => exclude_all_address_required, 'ExcludeLocalAddressRequired' => exclude_local_address_required, 'ExcludeForeignAddressRequired' => exclude_foreign_address_required, 'Beta' => beta, 'NearNumber' => near_number, 'NearLatLong' => near_lat_long, 'Distance' => distance, 'InPostalCode' => in_postal_code, 'InRegion' => in_region, 'InRateCenter' => in_rate_center, 'InLata' => in_lata, 'InLocality' => in_locality, 'FaxEnabled' => fax_enabled, 'PageToken' => page_token, 'Page' => page_number, 'PageSize' => page_size, }) response = @version.page( 'GET', @uri, params ) SharedCostPage.new(@version, response, @solution) end ## # Retrieve a single page of SharedCostInstance records from the API. # Request is executed immediately. # @param [String] target_url API-generated URL for the requested results page # @return [Page] Page of SharedCostInstance def get_page(target_url) response = @version.domain.request( 'GET', target_url ) SharedCostPage.new(@version, response, @solution) end ## # Provide a user friendly representation def to_s '#<Twilio.Api.V2010.SharedCostList>' end end class SharedCostPage < Page ## # Initialize the SharedCostPage # @param [Version] version Version that contains the resource # @param [Response] response Response from the API # @param [Hash] solution Path solution for the resource # @return [SharedCostPage] SharedCostPage def initialize(version, response, solution) super(version, response) # Path Solution @solution = solution end ## # Build an instance of SharedCostInstance # @param [Hash] payload Payload response from the API # @return [SharedCostInstance] SharedCostInstance def get_instance(payload) SharedCostInstance.new( @version, payload, account_sid: @solution[:account_sid], country_code: @solution[:country_code], ) end ## # Provide a user friendly representation def to_s '<Twilio.Api.V2010.SharedCostPage>' end end class SharedCostInstance < InstanceResource ## # Initialize the SharedCostInstance # @param [Version] version Version that contains the resource # @param [Hash] payload payload that contains response from Twilio # @param [String] account_sid The account_sid # @param [String] country_code The # [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of # the country. # @return [SharedCostInstance] SharedCostInstance def initialize(version, payload, account_sid: nil, country_code: nil) super(version) # Marshaled Properties @properties = { 'friendly_name' => payload['friendly_name'], 'phone_number' => payload['phone_number'], 'lata' => payload['lata'], 'locality' => payload['locality'], 'rate_center' => payload['rate_center'], 'latitude' => payload['latitude'].to_f, 'longitude' => payload['longitude'].to_f, 'region' => payload['region'], 'postal_code' => payload['postal_code'], 'iso_country' => payload['iso_country'], 'address_requirements' => payload['address_requirements'], 'beta' => payload['beta'], 'capabilities' => payload['capabilities'], } end ## # @return [String] A formatted version of the phone number def friendly_name @properties['friendly_name'] end ## # @return [String] The phone number in E.164 format def phone_number @properties['phone_number'] end ## # @return [String] The LATA of this phone number def lata @properties['lata'] end ## # @return [String] The locality or city of this phone number's location def locality @properties['locality'] end ## # @return [String] The rate center of this phone number def rate_center @properties['rate_center'] end ## # @return [String] The latitude of this phone number's location def latitude @properties['latitude'] end ## # @return [String] The longitude of this phone number's location def longitude @properties['longitude'] end ## # @return [String] The two-letter state or province abbreviation of this phone number's location def region @properties['region'] end ## # @return [String] The postal or ZIP code of this phone number's location def postal_code @properties['postal_code'] end ## # @return [String] The ISO country code of this phone number def iso_country @properties['iso_country'] end ## # @return [String] The type of Address resource the phone number requires def address_requirements @properties['address_requirements'] end ## # @return [Boolean] Whether the phone number is new to the Twilio platform def beta @properties['beta'] end ## # @return [String] Whether a phone number can receive calls or messages def capabilities @properties['capabilities'] end ## # Provide a user friendly representation def to_s "<Twilio.Api.V2010.SharedCostInstance>" end ## # Provide a detailed, user friendly representation def inspect "<Twilio.Api.V2010.SharedCostInstance>" end end end end end end end end
57.567951
506
0.572637
e2b1b671dfcb9b453760fd9f14de3bdbd8c3a857
1,476
require 'pry' require_relative './laboratory_test_result' require_relative './format_conversor' class Parser DELIMITER = "|" LAB_RESULT_START_TOKEN = "OBX|" LAB_COMMENT_START_TOKEN = "NTE|" TEST_TYPES = { C100: "float", C200: "float", A250: "boolean", B250: "nil_3plus" } def initialize(file_path) content = File.read(file_path).gsub("\n", "") @conversor = FormatConversor.new @lab_tests = map_tests(content) end def mapped_results mapped_results = [] @lab_tests.map do |test| result = extract_test_result(test.shift) comment = extract_comment(test) LaboratoryTestResult.new(code: result[:code], result: result[:result], format: result[:format], comment: comment ) end end private def map_tests(tests_string) mapped_tests = tests_string.split(LAB_RESULT_START_TOKEN) mapped_tests.shift return mapped_tests.map{|e| e.split(LAB_COMMENT_START_TOKEN)} end def extract_test_result(test_string) test = test_string.split(DELIMITER) code = test[1] result = test[2] format = TEST_TYPES.fetch(code.to_sym) return { format: format, code: code, result: @conversor.convert(result, format) } end def extract_comment(array_of_comments) return array_of_comments.map{|e| e.split(DELIMITER).last}.join("\n") end end
23.806452
72
0.631436
4a12ecd969803a4cf0d5b5c93cbc05f9901c107a
123
# frozen_string_literal: true FactoryBot.define do factory :field_project do sequence(:kobo_id) { |n| n } end end
15.375
32
0.715447
91355d352b4ed44523f032fcbcc8b3908b59e59c
150
require 'test_helper' class TranslationEngineTest < ActiveSupport::TestCase test "truth" do assert_kind_of Module, TranslationEngine end end
18.75
53
0.793333
3330fd5dcc3107df2994d28575347da6377697c3
768
# frozen_string_literal: true require 'puppet/provider/a2mod' Puppet::Type.type(:a2mod).provide(:a2mod, parent: Puppet::Provider::A2mod) do desc 'Manage Apache 2 modules on Debian and Ubuntu' optional_commands encmd: 'a2enmod' optional_commands discmd: 'a2dismod' commands apache2ctl: 'apache2ctl' confine osfamily: :debian defaultfor operatingsystem: [:debian, :ubuntu] def self.instances modules = apache2ctl('-M').lines.map { |line| m = line.match(%r{(\w+)_module \(shared\)$}) m[1] if m }.compact modules.map do |mod| new( name: mod, ensure: :present, provider: :a2mod, ) end end def create encmd resource[:name] end def destroy discmd resource[:name] end end
20.210526
77
0.64974
6216f0db8a17336034f10d97c47c5178e019120a
1,240
class Pwntools < Formula include Language::Python::Virtualenv desc "CTF framework used by Gallopsled in every CTF" homepage "https://github.com/Gallopsled/pwntools" url "https://github.com/Gallopsled/pwntools/archive/3.12.2.tar.gz" sha256 "8e048b514ee449b4c76f4eba1b4fcd48fdefd1bf04ae4c62b44e984923d2e979" revision 1 bottle do cellar :any sha256 "258e2df2d025801d2173307b68639b968f0293d3d5f9acb8c7a884e5cd639768" => :mojave sha256 "3a6fa84fbdd9683af6b5800fd4fa14e8369419f3a8abc9b5e8bd23bde447c3a5" => :high_sierra sha256 "60d76ec99a2646e6ea82e226aff196f45af7d209c36ed848cc29dea52b5e1c54" => :sierra end depends_on "[email protected]" depends_on "python@2" # does not support Python 3 conflicts_with "moreutils", :because => "Both install `errno` binaries" def install venv = virtualenv_create(libexec) system libexec/"bin/pip", "install", "-v", "--no-binary", ":all:", "--ignore-installed", buildpath system libexec/"bin/pip", "uninstall", "-y", name venv.pip_install_and_link buildpath end test do assert_equal "686f6d6562726577696e7374616c6c636f6d706c657465", shell_output("#{bin}/hex homebrewinstallcomplete").strip end end
35.428571
93
0.735484
ed6d1aebe2334dc2ed215c038268a0e832a88b70
2,447
require 'thor' require "rake-pipeline" require 'rake-pipeline-web-filters' require 'fileutils' require_relative 'recipes' require 'pry' module CSConsole class CLI < Thor include Thor::Actions desc "build", "Build the cs_console with various recipes" method_option :build_type, default: :all, aliases: '-t', desc: 'Specify a build type. Use the -l option to list possible builds.' method_option :list_builds, aliases: '-l', desc: "List Build types and their descriptions" def build if options[:list_builds] CSConsole::Recipes.list.each do |recipe| recipe_class = CSConsole::Recipes.get_recipe(recipe) say "#{recipe_class.description}\n" end else puts "Compiling files..." project.invoke puts "Adding license to compiled files..." add_license_to_files('./compiled/cs_console.css', './compiled/cs_console.js') puts "Adding version to compiled files..." add_version_to_files('./compiled/cs_console.css', './compiled/cs_console.js') puts 'Cleaning up temporary files...' clean_up_temp_files puts 'Finished! Compiled files can be found in /compiled' end end private def project unless @project build_options = nil if recipe.build_options build_options = instance_exec(&recipe.build_options) end @project ||= Rake::Pipeline::Project.new.build(&recipe.build(build_options)) end @project end def recipe @recipe ||= CSConsole::Recipes.get_recipe(options[:build_type]) end def clean_up_temp_files FileUtils.rm_rf(File.expand_path('./tmp')) end def add_license_to_files(*file_paths) license_content = File.read(File.expand_path('./LICENSE')) file_paths.each do |file_path| compiled_file = File.expand_path(file_path) compiled_fileContent = File.read(compiled_file) File.write(compiled_file, "/*\n#{license_content}\n*/\n\n#{compiled_fileContent}") end end def add_version_to_files(*file_paths) version_content = File.read(File.expand_path('./Version')) file_paths.each do |file_path| compiled_file = File.expand_path(file_path) compiled_fileContent = File.read(compiled_file) File.write(compiled_file, "/*\nCS Console Version: #{version_content}\n*/\n\n#{compiled_fileContent}") end end end end
32.197368
133
0.669391
f891de403d83a5b0c732b3ffada668d1d1df5925
264
# frozen_string_literal: true require 'mkmf' config_string("strict_warnflags") {|w| $warnflags += " #{w}"} with_werror("", {:werror => true}) do |opt, | have_var("timezone", "time.h", opt) have_var("altzone", "time.h", opt) end create_makefile('date_core')
22
61
0.666667
111c732168257bffd12473c9a5052823a2a073e0
889
# frozen_string_literal: true # Omniauth callacks for SAML authentication class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController # rubocop:disable Style/ClassAndModuleChildren skip_before_action :authenticate_user! protect_from_forgery with: :exception, except: :saml def passthru redirect_to new_user_session_path end def saml auth_hash = request.env['omniauth.auth'] email = auth_hash.info.email.first roles = sanitize_saml_roles(auth_hash.info.roles || []) redirect_to(unauthorized_user_path) and return unless roles.include?('administrator') @user = User.create_or_find_by!(email: email, uid: email, provider: 'saml') sign_in(@user) redirect_to(root_path) end private def sanitize_saml_roles(roles) roles.map do |role| role.downcase.sub(/^handle-/, '').gsub(/-/, '_') end end end
27.78125
125
0.731159
189dde8e151f7a31277b0f60c3e92dab81ac24c1
73
require 'test_helper' class ClinicHelperTest < ActionView::TestCase end
14.6
45
0.821918
03389154b90bf63f2edc6e8322e1c47fc57fd5dd
3,199
class Heartbeat < Formula desc "Lightweight Shipper for Uptime Monitoring" homepage "https://www.elastic.co/beats/heartbeat" url "https://github.com/elastic/beats.git", tag: "v8.1.3", revision: "271435c21bfd4e2e621d87c04f4b815980626978" license "Apache-2.0" head "https://github.com/elastic/beats.git", branch: "master" bottle do sha256 cellar: :any_skip_relocation, arm64_monterey: "e8f014d1c59e23f1af3738dad27941c681c661074670237f67ce300845538338" sha256 cellar: :any_skip_relocation, arm64_big_sur: "f43d576b6a50ab09787cee262f78c7dbbe30d30d83da787950ea908383ac5202" sha256 cellar: :any_skip_relocation, monterey: "28872e7c3c3b02ebe6fe7e7ca7251110465662e55c810b450027c0d1ffa02ce1" sha256 cellar: :any_skip_relocation, big_sur: "ff37a7a538a216556e89085c3ddf6ed5ea41a2f4e823d9f873769b0e03d8733c" sha256 cellar: :any_skip_relocation, catalina: "c7804bbf23e8db6d6a9e8cd05b99e74644dc9758ba79f64110fc9a4afcdb5268" sha256 cellar: :any_skip_relocation, x86_64_linux: "30d957dbd17fd206a5b829344976440940271bf68fbd137861cf0046bcc3e508" end depends_on "go" => :build depends_on "mage" => :build depends_on "[email protected]" => :build uses_from_macos "netcat" => :test def install # remove non open source files rm_rf "x-pack" cd "heartbeat" do # prevent downloading binary wheels during python setup system "make", "PIP_INSTALL_PARAMS=--no-binary :all", "python-env" system "mage", "-v", "build" ENV.deparallelize system "mage", "-v", "update" (etc/"heartbeat").install Dir["heartbeat.*", "fields.yml"] (libexec/"bin").install "heartbeat" end (bin/"heartbeat").write <<~EOS #!/bin/sh exec #{libexec}/bin/heartbeat \ --path.config #{etc}/heartbeat \ --path.data #{var}/lib/heartbeat \ --path.home #{prefix} \ --path.logs #{var}/log/heartbeat \ "$@" EOS end def post_install (var/"lib/heartbeat").mkpath (var/"log/heartbeat").mkpath end service do run opt_bin/"heartbeat" end test do # FIXME: This keeps stalling CI when tested as a dependent. See, for example, # https://github.com/Homebrew/homebrew-core/pull/91712 return if OS.linux? && ENV["HOMEBREW_GITHUB_ACTIONS"].present? port = free_port (testpath/"config/heartbeat.yml").write <<~EOS heartbeat.monitors: - type: tcp schedule: '@every 5s' hosts: ["localhost:#{port}"] check.send: "hello\\n" check.receive: "goodbye\\n" output.file: path: "#{testpath}/heartbeat" filename: heartbeat codec.format: string: '%{[monitor]}' EOS fork do exec bin/"heartbeat", "-path.config", testpath/"config", "-path.data", testpath/"data" end sleep 5 assert_match "hello", pipe_output("nc -l #{port}", "goodbye\n", 0) sleep 5 output = JSON.parse((testpath/"data/meta.json").read) assert_includes output, "first_start" (testpath/"data").glob("heartbeat-*.ndjson") do |file| s = JSON.parse(file.read) assert_match "up", s["status"] end end end
33.322917
123
0.663957
e9abd204257793338b6ef5ff31581a18596bd61d
2,833
module SirTrevor module Helpers module ViewHelper extend ActiveSupport::Concern include Twitter::Autolink def render_sir_trevor(json, image_type = 'large') if hash = parse_sir_trevor(json) hash.map { |object| render_sir_trevor_block(object, image_type) }.compact.join.html_safe else '' end end def render_sir_trevor_block(object, image_type = 'large') view_name = "sir-trevor/blocks/#{object['type'].to_s.downcase}_block" render(view_name, :block => object['data'], :image_type => image_type) if object.has_key?("data") end def render_sir_trevor_image(json, image_type = "large") image = pluck_sir_trevor_type(json, "image") unless image.nil? render(:partial => "sir-trevor/blocks/image_block", :locals => {:block => image['data'], :image_type => image_type, :protocol => request.protocol}) if image.has_key?("data") end end def sir_trevor_image_tag(block, image_type) # Does the image type exist on the block? if(block['file'].present? && block['file'][image_type].present?) image = block['file'][image_type] image_url = image['url'] width = image['width'] if image['width'].present? height = image['height'] if image['height'].present? options = { :class => "sir-trevor-image #{image_type}", :alt => block['description'] } options.merge!({ :width => width }) unless width.nil? options.merge!({ :height => height }) unless height.nil? image_tag(image_url, options) unless image_url.nil? end end def sir_trevor_markdown(text) options = {:hard_wrap => true, :filter_html => true, :autolink => true, :no_intra_emphasis => true, :fenced_code_blocks => true, link_attributes: { rel: 'nofollow', target: '_blank' }} markdown = Redcarpet::Markdown.new(CustomMarkdownFormatter.new(options)) markdown.render(text).html_safe end def parse_sir_trevor(json) hash = JSON.parse(json) return false unless hash.has_key?("data") hash["data"] end private # Get's the first instance of a type from the specified JSON def pluck_sir_trevor_type(json, type) hash = JSON.parse(json) if hash.has_key?("data") item = hash["data"].select { |item| item["type"] == type } item.first end end end end end class CustomMarkdownFormatter < Redcarpet::Render::HTML def block_code(code, language) "<p>" << code << "</p>" end def codespan(code) code end end
31.131868
192
0.58101
6130f357d6720d1ee7962ec085821bbd5dd4dd5e
1,392
=begin Copyright 2010-2017 Sarosys LLC <http://www.sarosys.com> This file is part of the Arachni Framework project and is subject to redistribution and commercial restrictions. Please see the Arachni Framework web site for more information on licensing and terms of use. =end class Arachni::Checks::Body < Arachni::Check::Base def prepare @prepared = true end def run return if !@prepared @ran = true end def clean_up return if !@ran log_issue( vector: Factory[:body_vector] ) end def self.info { name: 'Test check', description: %q{Test description}, author: 'Tasos "Zapotek" Laskos <[email protected]> ', version: '0.1', references: { 'Wikipedia' => 'http://en.wikipedia.org/' }, elements: [ Element::Body ], targets: { 'Generic' => 'all' }, issue: { name: "Test issue #{name.to_s}", description: %q{Test description}, tags: ['some', 'tag'], cwe: '0', severity: Severity::HIGH, remedy_guidance: %q{Watch out!.}, remedy_code: '' } } end end
28.408163
86
0.496408
f76e813347bbe61cc5c93cb7aeb077ac301a563c
3,334
class Cms::ColumnsController < ApplicationController include Cms::BaseFilter include Cms::CrudFilter model Cms::Column::Base navi_view 'cms/main/conf_navi' helper_method :column_type_options private def set_form @cur_form ||= Cms::Form.site(@cur_site).find(params[:form_id]) end def set_items set_form @items = @cur_form.columns end def set_item set_form @item = @cur_form.columns.find(params[:id]) @item.attributes = fix_params @model = @item.class rescue Mongoid::Errors::DocumentNotFound => e return render_destroy(true) if params[:action] == 'destroy' raise e end def set_crumbs set_form @crumbs << [Cms::Form.model_name.human, cms_forms_path] @crumbs << [@cur_form.name, cms_form_path(id: @cur_form)] @crumbs << [Cms::Column::Base.model_name.human, action: :index] end def fix_params set_form { cur_site: @cur_site, cur_form: @cur_form } end def pre_params ret = super || {} max_order = @cur_form.columns.max(:order) || 0 ret[:order] = max_order + 10 if @cur_form.sub_type_entry? ret[:required] = "optional" end ret end def column_type_options items = {} Cms::Column.route_options.each do |name, path| mod = path.sub(/\/.*/, '') items[mod] = { name: t("modules.#{mod}"), items: [] } if !items[mod] items[mod][:items] << [ name.sub(/.*\//, ''), path ] end items end def set_model model = self.class.model_class if params[:type].present? type = params[:type] type = type.sub('/', '/column/') type = type.classify model = type.constantize end @model = model end public def index set_items raise '403' unless @cur_form.allowed?(:read, @cur_user, site: @cur_site) @items = @items.search(params[:s]). order_by(order: 1). page(params[:page]).per(50) end def show raise '403' unless @cur_form.allowed?(:read, @cur_user, site: @cur_site, node: @cur_node) render end def new set_model raise '403' unless @cur_form.allowed?(:edit, @cur_user, site: @cur_site) @item = @model.new pre_params.merge(fix_params) end def create set_model raise '403' unless @cur_form.allowed?(:edit, @cur_user, site: @cur_site) @item = @model.new get_params render_create @item.save end def edit raise '403' unless @cur_form.allowed?(:edit, @cur_user, site: @cur_site, node: @cur_node) render end def update @item.attributes = get_params @item.in_updated = params[:_updated] if @item.respond_to?(:in_updated) raise '403' unless @cur_form.allowed?(:edit, @cur_user, site: @cur_site, node: @cur_node) render_update @item.update end def delete raise '403' unless @cur_form.allowed?(:delete, @cur_user, site: @cur_site, node: @cur_node) render end def destroy raise '403' unless @cur_form.allowed?(:delete, @cur_user, site: @cur_site, node: @cur_node) render_destroy @item.destroy end def destroy_all raise '403' unless @cur_form.allowed?(:delete, @cur_user, site: @cur_site, node: @cur_node) entries = @items.entries @items = [] entries.each do |item| next if item.destroy @items << item end render_destroy_all(entries.size != @items.size) end end
22.527027
95
0.644871
33c6c24449ccb69821524c6f3bfff84aed3a6b11
166
require 'spec_helper' require_relative './simple_check_shared' describe Gitlab::HealthChecks::DbCheck do include_examples 'simple_check', 'db_ping', 'Db', '1' end
23.714286
55
0.777108
7a3f2e368ef1f4e5bdf95898ae146d5e3052bf22
49
require_relative "app" run Sinatra::Application
12.25
24
0.816327
1d578a712a8c6a973fdd69c3b80cc7daaea2a3d1
286
module OdfCore module Element module Text class CreationTime < AbstractElement XML_ELEMENT_NAME = 'text:creation-time' CHILDREN = [].freeze ATTRIBUTES = ["style:data-style-name", "text:fixed", "text:time-value"].freeze end end end end
19.066667
86
0.636364
38961e4eff695e57f75ffa5cdc3fdc32d177240b
7,220
# frozen_string_literal: true require "active_support/core_ext/file/atomic" require "active_support/core_ext/string/conversions" require "uri/common" module ActiveSupport module Cache # A cache store implementation which stores everything on the filesystem. class FileStore < Store attr_reader :cache_path DIR_FORMATTER = "%03X" FILENAME_MAX_SIZE = 226 # max filename size on file system is 255, minus room for timestamp, pid, and random characters appended by Tempfile (used by atomic write) FILEPATH_MAX_SIZE = 900 # max is 1024, plus some room GITKEEP_FILES = [".gitkeep", ".keep"].freeze def initialize(cache_path, **options) super(options) @cache_path = cache_path.to_s end # Advertise cache versioning support. def self.supports_cache_versioning? true end # Deletes all items from the cache. In this case it deletes all the entries in the specified # file store directory except for .keep or .gitkeep. Be careful which directory is specified in your # config file when using +FileStore+ because everything in that directory will be deleted. def clear(options = nil) root_dirs = (Dir.children(cache_path) - GITKEEP_FILES) FileUtils.rm_r(root_dirs.collect { |f| File.join(cache_path, f) }) rescue Errno::ENOENT, Errno::ENOTEMPTY end # Preemptively iterates through all stored keys and removes the ones which have expired. def cleanup(options = nil) options = merged_options(options) search_dir(cache_path) do |fname| entry = read_entry(fname, **options) delete_entry(fname, **options) if entry && entry.expired? end end # Increment a cached integer value. Returns the updated value. # # If the key is unset, it starts from +0+: # # cache.increment("foo") # => 1 # cache.increment("bar", 100) # => 100 # # To set a specific value, call #write: # # cache.write("baz", 5) # cache.increment("baz") # => 6 # def increment(name, amount = 1, options = nil) modify_value(name, amount, options) end # Decrement a cached integer value. Returns the updated value. # # If the key is unset, it will be set to +-amount+. # # cache.decrement("foo") # => -1 # # To set a specific value, call #write: # # cache.write("baz", 5) # cache.decrement("baz") # => 4 # def decrement(name, amount = 1, options = nil) modify_value(name, -amount, options) end def delete_matched(matcher, options = nil) options = merged_options(options) instrument(:delete_matched, matcher.inspect) do matcher = key_matcher(matcher, options) search_dir(cache_path) do |path| key = file_path_key(path) delete_entry(path, **options) if key.match(matcher) end end end private def read_entry(key, **options) if payload = read_serialized_entry(key, **options) entry = deserialize_entry(payload) entry if entry.is_a?(Cache::Entry) end end def read_serialized_entry(key, **) File.binread(key) if File.exist?(key) rescue => error logger.error("FileStoreError (#{error}): #{error.message}") if logger nil end def write_entry(key, entry, **options) write_serialized_entry(key, serialize_entry(entry, **options), **options) end def write_serialized_entry(key, payload, **options) return false if options[:unless_exist] && File.exist?(key) ensure_cache_path(File.dirname(key)) File.atomic_write(key, cache_path) { |f| f.write(payload) } true end def delete_entry(key, **options) if File.exist?(key) begin File.delete(key) delete_empty_directories(File.dirname(key)) true rescue # Just in case the error was caused by another process deleting the file first. raise if File.exist?(key) false end end end # Lock a file for a block so only one process can modify it at a time. def lock_file(file_name, &block) if File.exist?(file_name) File.open(file_name, "r+") do |f| f.flock File::LOCK_EX yield ensure f.flock File::LOCK_UN end else yield end end # Translate a key into a file path. def normalize_key(key, options) key = super fname = URI.encode_www_form_component(key) if fname.size > FILEPATH_MAX_SIZE fname = ActiveSupport::Digest.hexdigest(key) end hash = Zlib.adler32(fname) hash, dir_1 = hash.divmod(0x1000) dir_2 = hash.modulo(0x1000) # Make sure file name doesn't exceed file system limits. if fname.length < FILENAME_MAX_SIZE fname_paths = fname else fname_paths = [] begin fname_paths << fname[0, FILENAME_MAX_SIZE] fname = fname[FILENAME_MAX_SIZE..-1] end until fname.blank? end File.join(cache_path, DIR_FORMATTER % dir_1, DIR_FORMATTER % dir_2, fname_paths) end # Translate a file path into a key. def file_path_key(path) fname = path[cache_path.to_s.size..-1].split(File::SEPARATOR, 4).last URI.decode_www_form_component(fname, Encoding::UTF_8) end # Delete empty directories in the cache. def delete_empty_directories(dir) return if File.realpath(dir) == File.realpath(cache_path) if Dir.children(dir).empty? Dir.delete(dir) rescue nil delete_empty_directories(File.dirname(dir)) end end # Make sure a file path's directories exist. def ensure_cache_path(path) FileUtils.makedirs(path) unless File.exist?(path) end def search_dir(dir, &callback) return if !File.exist?(dir) Dir.each_child(dir) do |d| name = File.join(dir, d) if File.directory?(name) search_dir(name, &callback) else callback.call name end end end # Modifies the amount of an integer value that is stored in the cache. # If the key is not found it is created and set to +amount+. def modify_value(name, amount, options) file_name = normalize_key(name, options) lock_file(file_name) do options = merged_options(options) if num = read(name, options) num = num.to_i + amount write(name, num, options) num else write(name, Integer(amount), options) amount end end end end end end
32.522523
169
0.582548
61e66dbfc4724ec6a5ec2d013cca3a3e28e90763
2,521
require "test_helper" class Edition::ActiveEditorsTest < ActiveSupport::TestCase test "can record editing intent" do user = create(:writer) edition = create(:edition) edition.open_for_editing_as(user) Timecop.travel(1.minute.from_now) assert_equal [user], edition.recent_edition_openings.map(&:editor) end test "recording editing intent for a user who's already editing just updates the timestamp" do user = create(:writer) edition = create(:edition) edition.open_for_editing_as(user) Timecop.travel(1.minute.from_now) assert_difference "edition.recent_edition_openings.count", 0 do edition.open_for_editing_as(user) end assert_equal user, edition.recent_edition_openings.first.editor assert_equal Time.zone.now.to_s(:rfc822), edition.recent_edition_openings.first.created_at.in_time_zone.to_s(:rfc822) end test "can check exclude a given editor from the list of recent edition openings" do user1 = create(:writer) edition = create(:edition) edition.open_for_editing_as(user1) Timecop.travel(1.minute.from_now) user2 = create(:writer) edition.open_for_editing_as(user2) assert_equal [user1], edition.recent_edition_openings.except_editor(user2).map(&:editor) end test "editors considered active for up to 2 hours" do user = create(:writer) edition = create(:edition) edition.open_for_editing_as(user) Timecop.travel((1.hour + 59.minutes).from_now) assert_equal [user], edition.active_edition_openings.map(&:editor) Timecop.travel((1.minute + 1.second).from_now) assert_equal [], edition.active_edition_openings end test "#save_as removes all RecentEditionOpenings for the specified editor" do user = create(:writer) edition = create(:edition) edition.open_for_editing_as(user) assert_difference "edition.recent_edition_openings.count", -1 do edition.save_as(user) end end test "RecentEditionOpening#expunge! deletes entries more than 2 hours old" do edition = create(:edition) create(:recent_edition_opening, editor: create(:author), edition: edition, created_at: 2.hours.ago + 1.second) create(:recent_edition_opening, editor: create(:author), edition: edition, created_at: 2.hours.ago) create(:recent_edition_opening, editor: create(:author), edition: edition, created_at: 2.hours.ago - 1.second) assert_equal 3, RecentEditionOpening.count RecentEditionOpening.expunge! assert_equal 2, RecentEditionOpening.count end end
40.015873
121
0.748512
f8ac27543e66e510ac62adf0211d7827d1ad5deb
1,058
class Gitea::Repository::Entries::GetService < Gitea::ClientService attr_reader :user, :repo_name, :filepath, :args # ref: The name of the commit/branch/tag. Default the repository’s default branch (usually master) # filepath: path of the dir, file, symlink or submodule in the repo # repo_name: the name of repository # ref: The name of the commit/branch/tag. Default the repository’s default branch (usually master) def initialize(user, repo_name, filepath, **args) @user = user @repo_name = repo_name @filepath = filepath @args = {ref: 'master'}.merge(args.compact) end def call response = get(url, params) render_result(response) end private def params @args.merge(token: user.gitea_token) end def url "/repos/#{user.login}/#{repo_name}/contents/#{filepath}".freeze end def render_result(response) body = JSON.parse(response.body) case response.status when 200 body when 404 raise '你访问的文件不存在' else raise body['message'] end end end
25.804878
100
0.677694
6ac31a151f02679309d2a16fffb17578458a653f
6,428
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' require 'metasploit/framework/login_scanner/glassfish' require 'metasploit/framework/credential_collection' class Metasploit3 < Msf::Auxiliary include Msf::Exploit::Remote::HttpClient include Msf::Auxiliary::AuthBrute include Msf::Auxiliary::Report include Msf::Auxiliary::Scanner def initialize super( 'Name' => 'GlassFish Brute Force Utility', 'Description' => %q{ This module attempts to login to GlassFish instance using username and password combinations indicated by the USER_FILE, PASS_FILE, and USERPASS_FILE options. It will also try to do an authentication bypass against older versions of GlassFish. Note: by default, GlassFish 4.0 requires HTTPS, which means you must set the SSL option to true, and SSLVersion to TLS1. It also needs Secure Admin to access the DAS remotely. }, 'Author' => [ 'Joshua Abraham <jabra[at]spl0it.org>', # @Jabra 'sinn3r' ], 'References' => [ ['CVE', '2011-0807'], ['OSVDB', '71948'] ], 'License' => MSF_LICENSE ) register_options( [ # There is no TARGETURI because when Glassfish is installed, the path is / Opt::RPORT(4848), OptString.new('USERNAME',[true, 'A specific username to authenticate as','admin']), OptBool.new('SSL', [false, 'Negotiate SSL for outgoing connections', false]), OptEnum.new('SSLVersion', [false, 'Specify the version of SSL that should be used', 'TLS1', ['SSL2', 'SSL3', 'TLS1']]) ], self.class) end # # Module tracks the session id, and then it will have to pass the last known session id to # the LoginScanner class so the authentication can proceed properly # # # For a while, older versions of Glassfish didn't need to set a password for admin, # but looks like no longer the case anymore, which means this method is getting useless # (last tested: Aug 2014) # def is_password_required?(version) success = false if version =~ /^[29]\.x$/ res = send_request_cgi({'uri'=>'/applications/upload.jsf'}) p = /<title>Deploy Enterprise Applications\/Modules/ if (res && res.code.to_i == 200 && res.body.match(p) != nil) success = true end elsif version =~ /^3\./ res = send_request_cgi({'uri'=>'/common/applications/uploadFrame.jsf'}) p = /<title>Deploy Applications or Modules/ if (res && res.code.to_i == 200 && res.body.match(p) != nil) success = true end end success end def init_loginscanner(ip) @cred_collection = Metasploit::Framework::CredentialCollection.new( blank_passwords: datastore['BLANK_PASSWORDS'], pass_file: datastore['PASS_FILE'], password: datastore['PASSWORD'], user_file: datastore['USER_FILE'], userpass_file: datastore['USERPASS_FILE'], username: datastore['USERNAME'], user_as_pass: datastore['USER_AS_PASS'] ) @scanner = Metasploit::Framework::LoginScanner::Glassfish.new( configure_http_login_scanner( cred_details: @cred_collection, stop_on_success: datastore['STOP_ON_SUCCESS'], bruteforce_speed: datastore['BRUTEFORCE_SPEED'], connection_timeout: 5 ) ) end def do_report(ip, port, result) service_data = { address: ip, port: port, service_name: 'http', protocol: 'tcp', workspace_id: myworkspace_id } credential_data = { module_fullname: self.fullname, origin_type: :service, private_data: result.credential.private, private_type: :password, username: result.credential.public, }.merge(service_data) credential_core = create_credential(credential_data) login_data = { core: credential_core, last_attempted_at: DateTime.now, status: result.status }.merge(service_data) create_credential_login(login_data) end def bruteforce(ip) @scanner.scan! do |result| case result.status when Metasploit::Model::Login::Status::SUCCESSFUL print_brute :level => :good, :ip => ip, :msg => "Success: '#{result.credential}'" do_report(ip, rport, result) when Metasploit::Model::Login::Status::DENIED_ACCESS print_brute :level => :status, :ip => ip, :msg => "Correct credentials, but unable to login: '#{result.credential}'" do_report(ip, rport, result) when Metasploit::Model::Login::Status::UNABLE_TO_CONNECT if datastore['VERBOSE'] print_brute :level => :verror, :ip => ip, :msg => "Could not connect" end invalidate_login( address: ip, port: rport, protocol: 'tcp', public: result.credential.public, private: result.credential.private, realm_key: result.credential.realm_key, realm_value: result.credential.realm, status: result.status ) when Metasploit::Model::Login::Status::INCORRECT if datastore['VERBOSE'] print_brute :level => :verror, :ip => ip, :msg => "Failed: '#{result.credential}'" end invalidate_login( address: ip, port: rport, protocol: 'tcp', public: result.credential.public, private: result.credential.private, realm_key: result.credential.realm_key, realm_value: result.credential.realm, status: result.status ) end end end # # main # def run_host(ip) init_loginscanner(ip) msg = @scanner.check_setup if msg print_brute :level => :error, :ip => rhost, :msg => msg return end print_brute :level=>:status, :ip=>rhost, :msg=>('Checking if Glassfish requires a password...') if @scanner.version =~ /^[239]\.x$/ && is_password_required?(@scanner.version) print_brute :level => :good, :ip => ip, :msg => "Note: This Glassfish does not require a password" else print_brute :level=>:status, :ip=>rhost, :msg=>("Glassfish is protected with a password") end bruteforce(ip) unless @scanner.version.blank? end end
32.964103
126
0.627878
39536c1a03e029dee339fb3ad658c65ff9457c37
594
require 'spec/helper' spec_require 'erubis' require 'examples/templates/template_erubis' describe 'Template Erubis' do behaves_like 'http' ramaze it '/' do get('/').body.strip.should == "<a href=\"/\">Home</a> | <a href=\"/internal\">internal</a> | <a href=\"/external\">external</a>" end %w[/internal /external].each do |url| it url do html = get(url).body html.should.not == nil html.should =~ %r{<title>Template::Erubis (internal|external)</title>} html.should =~ %r{<h1>The (internal|external) Template for Erubis</h1>} end end end
24.75
104
0.627946
ed0ed41521361d52891ba39437ba49753ba6472d
942
class Lego < Formula desc "Let's Encrypt client" homepage "https://go-acme.github.io/lego/" url "https://github.com/go-acme/lego.git", :tag => "v3.3.0", :revision => "63758264cb8537f498820cc36ad3bcaf201a5a5f" bottle do cellar :any_skip_relocation sha256 "30dea0a6027acd8ca7e69f5075729ad3a65f2ef3820191139e30d3f0d43f07e6" => :catalina sha256 "f178e501b24c5bb77636dc2d6d9ffb81466cde43a61517b219b5aeba4db33077" => :mojave sha256 "a896c91af26c66658cb5956eb0e561cb7ab5dfbe1b7b6321f40924a4ebc4263a" => :high_sierra sha256 "0e5acafc38b41dccfe188d1188896940b12afeff93a5711e6f1368183226bf44" => :x86_64_linux end depends_on "go" => :build def install system "go", "build", "-ldflags", "-s -w -X main.version=#{version}", "-trimpath", "-o", bin/"lego", "cmd/lego/main.go" prefix.install_metafiles end test do assert_match version.to_s, shell_output("#{bin}/lego -v") end end
33.642857
94
0.726115
e27f2a65f1669f5243dff08aee6215954fefc8cf
5,156
#!/usr/bin/ruby -w $LOAD_PATH.unshift "lib", "ext" require 'ode' require '../utils' include UtilityFunctions # Minimal test case for a segfault in Ruby-20021117. header "Experiment: Proc.to_s segfault minimal testcase" # Test unit struct -- makes passing test data around a bit more readble. FlagUnit = Struct::new( "FlagUnit", :op, :input, :result, :predicate ) # Test data for flag/option accessors (Mapped into FlagUnit objects) FlagTests = { # Flag/accessor (:op) # :input, :result, :predicate :bounce => [ [ 0.0, 0.0, true ], [ 1.0, 1.0, true ], [ 1.1, RangeError, true ], [ nil, nil, false ], [ 0.05, 0.05, true ], [ false, nil, false ], [ -2.0, RangeError, false ], [ 2e-4, 2e-4, true ], [ 14467.232373, RangeError, true ], [ nil, nil, false ], [ "foo", TypeError, false ], [ ["foo"], TypeError, false ], [ :foo, TypeError, false ], [ $stderr, TypeError, false ], ], :bounceVelocity => [ [ 0.1, 0.1, nil ], [ 1, 1.0, nil ], [ 115, 115.0, nil ], [ 0, 0, nil ], [ -5, RangeError, nil ], [ nil, TypeError, nil ], [ "foo", TypeError, nil ], [ ["foo"], TypeError, nil ], [ :foo, TypeError, nil ], [ $stderr, TypeError, nil ], ], :softERP => [ [ 0.1, 0.1, true ], [ 0.8, 0.8, true ], [ 0, 0.0, true ], [ 1, 1.0, true ], [ 11.141674, RangeError, true ], [ -2.0, RangeError, true ], [ false, nil, false ], [ 14467.232373, RangeError, false ], [ 4e-4, 4e-4, true ], [ nil, nil, false ], [ "foo", TypeError, false ], [ ["foo"], TypeError, false ], [ :foo, TypeError, false ], [ $stderr, TypeError, false ], ], :softCFM => [ [ 0.1, 0.1, true ], [ 0.8, 0.8, true ], [ 0, 0.0, true ], [ 1, 1.0, true ], [ 11.141674, RangeError, true ], [ -2.0, RangeError, true ], [ false, nil, false ], [ 14467.232373, RangeError, false ], [ 4e-4, 4e-4, true ], [ nil, nil, false ], [ "foo", TypeError, false ], [ ["foo"], TypeError, false ], [ :foo, TypeError, false ], [ $stderr, TypeError, false ], ], :motion1 => [ [ 0.1, 0.1, true ], [ 0.8, 0.8, true ], [ 0, 0.0, true ], [ 1, 1.0, true ], [ 11.141674, 11.141674, true ], [ -2.0, -2.0, true ], [ false, nil, false ], [ 14467.232373, 14467.232373, true ], [ 1444e-4, 1444e-4, true ], [ nil, nil, false ], [ "foo", TypeError, false ], [ ["foo"], TypeError, false ], [ :foo, TypeError, false ], [ $stderr, TypeError, false ], ], :motion2 => [ [ 0.1, 0.1, true ], [ 0.8, 0.8, true ], [ 0, 0.0, true ], [ 1, 1.0, true ], [ 11.141674, 11.141674, true ], [ -2.0, -2.0, true ], [ false, nil, false ], [ 14467.232373, 14467.232373, true ], [ 1444e-4, 1444e-4, true ], [ nil, nil, false ], [ "foo", TypeError, false ], [ ["foo"], TypeError, false ], [ :foo, TypeError, false ], [ $stderr, TypeError, false ], ], :slip1 => [ [ 0.1, 0.1, true ], [ 0.8, 0.8, true ], [ 0, 0.0, true ], [ 1, 1.0, true ], [ 11.141674, RangeError, true ], [ -2.0, RangeError, true ], [ false, nil, false ], [ 14467.232373, RangeError, false ], [ 4e-4, 4e-4, true ], [ nil, nil, false ], [ "foo", TypeError, false ], [ ["foo"], TypeError, false ], [ :foo, TypeError, false ], [ $stderr, TypeError, false ], ], :slip2 => [ [ 0.1, 0.1, true ], [ 0.8, 0.8, true ], [ 0, 0.0, true ], [ 1, 1.0, true ], [ 11.141674, RangeError, true ], [ -2.0, RangeError, true ], [ false, nil, false ], [ 14467.232373, RangeError, false ], [ 4e-4, 4e-4, true ], [ nil, nil, false ], [ "foo", TypeError, false ], [ ["foo"], TypeError, false ], [ :foo, TypeError, false ], [ $stderr, TypeError, false ], ], :mu2 => [ [ 0.0, 0.0, true ], [ ODE::Infinity, ODE::Infinity, true ], [ 15, 15.0, true ], [ nil, nil, false ], [ 11.141674, 11.141674, true ], [ false, nil, false ], [ -2.0, RangeError, false ], [ 14467.232373, 14467.232373, true ], # Make sure illegal values don't unset the mode [ -11.01, RangeError, true ], [ nil, nil, false ], [ "foo", TypeError, false ], [ ["foo"], TypeError, false ], [ :foo, TypeError, false ], [ $stderr, TypeError, false ], ], } FlagTests.keys.each {|k| FlagTests[k].each_with_index {|unit,i| message "#{k.to_s} ##{i}:: " unitStruct = FlagUnit::new( k, *unit ) message unitStruct.inspect + "\n" } }
27.572193
72
0.44841
21d6a753747dfc3a21182805cffe8a5e16f5b2c7
1,763
# frozen_string_literal: true require "montrose/errors" require "montrose/options" module Montrose # Abstract class for special recurrence rule required # in all instances of Recurrence. Frequency describes # the base recurrence interval. # class Frequency include Montrose::Rule FREQUENCY_TERMS = { "second" => "Secondly", "minute" => "Minutely", "hour" => "Hourly", "day" => "Daily", "week" => "Weekly", "month" => "Monthly", "year" => "Yearly" }.freeze FREQUENCY_KEYS = FREQUENCY_TERMS.keys.freeze attr_reader :time, :starts # Factory method for instantiating the appropriate Frequency # subclass. # def self.from_options(opts) frequency = opts.fetch(:every) { fail ConfigurationError, "Please specify the :every option" } class_name = FREQUENCY_TERMS.fetch(frequency.to_s) do fail "Don't know how to enumerate every: #{frequency}" end Montrose::Frequency.const_get(class_name).new(opts) end # @private def self.assert(frequency) FREQUENCY_TERMS.key?(frequency.to_s) or fail ConfigurationError, "Don't know how to enumerate every: #{frequency}" frequency.to_sym end def initialize(opts = {}) opts = Montrose::Options.merge(opts) @time = nil @starts = opts.fetch(:start_time) @interval = opts.fetch(:interval) end def matches_interval?(time_diff) (time_diff % @interval).zero? end end end require "montrose/frequency/daily" require "montrose/frequency/hourly" require "montrose/frequency/minutely" require "montrose/frequency/monthly" require "montrose/frequency/secondly" require "montrose/frequency/weekly" require "montrose/frequency/yearly"
25.926471
100
0.67612
039203c8ed15bf02f54bd773827418bd971adc79
1,800
## # $Id$ ## ## # This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # web site for more information on licensing and terms of use. # http://metasploit.com/ ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = AverageRanking include Msf::Exploit::Remote::Ftp def initialize(info = {}) super(update_info(info, 'Name' => 'Ipswitch WS_FTP Server 5.05 XMD5 Overflow', 'Description' => %q{ This module exploits a buffer overflow in the XMD5 verb in IPSWITCH WS_FTP Server 5.05. }, 'Author' => 'MC', 'License' => MSF_LICENSE, 'Version' => '$Revision$', 'References' => [ [ 'CVE', '2006-4847' ], [ 'OSVDB', '28939' ], [ 'BID', '20076' ], ], 'Privileged' => false, 'Payload' => { 'Space' => 300, 'BadChars' => "\x00\x7e\x2b\x26\x3d\x25\x3a\x22\x0a\x0d\x20\x2f\x5c\x2e", 'StackAdjustment' => -3500, }, 'Platform' => 'win', 'Targets' => [ [ 'Windows 2000 Pro SP4 English', { 'Ret' => 0x7c2ec663 } ], [ 'Windows XP Pro SP0 English', { 'Ret' => 0x77dc0df0 } ], [ 'Windows XP Pro SP1 English', { 'Ret' => 0x77dc5527 } ], ], 'DisclosureDate' => 'Sep 14 2006', 'DefaultTarget' => 0)) end def check connect disconnect if (banner =~ /WS_FTP Server 5.0.5/) return Exploit::CheckCode::Vulnerable end return Exploit::CheckCode::Safe end def exploit connect_login print_status("Trying target #{target.name}...") sploit = rand_text_alphanumeric(676, payload_badchars) sploit << [target.ret].pack('V') + payload.encoded send_cmd( ['XMD5', sploit] , false) handler disconnect end end
23.076923
78
0.596111
87c2d720880c29538b2ea742c5aa38cede1241d8
629
require 'slack_bot_server/version' require 'slack_bot_server/server' require 'logger' # A framework for running and controlling multiple bots. This # is designed to make it easier for developers to provide Slack # integration for their applications, instead of having individual # users run their own bot instances. module SlackBotServer # A Logger instance, defaulting to +INFO+ level def self.logger @logger ||= Logger.new(STDOUT) end # Assign the logger to be used by SlackBotServer # @param logger [Logger] def self.logger=(logger) @logger = logger end end SlackBotServer.logger.level = Logger::INFO
27.347826
66
0.759936
38b00b392d32a7f9348d0ded8d33ad7803952036
1,295
lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'acts_as_learnable/version' Gem::Specification.new do |spec| spec.name = 'acts_as_learnable' spec.version = ActsAsLearnable::VERSION spec.authors = ['Dan Kim'] spec.email = ['[email protected]'] spec.summary = 'A simple way to create flashcards in your app.' spec.description = 'ActsAsLearnable is a Ruby gem for ActiveRecord models. It provides a simple way to create flashcards in your app. It automatically schedules flashcards for review depending on recall quality (1 to 5). You can easily create a Spaced Repetition System (SRS) using this gem.' spec.homepage = 'https://github.com/itsdn/acts_as_learnable' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test)/}) spec.require_paths = ['lib'] spec.add_dependency 'activerecord', '>= 4.2' spec.add_dependency 'activesupport', '>= 4.2' spec.add_development_dependency 'bundler' spec.add_development_dependency 'rake' spec.add_development_dependency 'sqlite3' spec.add_development_dependency 'byebug' end
44.655172
296
0.703475
6ac52a9faf9ba18e13b7216c5c0155913e1ad45f
542
# frozen_string_literal: true module Station class Mapping class RequiredValue < StandardError def initialize(name) super("'#{name}' is a required value") end end class RequiredType < StandardError def initialize(name, value, type) super("'#{name}' is of type '#{value.class}', but needs to be of type '#{type}'") end end class UnknownProperty < StandardError def initialize(name) super("'#{name}' is an unknown property or collection") end end end end
24.636364
89
0.630996
e2230a2d644b1bb0ace3807be0999c14fa798eed
869
# frozen_string_literal: true class WebHookLog < ApplicationRecord include SafeUrl include Presentable include DeleteWithLimit include CreatedAtFilterable self.primary_key = :id belongs_to :web_hook serialize :request_headers, Hash # rubocop:disable Cop/ActiveRecordSerialize serialize :request_data, Hash # rubocop:disable Cop/ActiveRecordSerialize serialize :response_headers, Hash # rubocop:disable Cop/ActiveRecordSerialize validates :web_hook, presence: true before_save :obfuscate_basic_auth def self.recent where('created_at >= ?', 2.days.ago.beginning_of_day) .order(created_at: :desc) end def success? response_status =~ /^2/ end def internal_error? response_status == WebHookService::InternalErrorResponse::ERROR_MESSAGE end private def obfuscate_basic_auth self.url = safe_url end end
21.725
79
0.765247
794f2d8dd49928c14f8e38374082f1baa537feac
1,589
# Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'google/apis/runtimeconfig_v1beta1/service.rb' require 'google/apis/runtimeconfig_v1beta1/classes.rb' require 'google/apis/runtimeconfig_v1beta1/representations.rb' module Google module Apis # Cloud Runtime Configuration API # # The Runtime Configurator allows you to dynamically configure and expose # variables through Google Cloud Platform. In addition, you can also set # Watchers and Waiters that will watch for changes to your data and return based # on certain conditions. # # @see https://cloud.google.com/deployment-manager/runtime-configurator/ module RuntimeconfigV1beta1 VERSION = 'V1beta1' REVISION = '20200803' # View and manage your data across Google Cloud Platform services AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform' # Manage your Google Cloud Platform services' runtime configuration AUTH_CLOUDRUNTIMECONFIG = 'https://www.googleapis.com/auth/cloudruntimeconfig' end end end
38.756098
84
0.753933
e943683f52d90f9af7ce4396e25955c4ca408c67
102
json.extract! upload, :id, :name, :created_at, :updated_at json.url upload_url(upload, format: :json)
34
58
0.745098
bb8d8a11241701cccd680bc972ea6ae9512f69a1
2,212
require 'spec_helper' describe package('httpd'), :if => os[:family] == 'redhat' do it { should be_installed } end describe package('apache2'), :if => os[:family] == 'ubuntu' do it { should be_installed } end describe service('httpd'), :if => os[:family] == 'redhat' do it { should be_enabled } it { should be_running } end describe service('apache2'), :if => os[:family] == 'ubuntu' do it { should be_enabled } it { should be_running } end describe service('org.apache.httpd'), :if => os[:family] == 'darwin' do it { should be_enabled } it { should be_running } end describe port(80) do it { should be_listening } end describe file('/etc/passwd') do it { should be_file } end describe file('/var/log/apache2') do it { should be_directory } end describe command('ls -al /') do its(:stdout) { should match /bin/ } end describe package('mysql-server') do it { should be_installed } end describe service('mysql') do it { should be_enabled } it { should be_running } end describe port(3306) do it { should be_listening.on('127.0.0.1').with('tcp') } end db_user = "user" db_password = "password" db_name = "sample" describe command("mysqlshow -u#{db_user} -p#{db_password}") do # its (:stdout) { should eq 'user' } its (:stdout) { should match /Databases/ } end # describe command("mysqlshow -u#{db_user} -p#{db_password} #{db_name}") do # its (:stdout) { should match /Database:\ #{db_name}/ } # end describe command("mysqladmin -u#{db_user} -p#{db_password} variables |grep character_set_server") do its (:stdout) { should match /utf8/ } end # check php.ini for cli # todo: fail 2 parameters php_values = [ {'default_mimetype' => 'text/html'}, # {'max_execution_time' => 30}, {'memory_limit' => '-1'}, {'post_max_size' => '8M'}, {'upload_max_filesize' => '2M'}, # {'max_input_time' => 60}, {'date.timezone' => 'Asia/Tokyo'} ] describe 'PHP config parameters' do php_values.each do |php_value| context php_config(php_value.keys.first) do its(:value) { should eq php_value[php_value.keys.first] } end end end describe command('ruby -v') do let(:disable_sudo) { true } its(:stdout) { should match /ruby 2\.3\.0.+/ } end
23.041667
100
0.659584
abf143e73366beebe5d3f140e61771b2ce1e3582
2,246
module Cenit module ApiBuilder module BridgingServiceApplicationConn extend ActiveSupport::Concern included do belongs_to :connection, class_name: Setup::Connection.name, inverse_of: nil field :target_api_base_url, type: String after_save :setup_connection before_destroy :destroy_authorization, :destroy_connection end def setup_connection_parameters(security_scheme) # ... end def target_api_base_url get_connection.url end def target_api_base_url=(value) get_connection&.update(url: value.blank? ? spec.servers.first.url : value) end def get_connection return @conn unless @conn.nil? @conn = self.connection ||= begin criteria = { namespace: namespace, name: 'default_connection' } Setup::Connection.where(criteria).first || create_default_connection(criteria) end end def create_default_connection(data) return nil if spec.nil? auth = get_authorization data[:url] = spec.servers.first.try(:url) || 'http://api.demo.io' data[:headers] = [] data[:parameters] = [] data[:template_parameters] = [] unless auth.nil? data[:authorization] = { id: auth.id, _reference: true } type = auth._type.split('::').last.underscore.to_sym if (type == :oauth2_authorization) data[:authorization_handler] = true data[:headers] << {key: 'Authorization', value: 'Bearer {{access_token}}'} end end spec.components.security_schemes.each do |_, scheme| next unless scheme.type == 'apiKey' tp_name = scheme.name.parameterize.underscore item = { key: scheme.name, value: "{{#{tp_name}}}" } data[:headers] << item if scheme.in == 'header' data[:parameters] << item if scheme.in == 'query' end Setup::Connection.create_from_json!(data) end def setup_connection conn_id = get_connection.id self.set(connection_id: conn_id) if connection_id != conn_id end def destroy_connection connection&.destroy end end end end
28.43038
88
0.616652