Input: Public : Feed the decoder raw data from the wire [CODESPLIT] def << data # put the data into the buffer, as # we might be replaying if data @buffer << data end # Don't do work if we don't have to if @buffer . length < 2 return end # decode the first 2 bytes, with # opcode, lengthgth, masking bit, and frag bit h1 , h2 = @buffer . unpack ( "CC" ) # check the fragmentation bit to see # if this is a message fragment fin = ( ( h1 & 0x80 ) == 0x80 ) # used to keep track of our position in the buffer offset = 2 # see above for possible opcodes opcode = ( h1 & 0x0F ) # the leading length idicator length = ( h2 & 0x7F ) # masking bit, is the data masked with # a specified masking key? masked = ( ( h2 & 0x80 ) == 0x80 ) # Find errors and fail fast if h1 & 0b01110000 != 0 return emit :error , 1002 , "RSV bits must be 0" end if opcode > 7 if ! fin return emit :error , 1002 , "Control frame cannot be fragmented" elsif length > 125 return emit :error , 1002 , "Control frame is too large #{length}" elsif opcode > 0xA return emit :error , 1002 , "Unexpected reserved opcode #{opcode}" elsif opcode == CLOSE && length == 1 return emit :error , 1002 , "Close control frame with payload of length 1" end else if opcode != CONTINUATION && opcode != TEXT_FRAME && opcode != BINARY_FRAME return emit :error , 1002 , "Unexpected reserved opcode #{opcode}" end end # Get the actual size of the payload if length > 125 if length == 126 length = @buffer . unpack ( "@#{offset}n" ) . first offset += 2 else length = @buffer . unpack ( "@#{offset}L!>" ) . first offset += 8 end end # unpack the masking key if masked key = @buffer . unpack ( "@#{offset}N" ) . first offset += 4 end # replay on next frame if @buffer . size < ( length + offset ) return false end # Read the important bits payload = @buffer . unpack ( "@#{offset}C#{length}" ) # Unmask the data if it"s masked if masked payload . bytesize . times do | i | payload [ i ] = ( ( payload [ i ] ^ ( key >> ( ( 3 - ( i % 4 ) ) * 8 ) ) ) & 0xFF ) end end payload = payload . pack ( "C*" ) case opcode when CONTINUATION # We shouldn't get a contination without # knowing whether or not it's binary or text unless @fragmented return emit :error , 1002 , "Unexepected continuation" end if @fragmented == :text @chunks << payload . force_encoding ( "UTF-8" ) else @chunks << payload end if fin if @fragmented == :text && ! valid_utf8? ( @chunks ) return emit :error , 1007 , "Invalid UTF" end emit :frame , @chunks , @fragmented == :binary @chunks = nil @fragmented = false end when TEXT_FRAME # We shouldn't get a text frame when we # are expecting a continuation if @fragmented return emit :error , 1002 , "Unexepected frame" end # emit or buffer if fin unless valid_utf8? ( payload ) return emit :error , 1007 , "Invalid UTF Hmm" end emit :frame , payload , false else @chunks = payload . force_encoding ( "UTF-8" ) @fragmented = :text end when BINARY_FRAME # We shouldn't get a text frame when we # are expecting a continuation if @fragmented return emit :error , 1002 , "Unexepected frame" end # emit or buffer if fin emit :frame , payload , true else @chunks = payload @fragmented = :binary end when CLOSE code , explain = payload . unpack ( "nA*" ) if explain && ! valid_utf8? ( explain ) emit :close , 1007 else emit :close , response_close_code ( code ) end when PING emit :ping , payload when PONG emit :pong , payload end # Remove data we made use of and call back # TODO: remove recursion @buffer = @buffer [ offset + length .. - 1 ] || "" if not @buffer . empty? self << nil end end


Input: read options from YAML config [CODESPLIT] def configure # config file default options configuration = { :options => { :verbose => false , :coloring => 'AUTO' } , :mount => { :source => { :name => nil } , :mountpoint => { :name => nil } , :passphrasefile => { :name => 'passphrase' } , :keyfile => { :name => 'encfs6.xml' } , :cmd => nil , :executable => nil } , :unmount => { :mountpoint => { :name => nil } , :cmd => nil , :executable => nil } , :copy => { :source => { :name => nil } , :destination => { :name => nil } , :cmd => nil , :executable => nil } } # set default config if not given on command line config = @options [ :config ] unless config config = [ File . join ( @working_dir , "revenc.conf" ) , File . join ( @working_dir , ".revenc.conf" ) , File . join ( @working_dir , "config" , "revenc.conf" ) , File . expand_path ( File . join ( "~" , ".revenc.conf" ) ) ] . detect { | filename | File . exists? ( filename ) } end if config && File . exists? ( config ) # rewrite options full path for config for later use @options [ :config ] = config # load options from the config file, overwriting hard-coded defaults config_contents = YAML :: load ( File . open ( config ) ) configuration . merge! ( config_contents . symbolize_keys! ) if config_contents && config_contents . is_a? ( Hash ) else # user specified a config file?, no error if user did not specify config file raise "config file not found" if @options [ :config ] end # the command line options override options read from the config file @options = configuration [ :options ] . merge! ( @options ) @options . symbolize_keys! # mount, unmount and copy configuration hashes @options [ :mount ] = configuration [ :mount ] . recursively_symbolize_keys! if configuration [ :mount ] @options [ :unmount ] = configuration [ :unmount ] . recursively_symbolize_keys! if configuration [ :unmount ] @options [ :copy ] = configuration [ :copy ] . recursively_symbolize_keys! if configuration [ :copy ] end


Input: PATCH / PUT / subscriptions / 1 [CODESPLIT] def update @subscription . end_trial_now = ( params [ :subscription ] [ :end_trial_now ] == '1' ) if @subscription . end_trial_now params [ :subscription ] [ 'trial_end(1i)' ] = '' params [ :subscription ] [ 'trial_end(2i)' ] = '' params [ :subscription ] [ 'trial_end(3i)' ] = '' end if @subscription . update ( subscription_params ) redirect_to [ :admin , @subscription ] , notice : 'Subscription was successfully updated.' else render :edit end end


Input: Initializes a new feedtosis library . It must be initialized with a valid URL as the first argument . A following optional + options + Hash may take the arguments : * backend : a key - value store to be used for summary structures of feeds fetched . Moneta backends work well but any object acting like a Hash is valid . * retained_digest_size : an Integer specifying the number of previous MD5 sets of entries to keep used for new feed detection Retrieves the latest entries from this feed . Returns a Feedtosis :: Result object which delegates methods to the Curl :: Easy object making the request and the FeedNormalizer :: Feed object that may have been created from the HTTP response body . [CODESPLIT] def fetch curl = build_curl_easy curl . perform feed = process_curl_response ( curl ) Feedtosis :: Result . new ( curl , feed ) end


Input: Marks entries as either seen or not seen based on the unique signature of the entry which is calculated by taking the MD5 of common attributes . [CODESPLIT] def mark_new_entries ( response ) digests = summary_digests # For each entry in the responses object, mark @_seen as false if the  # digest of this entry doesn't exist in the cached object. response . entries . each do | e | seen = digests . include? ( digest_for ( e ) ) e . instance_variable_set ( :@_seen , seen ) end response end


Input: Processes the results by identifying which entries are new if the response is a 200 . Otherwise returns the Curl :: Easy object for the user to inspect . [CODESPLIT] def process_curl_response ( curl ) if curl . response_code == 200 response = parser_for_xml ( curl . body_str ) response = mark_new_entries ( response ) store_summary_to_backend ( response , curl ) response end end


Input: Sets the headers from the backend if available [CODESPLIT] def set_header_options ( curl ) summary = summary_for_feed unless summary . nil? curl . headers [ 'If-None-Match' ] = summary [ :etag ] unless summary [ :etag ] . nil? curl . headers [ 'If-Modified-Since' ] = summary [ :last_modified ] unless summary [ :last_modified ] . nil? end curl end


Input: Stores information about the retrieval including ETag Last - Modified and MD5 digests of all entries to the backend store . This enables conditional GET usage on subsequent requests and marking of entries as either new or seen . [CODESPLIT] def store_summary_to_backend ( feed , curl ) headers = HttpHeaders . new ( curl . header_str ) # Store info about HTTP retrieval summary = { } summary . merge! ( :etag => headers . etag ) unless headers . etag . nil? summary . merge! ( :last_modified => headers . last_modified ) unless headers . last_modified . nil? # Store digest for each feed entry so we can detect new feeds on the next  # retrieval new_digest_set = feed . entries . map do | e | digest_for ( e ) end new_digest_set = summary_for_feed [ :digests ] . unshift ( new_digest_set ) new_digest_set = new_digest_set [ 0 .. @options [ :retained_digest_size ] ] summary . merge! ( :digests => new_digest_set ) set_summary ( summary ) end


Input: Computes a unique signature for the FeedNormalizer :: Entry object given . This signature will be the MD5 of enough fields to have a reasonable probability of determining if the entry is unique or not . [CODESPLIT] def digest_for ( entry ) MD5 . hexdigest ( [ entry . title , entry . content , entry . date_published ] . join ) end


Input: Print a colored banner to $stderr in green . [CODESPLIT] def banner ( str , color : GREEN ) now = Time . new . strftime ( "%H:%M:%S" ) s = "#{str} " . ljust ( 72 , " " ) $stderr . puts "#{color}[#{now}] #{s}#{RESET}" end


Input: Add logger support easy for log monitor when running your app Output errors and valid records count TODO add color support [CODESPLIT] def logger ( options = { records : [ ] , uri : '' , error : '' , type : '' , opts : { } } ) records = options [ :records ] . nil? ? [ ] : options [ :records ] error = options [ :error ] uri = options [ :uri ] type = options [ :type ] opts = options [ :opts ] if defined? Rails if error . present? Rails . logger . info ">>> Error: #{error}" else Rails . logger . info ">>> Querying Sqoot API V2: #{type}" Rails . logger . info ">>> #{uri}" Rails . logger . info ">>> #{opts}" Rails . logger . info ">>> Hit #{records.count} records" end else if error . present? puts ">>> Error: #{error}" puts '' else puts ">>> Querying Sqoot API V2: #{type}" puts '' puts ">>> #{uri}" puts '' puts ">>> #{opts}" puts '' puts ">>> Hit #{records.count} records" puts '' end end end


Input: The action [CODESPLIT] def assert_it ( message ) $stderr . puts ( "Assertion failed: " + message . to_s ) $stderr . puts ( "at: " ) caller . each { | trace | $stderr . puts trace } end


Input: ATTACHED PROCESSES [CODESPLIT] def attach_tick_process ( process , ticks_to_wait = 0 ) self . attached_processes << AttachedProcess . build ( process : process , tickable : true , ticks_waiting : ticks_to_wait ) save! end


Input: TOKENS [CODESPLIT] def has_token? ( token ) token && token . _id && self . tokens . where ( _id : token . _id ) . first end


Input: CONSTRAINTS [CODESPLIT] def add_constraint! ( constraint ) raise PbwArgumentError ( 'Invalid constraint' ) unless constraint return false if has_constraint? ( constraint ) return false unless constraint . before_add ( self ) self . constraints << constraint save! constraint . after_add ( self ) self end


Input: CAPABILITIES [CODESPLIT] def add_capability! ( capability ) raise PbwArgumentError ( 'Invalid capability' ) unless capability return false if has_capability? ( capability ) return false unless capability . before_add ( self ) self . capabilities << capability save! capability . after_add ( self ) self end


Input: TRIGGERS [CODESPLIT] def add_trigger! ( trigger ) raise PbwArgumentError ( 'Invalid trigger' ) unless trigger return false if has_trigger? ( trigger ) self . triggers << trigger save! trigger . after_add ( self ) self end


Input: Build a HTTP object having been given a timeout and a URI object Returns Net :: HTTP object . [CODESPLIT] def build_http ( uri , timeout ) http = Net :: HTTP . new ( uri . host , uri . port ) if ( timeout > 0 ) http . open_timeout = timeout http . read_timeout = timeout end return http end


Input: All responses from openstack where any errors need to be caught are passed through this function . Unless a successful response is passed it will throw a Ropenstack error . If successful returns a hash of response body unless response body is nil then it returns an empty hash . [CODESPLIT] def error_manager ( uri , response ) case response when Net :: HTTPSuccess then # This covers cases where the response may not validate as JSON. begin data = JSON . parse ( response . body ) rescue data = { } end ## Get the Headers out of the response object data [ 'headers' ] = response . to_hash ( ) return data when Net :: HTTPBadRequest raise Ropenstack :: MalformedRequestError , response . body when Net :: HTTPNotFound raise Ropenstack :: NotFoundError , "URI: #{uri} \n" + response . body when Net :: HTTPUnauthorized raise Ropenstack :: UnauthorisedError , response . body else raise Ropenstack :: RopenstackError , response . body end end


Input: The function which you call to perform a http request using the request object given in the parameters . By default manage errors is true so all responses are passed through the error manager which converts the into Ropenstack errors . [CODESPLIT] def do_request ( uri , request , manage_errors = true , timeout = 10 ) begin http = build_http ( uri , timeout ) if ( manage_errors ) return error_manager ( uri , http . request ( request ) ) else http . request ( request ) return { "Success" => true } end rescue Timeout :: Error raise Ropenstack :: TimeoutError , "It took longer than #{timeout} to connect to #{uri.to_s}" rescue Errno :: ECONNREFUSED raise Ropenstack :: TimeoutError , "It took longer than #{timeout} to connect to #{uri.to_s}" end end


Input: Wrapper function for a get request just provide a uri and it will return you a hash with the result data . For authenticated transactions a token can be provided . Implemented using the do_request method . [CODESPLIT] def get_request ( uri , token = nil , manage_errors = true ) request = Net :: HTTP :: Get . new ( uri . request_uri , initheader = build_headers ( token ) ) return do_request ( uri , request , manage_errors ) end


Input: Wrapper function for delete requests just provide a uri and it will return you a hash with the result data . For authenticated transactions a token can be provided . Implemented using the do_request method . [CODESPLIT] def delete_request ( uri , token = nil , manage_errors = true ) request = Net :: HTTP :: Delete . new ( uri . request_uri , initheader = build_headers ( token ) ) return do_request ( uri , request , manage_errors ) end


Input: Wrapper function for a put request just provide a uri and a hash of the data to send then it will return you a hash with the result data . For authenticated transactions a token can be provided . Implemented using the do_request method [CODESPLIT] def put_request ( uri , body , token = nil , manage_errors = true ) request = Net :: HTTP :: Put . new ( uri . request_uri , initheader = build_headers ( token ) ) request . body = body . to_json return do_request ( uri , request , manage_errors ) end


Input: Wrapper function for a put request just provide a uri and a hash of the data to send then it will return you a hash with the result data . For authenticated transactions a token can be provided . [CODESPLIT] def post_request ( uri , body , token = nil , manage_errors = true ) request = Net :: HTTP :: Post . new ( uri . request_uri , initheader = build_headers ( token ) ) request . body = body . to_json return do_request ( uri , request , manage_errors ) end


Input: Functional composition f · g [CODESPLIT] def comp ( g ) Fn { | * a , & b | call ( g . call ( a , b ) ) } end


Input: Enumerates articles [CODESPLIT] def articles Enumerator . new do | y | article_ids . each do | id | y << article ( id ) end end end


Input: Gets an article by ID [CODESPLIT] def article ( id ) url = index . knowledgeManagement . articles . article url = url ( url , ArticleID : id ) decorate ( get ( url ) . body ) { | o | autodefine ( o ) } end


Input: BELOW HERE IS OLD CODE THAT MAY OR MAYNOT WORK THAR BE DRAGONS [CODESPLIT] def upload_image_from_file ( name , disk_format , container_format , minDisk , minRam , is_public , file ) data = { "name" => name , "disk_format" => disk_format , "container_format" => container_format , "minDisk" => minDisk , "minRam" => minRam , "public" => is_public } imagesBefore = images ( ) post_request ( address ( "images" ) , data , @token , false ) imagesAfter = images ( ) foundNewImage = true image = nil imagesAfter . each do | imageA | imagesBefore . each do | imageB | if ( imageA == imageB ) foundNewImage = false end end if ( foundNewImage ) image = imageA break end end return put_octect ( address ( image [ "file" ] ) , file . read , false ) end


Input: Special rest call for sending a file stream using an octet - stream main change is just custom headers . Still implemented using do_request function . [CODESPLIT] def put_octect ( uri , data , manage_errors ) headers = build_headers ( @token ) headers [ "Content-Type" ] = 'application/octet-stream' req = Net :: HTTP :: Put . new ( uri . request_uri , initheader = headers ) req . body = data return do_request ( uri , req , manage_errors , 0 ) end


Input: The rules followed are : 1 . Any live cell with fewer than two live neighbours dies as if caused by under - population . 2 . Any live cell with two or three live neighbours lives on to the next generation . 3 . Any live cell with more than three live neighbours dies as if by overcrowding . 4 . Any dead cell with exactly three live neighbours becomes a live cell as if by reproduction . 5 . Any live cell that is over 3 generations dies [CODESPLIT] def should_cell_live? ( board , cell , x , y ) live_neighbors_count = board . neighbors_of_cell_at ( x , y ) . select { | n | n . alive? } . size case cell . state when :live ( ( 2 .. 3 ) . include? live_neighbors_count ) && ( ! cell . old? ) when :dead live_neighbors_count == 3 end end


Input: Returns a path relative to the base path given the full path . This is the inverse of full_path . [CODESPLIT] def relative_path ( path ) path = File . expand_path ( path ) root = full_path ( "" ) if path . size >= root . size && path [ 0 ... root . size ] == root path [ 0 ... root . size ] = "" path = "/" if path . size == 0 path end end


Input: Renders an index page for the specified directory . [CODESPLIT] def index ( path ) @entries = [ ] Dir . entries ( path ) . each do | entry | relative_path = relative_path ( File . join ( path , entry ) ) if entry != "." && relative_path @entries << { :name => entry , :href => relative_path } end end @path = path haml :index end


Input: : css_extend = > : root_path = > . : scope_name = > rails_xxx : recipe_path = > icons / 16x16 : file_extend = > . png : spacing = > 10 : image_to_folder = > app / assets / images : image_source_folder = > app / assets / images / rails_xxx / sprite_sources : stylesheet_to = > app / assets / stylesheets / rails_xxx / sprite / icons / 16x16 . css . scss . erb : image_to_file_path = > rails_xxx / sprite / icons / 16x16 . png [CODESPLIT] def perform file_infos = [ ] #  puts "image_source_folder: #{image_source_folder}" #  puts "image_to_file_path: #{image_to_file_path}" #  puts "stylesheet_to: #{stylesheet_to}" counter = 0 x = 0 y = 0 max_w = 0 max_h = 0 Dir . entries ( image_source_folder ) . each do | file_name | if file_name != '.' && file_name != '..' && file_name . end_with? ( file_extend ) file_path = "#{image_source_folder}/#{file_name}" if :: File . file? ( file_path ) file_name_split = file_name . split ( '.' ) file_name_split . pop file_purename = file_name_split . join ( '.' ) file_info = { :filepath => file_path , :filename => file_name , :file_purename => file_purename , :idx => counter } . merge ( _library . load ( file_path ) ) file_info [ :x ] = x file_info [ :y ] = y y += ( spacing + file_info [ :height ] ) max_w = [ max_w , file_info [ :width ] ] . max max_h = y file_infos << file_info counter += 1 end end end _composite_images ( :file_infos => file_infos , :max_w => max_w , :max_h => max_h ) _composite_css ( file_infos , :max_w => max_w , :max_h => max_h ) end


Input: Create a new table . [CODESPLIT] def accessors_from_headers! raise "Can't define accessors from headers in a table without headers" unless @has_headers self . accessors = headers . map { | val | ( val && ! val . empty? ) ? val . to_s . downcase . tr ( '^a-z0-9_' , '_' ) . squeeze ( '_' ) . gsub ( / \A \z / , '' ) . to_sym : nil } end


Input: @param [ Array<Symbol > Hash<Symbol = > Integer > nil ] accessors [CODESPLIT] def accessors = ( accessors ) @accessor_columns = { } case accessors when nil # nothing to do when Array accessors . each_with_index do | name , idx | @accessor_columns [ name . to_sym ] = idx if name end when Hash @accessor_columns = Hash [ accessors . map { | name , index | [ name . to_sym , index ] } ] else raise ArgumentError , "Expected nil, an Array or a Hash, but got #{accessors.class}" end @accessor_columns . freeze @column_accessors = @accessor_columns . invert . freeze @accessors = @column_accessors . values_at ( 0 .. ( @column_accessors . keys . max || - 1 ) ) . freeze end


Input: @return [ Tabledata :: Row ] The row at the given row number ( zero based ) . Includes headers and footer . Returns the given default value or invokes the default block if the desired row does not exist . [CODESPLIT] def fetch_row ( row , * default ) raise ArgumentError , "Must only provide at max one default value or one default block" if default . size > ( block_given? ? 0 : 1 ) row_data = row ( row ) if row_data row_data elsif block_given? yield ( self , row ) elsif default . empty? raise KeyError , "Row not found: #{row.inspect}" else default . first end end


Input: @return [ Object ] The cell value at the given row and column number ( zero based ) . Includes headers and footer . Returns the given default value or invokes the default block if the desired cell does not exist . [CODESPLIT] def fetch_cell ( row , column , * default_value , & default_block ) raise ArgumentError , "Must only provide at max one default value or one default block" if default_value . size > ( block_given? ? 0 : 1 ) row_data = row ( row ) if row_data row_data . fetch ( column , default_value , default_block ) elsif block_given? yield ( self , row , column ) elsif default_value . empty? raise IndexError , "Row not found: #{row.inspect}, #{column.inspect}" else default_value . first end end


Input: Append a row to the table . [CODESPLIT] def << ( row ) index = @data . size begin row = row . to_ary rescue NoMethodError raise ArgumentError , "Row must be provided as Array or respond to `to_ary`, but got #{row.class} in row #{index}" unless row . respond_to? ( :to_ary ) raise end raise InvalidColumnCount . new ( index , row . size , column_count ) if @data . first && row . size != @data . first . size @data << row @rows << Row . new ( self , index , row ) self end


Input: This is the method that will place the anchor tag and id of the footnote within the paragraph body itself . [CODESPLIT] def html ( id , time ) inline_footnote_label = Build . tag ( "span" , Build . tag ( "sup" , id . to_s ) , :class => "inline-footnote-number" ) Build . tag ( "a" , inline_footnote_label , :href => "#footnote#{id}#{time}" ) end


Input: This is the method that will actually spit out the div that the footnote s content is in . This will generally be called after all of the paragraph s text has been spit out so that the footnotes can be appended after . Note that it needs to be passed an id from the caller so that it can be linked to corretly with an anchor tag in the body of the main text . [CODESPLIT] def footnote_html ( id , time ) footnote_label = Build . tag ( "span" , Build . tag ( "sup" , id . to_s ) , :class => "footnote-number" ) footnote_content = sequence . elements . map { | s | s . html } . join Build . tag ( "div" , footnote_label + footnote_content , :id => "footnote#{id}#{time}" , :class => "footnote" ) end


Input: Database Instance Actions [CODESPLIT] def instance_action ( id , action , param ) case action when "RESTART" post_request ( address ( "/instances/" + id + "/action" ) , { :restart => { } } , @token ) when "RESIZE" if param . is_a? String post_request ( address ( "/instances/" + id + "/action" ) , { :resize => { :flavorRef => param } } , @token ) elsif param . is_a? Int post_request ( address ( "/instances/" + id + "/action" ) , { :resize => { :volume => { :size => param } } } , @token ) else raise Ropenstack :: RopenstackError , "Invalid Parameter Passed" end else raise Ropenstack :: RopenstackError , "Invalid Action Passed" end end


Input: Given a Class generate a map of dependencies needed to construct a new instance of that class . Dependencies are looked up ( and / or instantiated as determined within the ObjectContext ) via the provided ObjectContext . [CODESPLIT] def resolve_for_class ( klass , object_context , remapping = nil ) remapping ||= { } klass . object_definition . component_names . inject ( { } ) do | obj_map , name | obj_map [ name ] = search_for ( klass , object_context , remapping [ name . to_sym ] || remapping [ name . to_s ] || name ) obj_map end end


Input: add errors error_on can be a symbol or object instance [CODESPLIT] def add ( error_on , message = "Unknown error" ) # humanize error_on if error_on . is_a? ( Symbol ) error_on_str = error_on . to_s else error_on_str = underscore ( error_on . class . name ) end error_on_str = error_on_str . gsub ( / \/ / , '_' ) error_on_str = error_on_str . gsub ( / / , ' ' ) error_on_str = error_on_str . gsub ( / / , '' ) . strip #error_on_str = error_on_str.capitalize @errors [ error_on_str ] ||= [ ] @errors [ error_on_str ] << message . to_s end


Input: Finds the neighbors of a given { Cell } s co - ordinates . The neighbors are the eight cells that surround the given one . [CODESPLIT] def neighbors_of_cell_at ( x , y ) neighbors = coords_of_neighbors ( x , y ) . map { | x , y | self . cell_at ( x , y ) } neighbors . reject { | n | n . nil? } end


Input: This is the first stage in a Game s #tick . [CODESPLIT] def reformat_for_next_generation! # create an array of dead cells and insert it as the first and last row of cells dead_cells = ( 1 .. @cells . first . size ) . map { Cell . new } # don't forget to deep copy the dead_cells @cells . unshift Marshal . load ( Marshal . dump ( dead_cells ) ) @cells . push Marshal . load ( Marshal . dump ( dead_cells ) ) # also insert a dead cell at the left and right of each row @cells . each do | row | row . unshift Cell . new row . push Cell . new end # validate to see if we broke the board validate end


Input: This is the third and last stage in a Game s #tick . [CODESPLIT] def shed_dead_weight! # Remove the first and last rows if all cells are dead @cells . shift if @cells . first . all? { | cell | cell . dead? } @cells . pop if @cells . last . all? { | cell | cell . dead? } # Remove the first cell of every row, if they are all dead first_columns = @cells . map { | row | row . first } if first_columns . all? { | cell | cell . dead? } @cells . each { | row | row . shift } end # Remove the last cell of every row, if they are all dead last_columns = @cells . map { | row | row . last } if last_columns . all? { | cell | cell . dead? } @cells . each { | row | row . pop } end validate end


Input: Calculates the co - ordinates of neighbors of a given pair of co - ordinates . [CODESPLIT] def coords_of_neighbors ( x , y ) coords_of_neighbors = [ ] ( x - 1 ) . upto ( x + 1 ) . each do | neighbors_x | ( y - 1 ) . upto ( y + 1 ) . each do | neighbors_y | next if ( x == neighbors_x ) && ( y == neighbors_y ) coords_of_neighbors << [ neighbors_x , neighbors_y ] end end coords_of_neighbors end


Input: Retrieve a list of merchants base on the following parameters [CODESPLIT] def merchant ( id , options = { } ) options = update_by_expire_time options if merchant_not_latest? ( id ) @rsqoot_merchant = get ( "merchants/#{id}" , options , SqootMerchant ) @rsqoot_merchant = @rsqoot_merchant . merchant if @rsqoot_merchant end logger ( uri : sqoot_query_uri , records : [ @rsqoot_merchant ] , type : 'merchants' , opts : options ) @rsqoot_merchant end


Input: Encode a standard payload to a hybi10 WebSocket frame [CODESPLIT] def encode data , opcode = TEXT_FRAME frame = [ ] frame << ( opcode | 0x80 ) packr = "CC" if opcode == TEXT_FRAME data . force_encoding ( "UTF-8" ) if ! data . valid_encoding? raise "Invalid UTF!" end end # append frame length and mask bit 0x80 len = data ? data . bytesize : 0 if len <= 125 frame << ( len | 0x80 ) elsif len < 65536 frame << ( 126 | 0x80 ) frame << len packr << "n" else frame << ( 127 | 0x80 ) frame << len packr << "L!>" end # generate a masking key key = rand ( 2 ** 31 ) # mask each byte with the key frame << key packr << "N" #puts "op #{opcode} len #{len} bytes #{data}" # Apply the masking key to every byte len . times do | i | frame << ( ( data . getbyte ( i ) ^ ( key >> ( ( 3 - ( i % 4 ) ) * 8 ) ) ) & 0xFF ) end frame . pack ( "#{packr}C*" ) end


Input: This method sets up the + Permission + class with all baked in methods . [CODESPLIT] def challah_permission unless included_modules . include? ( InstanceMethods ) include InstanceMethods extend ClassMethods end class_eval do validates_presence_of :name , :key validates_uniqueness_of :name , :key validates_format_of :key , :with => / / , :message => :invalid_key has_many :permission_roles , :dependent => :destroy has_many :roles , :through => :permission_roles , :order => 'roles.name' has_many :permission_users , :dependent => :destroy has_many :users , :through => :permission_users , :order => 'users.last_name, users.first_name' default_scope order ( 'permissions.name' ) attr_accessible :name , :description , :key , :locked after_create :add_to_admin_role end end


Input: Parses out the <tt > base_path< / tt > setting from a path to display it in a less verbose way . [CODESPLIT] def display_path ( filename = nil ) filename ||= path display_path = File . expand_path ( filename ) display_path . gsub ( base_path . to_s , "" ) end


Input: makes a POST request [CODESPLIT] def post hash = { } , payload raise 'Payload cannot be blank' if payload . nil? || payload . empty? hash . symbolize_keys! call ( :post , hash [ :endpoint ] , ( hash [ :args ] || { } ) . merge ( { :method => :post } ) , payload ) end


Input: low level api for request ( needed por PUT PATCH & DELETE methods ) [CODESPLIT] def call method , endpoint , args = { } , params raise "Endpoint can't be blank" unless endpoint raise "Method is missing" unless method url = ( method == :get || method == :delete ) ? url ( endpoint , params ) : url ( endpoint ) RestClient :: Request . execute ( method : method , url : url , headers : header ( args [ :headers ] ) , payload : params || { } ) do | response , request , result | #status = response.code == 200 ? :debug : :error #print(status, request, response.body) parse ( response , endpoint ) end end


Input: Networks [CODESPLIT] def networks ( id = nil ) endpoint = "networks" unless id . nil? endpoint = endpoint + "/" + id end return get_request ( address ( endpoint ) , @token ) end


Input: Create a new network on Openstack given a name and tenant id . [CODESPLIT] def create_network ( name , tenant , admin_state_up = true ) data = { 'network' => { 'name' => name , 'tenant_id' => tenant , 'admin_state_up' => admin_state_up } } return post_request ( address ( "networks" ) , data , @token ) end


Input: Create a new port given network and device ids optional parameter subnet id allows for scoping the port to a single subnet . [CODESPLIT] def create_port ( network , subnet = nil , device = nil , device_owner = nil ) data = { 'port' => { 'network_id' => network , } } unless device_owner . nil? data [ 'port' ] [ 'device_owner' ] = device_owner end unless device . nil? data [ 'port' ] [ 'device_id' ] = device end unless subnet . nil? data [ 'port' ] [ 'fixed_ips' ] = [ { 'subnet_id' => subnet } ] end puts data return post_request ( address ( "ports" ) , data , @token ) end


Input: Weird function for adding a port to multiple subnets if nessessary . [CODESPLIT] def move_port_to_subnets ( port_id , subnet_ids ) id_list = Array . new ( ) subnet_ids . each do | id | id_list << { "subnet_id" => id } end return update_port ( port_id , id_list ) end


Input: This is a convenience method that sets the Content - Type headers and writes the JSON String to the response . [CODESPLIT] def json ( data = { } , options = { } ) response [ CONTENT_TYPE ] = APPLICATION_JSON response . status = options [ :status ] if options . has_key? ( :status ) response . write self . class . json_serializer . dump ( data ) end


Input: This is a convenience method that forms an absolute URL based on the url parameter which can be a relative or absolute URL and then sets the headers and the body appropriately to do a 302 redirect . [CODESPLIT] def redirect_to ( url , options = { } ) full_url = absolute_url ( url , options ) response [ LOCATION ] = full_url respond_with 302 full_url end


Input: + name + ( Symbol ) : name for method + types + ( Array ) : array with types for method arguments + body + ( Proc ) : block called with method [CODESPLIT] def eql0? ( other ) #:nodoc: @ancestors . find { | a | a . __overload_methods . find { | m | m . name == other . name && m . types == other . types } } end


Input: Serialize [CODESPLIT] def as_json ( opts = { } ) raise NotImplementedError , 'as_json with arguments' unless opts . empty? { } . tap do | h | attributes . each do | attr , val | h [ attr ] = val . as_json end end end


Input: Gets a list of servers from OpenStack [CODESPLIT] def servers ( id ) endpoint = "/servers" unless id . nil? endpoint = endpoint + "/" + id end return get_request ( address ( endpoint ) , @token ) end


Input: Creates a server on OpenStack . [CODESPLIT] def create_server ( name , image , flavor , networks = nil , keypair = nil , security_group = nil , metadata = nil ) data = { "server" => { "name" => name , "imageRef" => image , "flavorRef" => flavor , } } unless networks . nil? data [ "server" ] [ "networks" ] = networks end unless keypair . nil? data [ "server" ] [ "key_name" ] = keypair end unless security_group . nil? data [ "server" ] [ "security_group" ] = security_group end return post_request ( address ( "/servers" ) , data , @token ) end


Input: Perform an action on a server on Openstack by passing an id and an action some actions require more data . [CODESPLIT] def action ( id , act , * args ) data = case act when "reboot" then { 'reboot' => { "type" => args [ 0 ] } } when "vnc" then { 'os-getVNCConsole' => { "type" => "novnc" } } when "stop" then { 'os-stop' => 'null' } when "start" then { 'os-start' => 'null' } when "pause" then { 'pause' => 'null' } when "unpause" then { 'unpause' => 'null' } when "suspend" then { 'suspend' => 'null' } when "resume" then { 'resume' => 'null' } when "create_image" then { 'createImage' => { 'name' => args [ 0 ] , 'metadata' => args [ 1 ] } } else raise "Invalid Action" end return post_request ( address ( "/servers/" + id + "/action" ) , data , @token ) end


Input: Delete an image stored on Openstack through the nova endpoint [CODESPLIT] def delete_image ( id ) uri = URI . parse ( "http://" + @location . host + ":" + @location . port . to_s + "/v2/images/" + id ) return delete_request ( uri , @token ) end


Input: Get method use by all other API qeury methods fetch records from the Sqoot API V2 url and provide wrapper functionality [CODESPLIT] def get ( path , opts = { } , wrapper = :: Hashie :: Mash ) uri , headers = url_generator ( path , opts ) begin json = JSON . parse uri . open ( headers ) . read result = wrapper . new json @query_options = result . query result rescue => e logger ( error : e ) nil end end


Input: Generate valid Sqoot API V2 url and provide two different way of authentication : : header : parameter [CODESPLIT] def url_generator ( path , opts = { } , require_key = false ) uri = URI . parse base_api_url headers = { read_timeout : read_timeout } uri . path = '/v2/' + path query = options_parser opts endpoint = path . split ( '/' ) [ 0 ] case authentication_method when :header headers . merge! 'Authorization' => "api_key #{api_key(endpoint)}" query += "&api_key=#{api_key(endpoint)}" if require_key when :parameter query += "&api_key=#{api_key(endpoint)}" end uri . query = query @sqoot_query_uri = uri [ uri , headers ] end


Input: Decide which api key should be used : private public [CODESPLIT] def api_key ( endpoint = '' ) if private_endpoints . include? endpoint private_api_key elsif public_endpoints . include? endpoint public_api_key else fail "No such endpoint #{endpoint} available." end end


Input: Example : options = { per_page : 10 page : 1 } Options should be parsed as http query : per_page = 10&page = 1 [CODESPLIT] def options_parser ( options = { } ) query = options . map do | key , value | [ key , value ] . map ( :to_s ) . join ( '=' ) end . join ( '&' ) URI . encode query end


Input: translations [CODESPLIT] def build_translations # if is_translated langs = Language . list_with_default else langs = [ '' ] end # langs_missing = langs - self . translations . all . map { | r | r . lang } langs_missing . each do | lang | self . translations . new ( :lang => lang ) end end


Input: content [CODESPLIT] def content ( lang = '' ) filename = fullpath ( lang ) return nil if filename . nil? return '' if ! File . exists? filename File . read ( filename ) end


Input: operations with path [CODESPLIT] def set_basepath if self . parent . nil? self . basepath = self . basename self . basedirpath ||= '' else self . basepath = self . parent . basepath + '/' + self . basename self . basedirpath ||= self . parent . basepath + '/' end end


Input: callbacks [CODESPLIT] def _before_validation fix_basedirpath # parent, basedirpath if self . parent_id . nil? && ! self . basedirpath . blank? set_parent_from_basedirpath elsif self . basedirpath . nil? && ! self . parent_id . nil? set_basedirpath_from_parent end set_basepath end


Input: Retrieve information of commissions based on the following parameters [CODESPLIT] def commissions ( options = { } ) options = update_by_expire_time options if commissions_not_latest? ( options ) @rsqoot_commissions = get ( 'commissions' , options , SqootCommission ) @rsqoot_commissions = @rsqoot_commissions . commissions if @rsqoot_commissions end logger ( uri : sqoot_query_uri , records : @rsqoot_commissions , type : 'commissions' , opts : options ) @rsqoot_commissions end


Input: import templates [CODESPLIT] def reviewimport_templates # input @dirname = params [ :dirname ] # work @backup_basedir = Optimacms :: BackupMetadata :: Backup . make_backup_dir_path @dirname @backup_templates_dirpath = File . join ( @backup_basedir , "templates" ) @analysis = Optimacms :: BackupMetadata :: TemplateImport . analyze_data_dir ( @backup_templates_dirpath ) end


Input: import pages [CODESPLIT] def reviewimport_pages # input @dirname = params [ :dirname ] # work @backup_basedir = Optimacms :: BackupMetadata :: Backup . make_backup_dir_path @dirname @backup_templates_dirpath = File . join ( @backup_basedir , "pages" ) @analysis = Optimacms :: BackupMetadata :: PageImport . analyze_data_dir ( @backup_templates_dirpath ) end


Input: List all available leagues . [CODESPLIT] def leagues ( opts = { } ) season = opts . fetch ( :season ) { Time . now . year } json_response get ( "competitions/?season=#{season}" ) end


Input: Show League Table / current standing . Filters : [CODESPLIT] def league_table ( id , opts = { } ) raise IdMissingError , 'missing id' if id . nil? match_day = opts [ :match_day ] uri = "competitions/#{id}/leagueTable/" url = match_day . nil? ? uri : "#{uri}?matchday=#{match_day}" json_response get ( url ) end


Input: List all fixtures for a certain league . Filters : [CODESPLIT] def league_fixtures ( id , opts = { } ) raise IdMissingError , 'missing id' if id . nil? time_frame = opts [ :time_frame ] match_day = opts [ :match_day ] uri = "competitions/#{id}/fixtures/" url = time_frame . nil? ? uri : "#{uri}?timeFrame=#{time_frame}" url = match_day . nil? ? url : "#{url}?matchday=#{match_day}" json_response get ( url ) end


Input: List fixtures across a set of leagues . Filters : [CODESPLIT] def fixtures ( opts = { } ) time_frame = opts [ :time_frame ] league = opts [ :league ] uri = "fixtures/" url = time_frame . nil? ? uri : "#{uri}?timeFrame=#{time_frame}" url = league . nil? ? url : "#{url}?league=#{league}" json_response get ( url ) end


Input: Show one fixture . Filters : [CODESPLIT] def fixture ( id , opts = { } ) raise IdMissingError , 'missing id' if id . nil? head2head = opts [ :head2head ] uri = "fixtures/#{id}/" url = head2head . nil? ? uri : "#{uri}?head2head=#{head2head}" json_response get ( url ) end


Input: Show all fixtures for a certain team . Filters : [CODESPLIT] def team_fixtures ( id , opts = { } ) raise IdMissingError , 'missing id' if id . nil? season = opts [ :season ] time_frame = opts [ :time_frame ] venue = opts [ :venue ] uri = "teams/#{id}/fixtures/" url = season . nil? ? uri : "#{uri}?season=#{season}" url = time_frame . nil? ? url : "#{url}?timeFrame=#{time_frame}" url = venue . nil? ? url : "#{url}?venue=#{venue}" json_response get ( url ) end


Input: Add match method which work like case statement but for types [CODESPLIT] def match ( * args , & block ) z = Module . new do include Ov extend self def try ( * args , & block ) let :anon_method , args , block end def otherwise ( & block ) let :otherwise , block end instance_eval block end begin z . anon_method ( args ) rescue Ov :: NotImplementError => e z . otherwise end end


Input: GET / pages / new [CODESPLIT] def new @page = Page . new ( path : '/' ) if params [ :path ] . present? @page . path = CGI :: unescape ( params [ :path ] ) end end


Input: Tries to return the value of the column identified by index corresponding accessor or header . It throws an IndexError exception if the referenced index lies outside of the array bounds . This error can be prevented by supplying a second argument which will act as a default value . [CODESPLIT] def fetch ( column , * default_value , & default_block ) raise ArgumentError , "Must only provide at max one default value or one default block" if default_value . size > ( block_given? ? 0 : 1 ) index = case column when Symbol then @table . index_for_accessor ( column ) when String then @table . index_for_header ( column ) when Integer then column else raise InvalidColumnSpecifier , "Invalid index type, expected Symbol, String or Integer, but got #{column.class}" end @data . fetch ( index , default_value , default_block ) end


Input: Convenience access of values in the row . Can either be used like Array# [] i . e . it accepts an offset an offset + length or an offset - to - offset range . Alternatively you can use a Symbol if it s a valid accessor in this table . And the last variant is using a String which will access the value of the corresponding header . [CODESPLIT] def [] ( a , b = nil ) if b || a . is_a? ( Range ) then slice ( a , b ) else at ( a ) end end


Input: Access a single cell by either index index - range accessor or header - name . [CODESPLIT] def at ( column ) case column when Symbol then at_accessor ( column ) when String then at_header ( column ) when Integer then at_index ( column ) when Range then @data [ column ] else raise InvalidColumnSpecifier , "Invalid index type, expected Symbol, String or Integer, but got #{column.class}" end end


Input: Access multiple values by either index index - range accessor or header - name . [CODESPLIT] def values_at ( * columns ) result = [ ] columns . each do | column | data = at ( column ) if column . is_a? ( Range ) result . concat ( data ) if data else result << data end end result end


Input: Allow reading and writing cell values by their accessor name . [CODESPLIT] def method_missing ( name , * args , & block ) return super unless @table . accessors? name =~ / \w / name_mod , assign = $1 , $2 index = @table . index_for_accessor ( name_mod ) arg_count = assign ? 1 : 0 return super unless index raise ArgumentError , "Wrong number of arguments (#{args.size} for #{arg_count})" if args . size > arg_count if assign then @data [ index ] = args . first else @data [ index ] end end


Input: Providers must define an authorize method . This is used to initialize and set authentication parameters to access the API [CODESPLIT] def authorize ( auth = { } ) @authentication ||= TaskMapper :: Authenticator . new ( auth ) auth = @authentication if ( auth . account . nil? and auth . subdomain . nil? ) or auth . username . nil? or auth . password . nil? raise "Please provide at least an account (subdomain), username and password)" end UnfuddleAPI . protocol = auth . protocol if auth . protocol? UnfuddleAPI . account = auth . account || auth . subdomain UnfuddleAPI . authenticate ( auth . username , auth . password ) end


Input: : nodoc : [CODESPLIT] def b64_encode ( string ) if Base64 . respond_to? ( :strict_encode64 ) Base64 . strict_encode64 ( string ) else # Fall back to stripping out newlines on Ruby 1.8. Base64 . encode64 ( string ) . gsub ( / \n / , '' ) end end


Input: @!method initialize ( api_key = get_api_key_from_env ) Constructor method @param api_key [ String ] ( see api_key ) @return [ Reliquary :: Client ] the initialized client [CODESPLIT] def parse ( json ) begin # strip off some layers of nonsense added by Oj MultiJson . load ( json , :symbolize_keys => true ) . values [ 0 ] rescue StandardError => e raise e end end


Input: @!method method_missing ( method_name * args &block ) Delegate HTTP method calls to RestClient :: Resource [CODESPLIT] def method_missing ( method_name , * args , & block ) begin self . api_base . send ( method_name . to_sym , args , block ) rescue StandardError => e raise e end end


Input: Adds a watch for a shallow change in the contents ( attributes elements or key - value pairs ) of one or more reactive objects . [CODESPLIT] def on_change_in ( * args , except : nil , & block ) args . each do | arg | ensure_reactive ( arg ) traverse ( arg , :shallow , except , args . size > 1 || block . arity == 3 , block ) end end


Input: Does a deep traversal of all values reachable from the given root object ( s ) . [CODESPLIT] def on_deep_change_in ( * roots , except : nil , & block ) roots . each do | root | ensure_reactive ( root ) traverse ( root , :node , except , true , block ) end end


Input: Must behave like a Volt :: Model and respond to #get ( attribute ) [CODESPLIT] def reactive_model? ( model ) Volt :: Model === model || # dirty way of letting anything be reactive if it wants ( model . respond_to? ( :reactive_model? ) && model . reactive_model? ) || ( model . class . respond_to? ( :reactive_model? ) && model . class . reactive_model? ) end


Input: Must behave like a Volt :: ArrayModel or Volt :: ReactiveArray [CODESPLIT] def reactive_array? ( model ) Volt :: ArrayModel === model || Volt :: ReactiveArray === model || # dirty way of letting anything be reactive if it wants ( model . respond_to? ( :reactive_array? ) && model . reactive_array? ) || ( model . class . respond_to? ( :reactive_array? ) && model . class . reactive_array? ) end


Input: Must behave like a Volt :: ReactiveHash [CODESPLIT] def reactive_hash? ( model ) Volt :: ReactiveHash === model || # dirty way of letting anything be reactive if it wants ( model . respond_to? ( :reactive_hash? ) && model . reactive_hash? ) || ( model . class . respond_to? ( :reactive_hash? ) && model . class . reactive_hash? ) end


Input: method_option : person : aliases = > - p : desc = > Delete the file after parsing it [CODESPLIT] def create ( message = "" ) if "help" == message invoke ( :help , [ "create" ] ) ; exit 0 end if File . pipe? ( STDIN ) || File . select ( [ STDIN ] , [ ] , [ ] , 0 ) != nil then message = STDIN . readlines ( ) . join ( "" ) end url = "https://api.pushbullet.com/v2/pushes" token = Utils :: get_token ( options ) unless message . empty? args = Utils :: get_push_args ( options ) args [ 'body' ] = message Utils :: send ( url , token , "post" , args ) else puts "Nothing to do." end end


Input:
Add a new secondary index to this model . Default option is : type = > : int can also be : bin Default option is : multi = > false can also be true Option : map can be used to map the index to a model ( see map_model ) . This assumes by default that the index name ends in _id ( use : map = > true ) If it ends in something else use : map = > _suffix [CODESPLIT] def index2i ( name , opts = { } ) name = name . to_s opts . replace ( { :type => :int , :multi => false , :finder => :find } . merge ( opts ) ) indexes2i [ name ] = opts class_eval %Q{
        def #{name}
          @indexes2i['#{name}']
        end

        def #{name}=(value)
          @indexes2i['#{name}'] = value
        end
      } if opts [ :map ] if opts [ :map ] === true # assume that it ends in _id model_name = name [ 0 .. - 4 ] map_model ( model_name , opts ) else model_name = name [ 0 .. - ( opts [ :map ] . length + 1 ) ] map_model ( model_name , opts . merge ( :suffix => opts [ :map ] ) ) end end end


Input:
The map_model method is a convenience method to map the model_id to getters and setters . The assumption is that you have a value or index2i for model_id . The default suffix is _id so map_model : promotion implies that promotion_id is the index2i . [CODESPLIT] def map_model ( model_name , opts = { } ) model_name = model_name . to_s class_name = Risky :: Inflector . classify ( model_name ) opts . replace ( { :type => :index2i , :suffix => '_id' } . merge ( opts ) ) class_eval %Q{
        def #{model_name}
          @#{model_name} ||= #{class_name}.#{opts[:finder]} #{model_name}#{opts[:suffix]}
        end

        def #{model_name}=(value)
          @#{model_name} = value
          self.#{model_name}#{opts[:suffix]} = value.nil? ? nil : value.id
        end

        def #{model_name}_id=(value)
          @#{model_name} = nil if self.#{model_name}_id != value
          indexes2i['#{model_name}#{opts[:suffix]}'] = value
        end
      } end


Input: Get a list of a tenants routers [CODESPLIT] def routers ( id = nil ) endpoint = "routers" unless id . nil? endpoint = endpoint + "/" + id end return get_request ( address ( endpoint ) , @token ) end


Input: Create a new router with a given name . [CODESPLIT] def create_router ( name , admin_state_up = true ) data = { 'router' => { 'name' => name , 'admin_state_up' => admin_state_up , } } return post_request ( address ( "routers" ) , data , @token ) end


Input: Delete a connection between a subnet and router given either port or subnet ids . [CODESPLIT] def delete_router_interface ( router , id , type ) data = case type when 'port' then { 'port_id' => id } when 'subnet' then { 'subnet_id' => id } else raise "Invalid Interface Type" end return put_request ( address ( "routers/" + router + "/remove_router_interface" ) , data , @token ) end


Input: find in self find in ancestors find types find any types [CODESPLIT] def where ( method ) @complete , @result = nil , nil z = find_or_next ( method ) { | method | self . find { | m | m . eql? ( method ) } } . find_or_next ( method ) { | method | self . find { | m | m . eql0? ( method ) } } . find_or_next ( method ) { | method | self . find { | m | m . like? ( method ) } } . find_or_next ( method ) { | method | self . find { | m | m . like0? ( method ) } } . get end


Input: load config from files [CODESPLIT] def load config_files . each do | file | config = YAML :: load ( File . open ( file ) ) @config . merge! config end end


Input: Retrieve a list of providers base on the following parameters [CODESPLIT] def providers ( options = { } ) options = update_by_expire_time options query = options . delete ( :query ) if providers_not_latest? ( options ) @rsqoot_providers = get ( 'providers' , options , SqootProvider ) @rsqoot_providers = @rsqoot_providers . providers . map ( :provider ) if @rsqoot_providers end result = query . present? ? query_providers ( query ) : @rsqoot_providers logger ( uri : sqoot_query_uri , records : result , type : 'providers' , opts : options ) result end


Input: Retrieve a list of categories base on the following parameters [CODESPLIT] def categories ( options = { } ) options = update_by_expire_time options query = options . delete ( :query ) if categories_not_latest? ( options ) @rsqoot_categories = get ( 'categories' , options , SqootCategory ) @rsqoot_categories = @rsqoot_categories . categories . map ( :category ) if @rsqoot_categories end result = query . present? ? query_categories ( query ) : @rsqoot_categories logger ( uri : sqoot_query_uri , records : result , type : 'categories' , opts : options ) result end


Input: This method sets up the + Role + class with all baked in methods . [CODESPLIT] def challah_role unless included_modules . include? ( InstanceMethods ) include InstanceMethods extend ClassMethods end class_eval do # Validations ################################################################ validates :name , :presence => true , :uniqueness => true # Relationships ################################################################ has_many :permission_roles , :dependent => :destroy has_many :permissions , :through => :permission_roles , :order => 'permissions.name' has_many :users , :order => 'users.first_name, users.last_name' # Scoped Finders ################################################################ default_scope order ( 'roles.name' ) # Callbacks ################################################################ after_save :save_permission_keys # Attributes ################################################################ attr_accessible :description , :default_path , :locked , :name end end


Input: def nil_if_blank self . trial_end = nil if self . trial_end . blank? end [CODESPLIT] def check_for_upgrade if plan_id_changed? old_plan = Plan . find ( plan_id_was ) if plan_id_was . present? self . upgraded = true if old_plan . nil? || old_plan . order < plan . order end end


Input: if chainable method or returns self for some other reason return this proxy instead [CODESPLIT] def method_missing ( name , * args , & block ) obj = __getobj__ __substitute_self__ ( obj . __send__ ( name , args , block ) , obj ) end


Input: Retrieve a list of deals based on the following parameters [CODESPLIT] def deals ( options = { } ) options = update_by_expire_time options if deals_not_latest? ( options ) uniq = ! ! options . delete ( :uniq ) @rsqoot_deals = get ( 'deals' , options , SqootDeal ) || [ ] @rsqoot_deals = @rsqoot_deals . deals . map ( :deal ) unless @rsqoot_deals . empty? @rsqoot_deals = uniq_deals ( @rsqoot_deals ) if uniq end logger ( uri : sqoot_query_uri , records : @rsqoot_deals , type : 'deals' , opts : options ) @rsqoot_deals end


Input: Retrieve a deal by id [CODESPLIT] def deal ( id , options = { } ) options = update_by_expire_time options if deal_not_latest? ( id ) @rsqoot_deal = get ( "deals/#{id}" , options , SqootDeal ) @rsqoot_deal = @rsqoot_deal . deal if @rsqoot_deal end logger ( uri : sqoot_query_uri , records : [ @rsqoot_deal ] , type : 'deal' , opts : options ) @rsqoot_deal end


Input: Auto Increment for deals query . [CODESPLIT] def total_sqoot_deals ( options = { } ) @total_deals ||= [ ] @cached_pages ||= [ ] page = options [ :page ] || 1 check_query_change options unless page_cached? page @total_deals += deals ( options ) @total_deals . uniq! @cached_pages << page . to_s @cached_pages . uniq! end @total_deals end


Input: Uniq deals from Sqoot because there are some many duplicated deals with different ids Simplely distinguish them by their titles [CODESPLIT] def uniq_deals ( deals = [ ] ) titles = deals . map ( :title ) . uniq titles . map do | title | deals . map do | deal | deal if deal . try ( :title ) == title end . compact . last end . flatten end


Input: A status checker for method : total_sqoot_deals If the query parameters changed this will reset the cache else it will do nothing [CODESPLIT] def check_query_change ( options = { } ) options = update_by_expire_time options @last_deals_query ||= '' current_query = options [ :query ] . to_s current_query += options [ :category_slugs ] . to_s current_query += options [ :location ] . to_s current_query += options [ :radius ] . to_s current_query += options [ :online ] . to_s current_query += options [ :expired_in ] . to_s current_query += options [ :per_page ] . to_s if @last_deals_query != current_query @last_deals_query = current_query @total_deals = [ ] @cached_pages = [ ] end end


Input: Read cookies from Mozilla cookies . txt - style IO stream [CODESPLIT] def load_cookies ( file ) now = :: Time . now io = case file when String open ( file ) else file end io . each_line do | line | line . chomp! line . gsub! ( / / , '' ) fields = line . split ( "\t" ) next if fields . length != 7 name , value , domain , for_domain , path , secure , version = fields [ 5 ] , fields [ 6 ] , fields [ 0 ] , ( fields [ 1 ] == "TRUE" ) , fields [ 2 ] , ( fields [ 3 ] == "TRUE" ) , 0 expires_seconds = fields [ 4 ] . to_i expires = ( expires_seconds == 0 ) ? nil : :: Time . at ( expires_seconds ) next if expires and ( expires < now ) cookies . add ( name , value , domain : domain , path : path , expires : expires , secure : secure ) end io . close if String === file self end


Input: Write cookies to Mozilla cookies . txt - style IO stream [CODESPLIT] def dump_cookies ( file ) io = case file when String open ( file , "w" ) else file end cookies . to_a . each do | cookie | io . puts ( [ cookie [ :domain ] , "FALSE" , # for_domain cookie [ :path ] , cookie [ :secure ] ? "TRUE" : "FALSE" , cookie [ :expires ] . to_i . to_s , cookie [ :name ] , cookie [ :value ] ] . join ( "\t" ) ) end io . close if String === file self end


Input: quick set value . [CODESPLIT] def set2 ( selector , value = nil ) elem = element ( xpath : selector ) . to_subtype case elem when Watir :: Radio elem . set when Watir :: Select elem . select value when Watir :: Input elem . set value when Watir :: TextArea elem . set value else elem . click end end


Input: Add expired time functionality to this gem By default is 1 . hour and can be replaced anywhere [CODESPLIT] def update_by_expire_time ( options = { } ) @expired_in = options [ :expired_in ] if options [ :expired_in ] . present? time = Time . now . to_i / expired_in . to_i options . merge ( expired_in : time ) end


Input: Make a GET API call with the current path value and [CODESPLIT] def get ( options = { } ) uri = new_uri params = merge_params ( options ) uri . query = URI . encode_www_form ( params ) Net :: HTTP . start ( uri . host , uri . port , :use_ssl => uri . scheme == 'https' ) do | http | request = Net :: HTTP :: Get . new ( uri ) response = http . request ( request ) unless response . is_a? ( Net :: HTTPSuccess ) raise "#{response.code} #{response.message}\n#{response.body}" end return response . body end end


Input: layout [CODESPLIT] def newlayout @item = model . new ( { :tpl_format => Optimacms :: Template :: EXTENSION_DEFAULT , :type_id => TemplateType :: TYPE_LAYOUT } ) item_init_parent @item . set_basedirpath_from_parent @url_back = url_list end


Input: block [CODESPLIT] def newblock @item = model . new ( { :tpl_format => Optimacms :: Template :: EXTENSION_DEFAULT , :type_id => TemplateType :: TYPE_BLOCKVIEW } ) item_init_parent @item . set_basedirpath_from_parent @url_back = url_list end


Input: folders [CODESPLIT] def newfolder @item = model . new ( :is_folder => true ) item_init_parent @item . basedirpath = @item . parent . basepath + '/' unless @item . parent_id . nil? end


Input: No ID provided - Lists details for available images . ID provided - Shows the image details as headers and the image binary in the body . [CODESPLIT] def images ( id , tenant_id ) if id . nil? return get_request ( address ( tenant_id , "images/detail" ) , @token ) else return get_request ( address ( tenant_id , "images/" + id ) , @token ) end end


Input: Registers a virtual machine image . [CODESPLIT] def image_create ( name , disk_format , container_format , create_image , tenant_id ) data = { :name => name , :disk_format => disk_format , :container_format => container_format } unless create_image . nil? data [ :create_image ] = create_image end post_request ( address ( tenant_id , "images" ) , data , @token ) end


Input: Replaces the membership list for an image . [CODESPLIT] def replace_memberships ( id , memberships , tenant_id ) data = { :memberships => memberships } put_request ( address ( tenant_id , "images/" + id + "/members" ) , data , @token ) end


Input: Adds a member to an image . [CODESPLIT] def add_member ( id , member_id , can_share , tenant_id ) if can_share . nil? data = { :member => { :can_share => false } } else data = { :member => { :can_share => can_share } } end put_request ( address ( tenant_id , "images/" + id + "/members/" + member_id ) , data , @token ) end


Input: Like mkdir - p + dir + . If + owner + is specified the directory will be chowned to owner . If + mode + is specified the directory will be chmodded to mode . Like all file commands the operation will be printed out if verbose? . [CODESPLIT] def mkdir ( dir , owner : nil , mode : nil ) FileUtils . mkdir_p ( dir , verbose : verbose? ) chown ( dir , owner ) if owner chmod ( dir , mode ) if mode end


Input: Like cp - pr + src + + dst . If + mkdir + is true the dst directoy will be created if necessary before the copy . If + owner + is specified the directory will be chowned to owner . If + mode + is specified the directory will be chmodded to mode . Like all file commands the operation will be printed out if verbose? . [CODESPLIT] def cp ( src , dst , mkdir : false , owner : nil , mode : nil ) mkdir_if_necessary ( File . dirname ( dst ) ) if mkdir FileUtils . cp_r ( src , dst , preserve : true , verbose : verbose? ) chown ( dst , owner ) if owner && ! File . symlink? ( dst ) chmod ( dst , mode ) if mode end


Input: Like mv + src + + dst . If + mkdir + is true the dst directoy will be created if necessary before the copy . Like all file commands the operation will be printed out if verbose? . [CODESPLIT] def mv ( src , dst , mkdir : false ) mkdir_if_necessary ( File . dirname ( dst ) ) if mkdir FileUtils . mv ( src , dst , verbose : verbose? ) end


Input: Like ln - sf + src + + dst . The command will be printed out if verbose? . [CODESPLIT] def ln ( src , dst ) FileUtils . ln_sf ( src , dst , verbose : verbose? ) rescue Errno :: EEXIST => e # It's a race - this can occur because ln_sf removes the old # dst, then creates the symlink. Raise if they don't match. raise e if ! ( File . symlink? ( dst ) && src == File . readlink ( dst ) ) end


Input: Runs #mkdir but ONLY if + dir + doesn t already exist . Returns true if directory had to be created . This is useful with verbose? to get an exact changelog . [CODESPLIT] def mkdir_if_necessary ( dir , owner : nil , mode : nil ) return if File . exist? ( dir ) || File . symlink? ( dir ) mkdir ( dir , owner : owner , mode : mode ) true end


Input: Runs #cp but ONLY if + dst + doesn t exist or differs from + src + . Returns true if the file had to be copied . This is useful with verbose? to get an exact changelog . [CODESPLIT] def cp_if_necessary ( src , dst , mkdir : false , owner : nil , mode : nil ) return if File . exist? ( dst ) && FileUtils . compare_file ( src , dst ) cp ( src , dst , mkdir : mkdir , owner : owner , mode : mode ) true end


Input: Runs #ln but ONLY if + dst + isn t a symlink or differs from + src + . Returns true if the file had to be symlinked . This is useful with verbose? to get an exact changelog . [CODESPLIT] def ln_if_necessary ( src , dst ) if File . symlink? ( dst ) return if src == File . readlink ( dst ) rm ( dst ) end ln ( src , dst ) true end


Input: Like chown user : user file . Like all file commands the operation will be printed out if verbose? . [CODESPLIT] def chown ( file , user ) # who is the current owner? @scripto_uids ||= { } @scripto_uids [ user ] ||= Etc . getpwnam ( user ) . uid uid = @scripto_uids [ user ] return if File . stat ( file ) . uid == uid FileUtils . chown ( uid , uid , file , verbose : verbose? ) end


Input: Like chmod mode file . Like all file commands the operation will be printed out if verbose? . [CODESPLIT] def chmod ( file , mode ) return if File . stat ( file ) . mode == mode FileUtils . chmod ( mode , file , verbose : verbose? ) end


Input: Like rm - rf && mkdir - p . Like all file commands the operation will be printed out if verbose? . [CODESPLIT] def rm_and_mkdir ( dir ) raise "don't do this" if dir == "" FileUtils . rm_rf ( dir , verbose : verbose? ) mkdir ( dir ) end


Input: Copy mode atime and mtime from + src + to + dst + . This one is rarely used and doesn t echo . [CODESPLIT] def copy_metadata ( src , dst ) stat = File . stat ( src ) File . chmod ( stat . mode , dst ) File . utime ( stat . atime , stat . mtime , dst ) end


Input: Atomically write to + path + . An open temp file is yielded . [CODESPLIT] def atomic_write ( path ) tmp = Tempfile . new ( File . basename ( path ) ) yield ( tmp ) tmp . close chmod ( tmp . path , 0o644 ) mv ( tmp . path , path ) ensure rm_if_necessary ( tmp . path ) end


Input: can be initialized from the following sources : - a WordTree :: Disk :: Library object - an open File object ( containing a list of files or paths to books ) - a String directory ( presumed to be the library on disk ) - a String file ( containing a list of files or paths to books ) [CODESPLIT] def iterable_from_source ( source ) case source when WordTree :: Disk :: Library then source when File then source . read . split ( "\n" ) . tap do | file | file . close end when String then if File . directory? ( source ) WordTree :: Disk :: Library . new ( source ) elsif File . exist? ( source ) IO . read ( source ) . split ( "\n" ) else raise Errno :: ENOENT , "Unable to find source for BookList, #{source.inspect}" end end end


Input: This implementation is what I m loosely calling type 1 or regular object creation : - Assume we re looking for a class to create an instance with - it may or may not have a declared list of named objects it needs to be constructed with [CODESPLIT] def type_1_constructor ( klass , name , object_context , overrides = nil ) klass ||= class_finder . find_class ( name ) if ! klass . object_peers . empty? anchor_object_peers object_context , klass . object_peers end constructor_func = nil if klass . has_object_definition? object_map = dependency_resolver . resolve_for_class ( klass , object_context , overrides ) constructor_func = lambda do klass . new ( object_map ) end elsif Utilities . has_zero_arg_constructor? ( klass ) # Default construction constructor_func = lambda do klass . new end else # Oops, out of ideas on how to build. raise ArgumentError . new ( "Class #{klass} has no special component needs, but neither does it have a zero-argument constructor." ) ; end object = nil Conject . override_object_context_with object_context do begin object = constructor_func . call rescue Exception => ex origin = "#{ex.message}\n\t#{ex.backtrace.join("\n\t")}" name ||= "(no name)" raise "Error while constructing object '#{name}' of class #{klass}: #{origin}" end end end


Input: Should be run by another thread - respond to all queued requests [CODESPLIT] def handle_requests until @requestmq . empty? request = @requestmq . deq ( true ) begin request . response = @app . call ( request . env ) rescue Exception => e request . exception = e ensure body = request . response . try ( :last ) body . close if body . respond_to? :close end end end


Input: Similar to Tabledata :: Table# [] but only returns values for this column . Provides array like access to this column s data . Only considers body values ( i . e . does not consider header and footer ) . [CODESPLIT] def [] ( * args ) rows = @table . body [ args ] if rows . is_a? ( Array ) # slice rows . map { | row | row [ @index ] } else # single row rows [ @index ] end end


Input: @param [ Hash ] options @option options [ Symbol ] : include_header Defaults to true . If set to false the header ( if present ) is excluded . @option options [ Symbol ] : include_footer Defaults to true . If set to false the footer ( if present ) is excluded . [CODESPLIT] def to_a ( options = nil ) data = @table . data . transpose [ @index ] if options start_offset = options [ :include_header ] && @table . headers? ? 1 : 0 end_offset = options [ :include_footer ] && @table . footer? ? - 2 : - 1 data [ start_offset .. end_offset ] else data end end


Input: Add a new folder to [CODESPLIT] def add_shared_folder ( folders ) folders = Array ( folders ) # can't use dig() might not be ruby 2.3 if ! @config . has_key? ( "folders" ) @config [ "folders" ] = [ ] end # all paths must be fully qualified.  If we were asked to do a relative path, change # it to the current directory since that's probably what the user wanted.  Not right? # user supply correct path! folders . each { | folder | if ! folder . start_with? '/' folder = "#{Dir.pwd}/#{folder}" end @config [ "folders" ] << folder } end


Input: return a hash of the configfile or empty hash if error encountered [CODESPLIT] def configfile_hash config = { } begin json = File . read ( configfile ) config = JSON . parse ( json ) rescue Errno :: ENOENT # depending on whether the instance has been saved or not, we may not # yet have a configfile - allow to proceed @logger . debug "#{configfile} does not exist" @force_save = true rescue JSON :: ParserError # swallow parse errors so that we can destroy and recreate automatically @logger . debug "JSON parse error in #{configfile}" @force_save = true end config end


Input: Accounts [CODESPLIT] def account ( id , head ) if head get_request ( address ( id ) , @token ) else head_request ( address ( id ) , @token ) end end


Input: Containers [CODESPLIT] def container ( account , container , head ) if head get_request ( address ( account + "/" + container ) , @token ) else head_request ( address ( account + "/" + container ) , @token ) end end


Input: 通过（名称、字符）替换表情 [CODESPLIT] def replace_emoji_with_images ( string ) return string unless string html ||= string . dup html = replace_name_with_images ( html ) html = replace_unicode_with_images ( html . to_str ) return html end


Input: 通过（名称）替换表情 [CODESPLIT] def replace_name_with_images ( string ) unless string && string . match ( names_regex ) return string end string . to_str . gsub ( names_regex ) do | match | if names . include? ( $1 ) %Q{<img class="emoji" src="//#{ image_url_for_name($1) }" />} else match end end end


Input: 通过（字符）替换表情 [CODESPLIT] def replace_unicode_with_images ( string ) unless string && string . match ( unicodes_regex ) return string end html ||= string . dup html . gsub! ( unicodes_regex ) do | unicode | %Q{<img class="emoji" src="//#{ image_url_for_unicode(unicode) }" />} end end


Input: 通过（名称）合成图片地址 [CODESPLIT] def image_url_for_name ( name ) image_url = "#{asset_host}#{ File.join(asset_path, name) }.png" if image_url . present? if asset_size . present? && asset_size . in? ( sizes ) image_url = [ image_url , asset_size ] . join ( asset_delimiter ) end end return image_url end


Input: Last parameter in array can be a hash of objects It is implemented this way ( instead of ( * models instrument : true )) because when passing in Sequel models ruby will invoke the . to_hash on them causing a load when trying to restructure the args [CODESPLIT] def finalize! ( * models_and_opts ) models , instrument = if models_and_opts . last . kind_of? ( :: Hash ) ins = models_and_opts . last . fetch ( :instrument ) do true end [ models_and_opts [ 0 .. - 2 ] , ins ] else [ models_and_opts , true ] end if instrument ActiveSupport :: Notifications . instrument 'praxis.mapper.finalize' do _finalize! ( models ) end else _finalize! ( models ) end end


Input: don t doc . never ever use yourself! FIXME : make private and fix specs that break? [CODESPLIT] def finalize_model! ( model , query = nil ) staged_queries = @staged [ model ] . delete ( :_queries ) || [ ] staged_keys = @staged [ model ] . keys non_identities = staged_keys - model . identities results = Set . new return results if @staged [ model ] . all? { | ( _key , values ) | values . empty? } if query . nil? query_class = @connection_manager . repository ( model . repository_name ) [ :query ] query = query_class . new ( self , model ) end # Apply any relevant blocks passed to track in the original queries staged_queries . each do | staged_query | staged_query . track . each do | ( association_name , block ) | next unless block spec = staged_query . model . associations [ association_name ] if spec [ :model ] == model query . instance_eval ( block ) if ( spec [ :type ] == :many_to_one || spec [ :type ] == :array_to_many ) && query . where file , line = block . source_location trace = [ "#{file}:#{line}" ] | caller raise RuntimeError , "Error finalizing model #{model.name} for association #{association_name.inspect} -- using a where clause when tracking associations of type #{spec[:type].inspect} is not supported" , trace end end end end # process non-unique staged keys #   select identity (any one should do) for those keys and stage blindly #   load and add records. if non_identities . any? to_stage = Hash . new do | hash , identity | hash [ identity ] = Set . new end non_identities . each do | key | values = @staged [ model ] . delete ( key ) rows = query . multi_get ( key , values , select : model . identities , raw : true ) rows . each do | row | model . identities . each do | identity | if identity . kind_of? Array to_stage [ identity ] << row . values_at ( identity ) else to_stage [ identity ] << row [ identity ] end end end end self . stage ( model , to_stage ) end model . identities . each do | identity_name | values = self . get_staged ( model , identity_name ) next if values . empty? query . where = nil # clear out any where clause from non-identity records = query . multi_get ( identity_name , values ) # TODO: refactor this to better-hide queries? self . queries [ model ] . add ( query ) results . merge ( add_records ( records ) ) # add nil records for records that were not found by the multi_get missing_keys = self . get_staged ( model , identity_name ) missing_keys . each do | missing_key | @row_keys [ model ] [ identity_name ] [ missing_key ] = nil get_staged ( model , identity_name ) . delete ( missing_key ) end end query . freeze # TODO: check whether really really did get all the records we should have.... results . to_a end


Input: return the record provided ( if added to the identity map ) or return the corresponding record if it was already present [CODESPLIT] def add_record ( record ) model = record . class record . identities . each do | identity , key | # FIXME: Should we be overwriting (possibly) a "nil" value from before? #        (due to that row not being found by a previous query) #        (That'd be odd since that means we tried to load that same identity) if ( existing = @row_keys [ model ] [ identity ] [ key ] ) # FIXME: should merge record into existing to add any additional fields return existing end get_staged ( model , identity ) . delete ( key ) @row_keys [ model ] [ identity ] [ key ] = record end @secondary_indexes [ model ] . each do | key , indexed_values | val = if key . kind_of? Array key . collect { | k | record . send ( k ) } else record . send ( key ) end indexed_values [ val ] << record end record . identity_map = self @rows [ model ] << record record end


Input: Turns all urls into clickable links . If a block is given each url is yielded and the result is used as the link text . [CODESPLIT] def urls ( text ) text . gsub ( @regex [ :protocol ] ) do scheme , href = $1 , $& punctuation = [ ] if auto_linked? ( $` , $' ) # do not change string; URL is already linked href else # don't include trailing punctuation character as part of the URL while href . sub! ( / #{ @regex [ :word_pattern ] } \/ / , '' ) punctuation . push $& if opening = @regex [ :brackets ] [ punctuation . last ] and href . scan ( opening ) . size > href . scan ( punctuation . last ) . size href << punctuation . pop break end end link_text = block_given? ? yield ( href ) : href href = '//' + href unless scheme "#{link_text}" + punctuation . reverse . join ( '' ) end end end


Input: Turns all email addresses into clickable links . If a block is given each email is yielded and the result is used as the link text . [CODESPLIT] def email_addresses ( text ) text . gsub ( @regex [ :mail ] ) do text = $& if auto_linked? ( $` , $' ) text else display_text = ( block_given? ) ? yield ( text ) : text # mail_to text, display_text "#{display_text}" end end end


Input: Specifies a new pluralization rule and its replacement . The rule can either be a string or a regular expression . The replacement should always be a string that may include references to the matched data from the rule . [CODESPLIT] def plural ( rule , replacement ) @uncountables . delete ( rule ) if rule . is_a? ( String ) @uncountables . delete ( replacement ) @plurals . insert ( 0 , [ rule , replacement ] ) end


Input: Specifies a new singularization rule and its replacement . The rule can either be a string or a regular expression . The replacement should always be a string that may include references to the matched data from the rule . [CODESPLIT] def singular ( rule , replacement ) @uncountables . delete ( rule ) if rule . is_a? ( String ) @uncountables . delete ( replacement ) @singulars . insert ( 0 , [ rule , replacement ] ) end


Input: Specifies a new irregular that applies to both pluralization and singularization at the same time . This can only be used for strings not regular expressions . You simply pass the irregular in singular and plural form . [CODESPLIT] def irregular ( singular , plural ) @uncountables . delete ( singular ) @uncountables . delete ( plural ) if singular [ 0 , 1 ] . upcase == plural [ 0 , 1 ] . upcase plural ( Regexp . new ( "(#{singular[0,1]})#{singular[1..-1]}$" , "i" ) , '\1' + plural [ 1 .. - 1 ] ) singular ( Regexp . new ( "(#{plural[0,1]})#{plural[1..-1]}$" , "i" ) , '\1' + singular [ 1 .. - 1 ] ) else plural ( Regexp . new ( "#{singular[0,1].upcase}(?i)#{singular[1..-1]}$" ) , plural [ 0 , 1 ] . upcase + plural [ 1 .. - 1 ] ) plural ( Regexp . new ( "#{singular[0,1].downcase}(?i)#{singular[1..-1]}$" ) , plural [ 0 , 1 ] . downcase + plural [ 1 .. - 1 ] ) singular ( Regexp . new ( "#{plural[0,1].upcase}(?i)#{plural[1..-1]}$" ) , singular [ 0 , 1 ] . upcase + singular [ 1 .. - 1 ] ) singular ( Regexp . new ( "#{plural[0,1].downcase}(?i)#{plural[1..-1]}$" ) , singular [ 0 , 1 ] . downcase + singular [ 1 .. - 1 ] ) end end


Input: run the action if valid and return true if successful [CODESPLIT] def execute raise errors . to_sentences unless valid? # default failing command result = false # protect command from recursion mutex = Mutagem :: Mutex . new ( 'revenc.lck' ) lock_successful = mutex . execute do result = system_cmd ( cmd ) end raise "action failed, lock file present" unless lock_successful result end


Input: = begin def my_set_render_template ( tpl_view tpl_layout ) @optimacms_tpl = tpl_view @optimacms_layout = tpl_layout end [CODESPLIT] def renderActionInOtherController ( controller , action , params , tpl_view = nil , tpl_layout = nil ) # include render into controller class if current_cms_admin_user controller . send 'include' , Optimacms :: Renderer :: AdminPageRenderer controller . send 'renderer_admin_edit' end # c = controller . new c . params = params if current_cms_admin_user #if !controller.respond_to?(:render_base, true) if ! c . respond_to? ( :render_base , true ) controller . send :alias_method , :render_base , :render controller . send :define_method , "render" do | options = nil , extra_options = { } , & block | if current_cms_admin_user && @pagedata render_with_edit ( options , extra_options , block ) else render_base ( options , extra_options , block ) end end end end #c.process_action(action, request) #c.dispatch(action, request) #c.send 'index_page' c . request = request #c.request.path_parameters = params.with_indifferent_access c . request . format = params [ :format ] || 'html' c . action_name = action c . response = ActionDispatch :: Response . new c . send 'my_set_render' c . send 'optimacms_set_pagedata' , @pagedata c . send 'my_set_render_template' , tpl_view , tpl_layout c . send 'my_set_meta' , @pagedata . meta #renderer_admin_edit #c.process_action(action) c . dispatch ( action , request , c . response ) #c.process_action(action, tpl_filename) #app = "NewsController".constantize.action(action) #app.process params # result #c c . response . body #app.response.body end


Input: rubocop : disable Metrics / MethodLength [CODESPLIT] def adjust_values ( act , payload ) payload . each do | key , value | case value when Hash act [ :tags ] . merge! ( value . select { | _ , v | v . is_a? ( String ) } ) when Numeric , Integer act [ :values ] [ key . to_sym ] = value . to_f when String , TrueClass , FalseClass act [ :values ] [ key . to_sym ] = value when Symbol act [ :values ] [ key . to_sym ] = value . to_s else next end end end


Input: rubocop : enable Metrics / MethodLength [CODESPLIT] def organize_event ( event ) act = { values : { duration : event . duration } , tags : { name : event . name } } adjust_values ( act , event . payload ) act end


Input: Output the results based on the requested output format [CODESPLIT] def output opts = options if opts . format FileUtils . mkdir_p opts . output_dir formatted_output end @results . clear end


Input: Run httperf from low_rate to high_rate stepping by rate_step [CODESPLIT] def run while @jobs . length > 0 do # do a warm up run first with the highest connection rate @current_job = @jobs . pop @current_rate = @current_job . high_rate . to_i httperf true ( @current_job . low_rate . to_i .. @current_job . high_rate . to_i ) . step ( @current_job . rate_step . to_i ) do | rate | @current_rate = rate httperf end output end end


Input: Detection [CODESPLIT] def file? ( filename ) return unless filename File . exist? File . join ( @library . source_path , filename . split ( '/' ) ) end


Input: Authenticate via keystone unless a token and tenant are defined then a unscoped token is returned with all associated data and stored in the [CODESPLIT] def authenticate ( username , password , tenant = nil ) data = { "auth" => { "passwordCredentials" => { "username" => username , "password" => password } } } unless tenant . nil? data [ "auth" ] [ "tenantName" ] = tenant end @data = post_request ( address ( "/tokens" ) , data , @token ) end


Input: Scope token provides two ways to call it : scope_token ( tenantName ) = > Just using the current token and a tenantName it scopes in the token . Token stays the same . scope_token ( username password tenantName ) = > This uses the username and password to reauthenticate with a tenant . The token changes . [CODESPLIT] def scope_token ( para1 , para2 = nil , para3 = nil ) if ( para2 . nil? ) data = { "auth" => { "tenantName" => para1 , "token" => { "id" => token ( ) } } } @data = post_request ( address ( "/tokens" ) , data , token ( ) ) else authenticate ( para1 , para2 , token ( ) , para3 ) end end


Input: Add a service to the keystone services directory [CODESPLIT] def add_to_services ( name , type , description ) data = { 'OS-KSADM:service' => { 'name' => name , 'type' => type , 'description' => description } } return post_request ( address ( "/OS-KSADM/services" ) , data , token ( ) ) end


Input: Add an endpoint list [CODESPLIT] def add_endpoint ( region , service_id , publicurl , adminurl , internalurl ) data = { 'endpoint' => { 'region' => region , 'service_id' => service_id , 'publicurl' => publicurl , 'adminurl' => adminurl , 'internalurl' => internalurl } } return post_request ( address ( "/endpoints" ) , data , token ( ) ) end


Input: Get the endpoint list [CODESPLIT] def get_endpoints ( token = nil ) if token . nil? return get_request ( address ( "/endpoints" ) , token ( ) ) else return get_request ( address ( "/tokens/#{token}/endpoints" ) , token ( ) ) end end


Input: Disables an instance method . [CODESPLIT] def disable_method ( method_name , message = nil ) disabled_methods [ method_name ] ||= DisabledMethod . new ( self , method_name , message ) disabled_methods [ method_name ] . disable! end


Input: Returns a Proc that acts as a replacement for the disabled method . [CODESPLIT] def to_proc disabled_method = self # This proc will be evaluated with "self" set to the original object. Proc . new do | * args , & block | disabled_method . execute ( self , args , block ) end end


Input: The replacement for the original method . It will raise a NoMethodError if the method is disabled . Otherwise it will execute the original method . [CODESPLIT] def execute ( object , * args , & block ) if disabled? raise NoMethodError , message else object . send ( aliased_name , args , block ) end end


Input: Replaces the original implementation of the method with an implementation that allows disabling . [CODESPLIT] def alias_method! klass . send ( :define_method , replacement_name , self ) klass . send ( :alias_method , aliased_name , method_name ) klass . send ( :alias_method , method_name , replacement_name ) end


Input: calculate public key from secret [CODESPLIT] def secret_to_public ( secret , form = :byte ) publickey = p_secret_to_public ( change_argument_format ( secret , form ) ) return change_result_format ( publickey , form ) end


Input: convert int to byte - string ( littleEndian ) num : unsigned number to convert to bytes length : byte length [CODESPLIT] def int_to_bytes ( num , length ) raise ArgumentError , "num :" + num . to_s if num < 0 raise ArgumentError , "length :" + length . to_s if length < 0 hex_str = num . to_s ( 16 ) hex_str = hex_str . rjust ( length 2 , "0" ) return hexstr_to_bytes ( hex_str ) . reverse [ 0 , length ] end


Input: region calculate mod calculate base ** exponent % modulus [CODESPLIT] def pow_mod ( base , exponent , modulus ) raise ArgumentError if exponent < 0 || modulus < 0 # result of Nmod1 is always 0 return 0 if modulus . equal? 1 result = 1 base = base % modulus while exponent > 0 result = result base % modulus if ( exponent % 2 ) . equal? 1 exponent = exponent >> 1 base = base base % modulus end return result end


Input: region calculate point of ed25519 curve Points are represented as array [ X Y Z T ] of extended coordinates with x = X / Z y = Y / Z x * y = T / Z [CODESPLIT] def point_add ( pa , pb ) _A = ( pa [ 1 ] - pa [ 0 ] ) * ( pb [ 1 ] - pb [ 0 ] ) % @@p _B = ( pa [ 1 ] + pa [ 0 ] ) * ( pb [ 1 ] + pb [ 0 ] ) % @@p _C = 2 * pa [ 3 ] * pb [ 3 ] * @@d % @@p _D = 2 * pa [ 2 ] * pb [ 2 ] % @@p _E = _B - _A _F = _D - _C _G = _D + _C _H = _B + _A return [ _E _F , _G _H , _F _G , _E _H ] end


Input: Computes pointQ = s * pointA [CODESPLIT] def point_mul ( s , pa ) pq = [ 0 , 1 , 1 , 0 ] # Neutral element while s > 0 do pq = point_add ( pq , pa ) unless ( s & 1 ) . equal? 0 pa = point_add ( pa , pa ) s >>= 1 end return pq end


Input: return point A == point B [CODESPLIT] def point_equal ( pa , pb ) # x1 / z1 == x2 / z2  <==>  x1 * z2 == x2 * z1 return false if ( pa [ 0 ] * pb [ 2 ] - pb [ 0 ] * pa [ 2 ] ) % @@p != 0 return false if ( pa [ 1 ] * pb [ 2 ] - pb [ 1 ] * pa [ 2 ] ) % @@p != 0 return true end


Input: region point manipulation Compute corresponding x - coordinate with low bit corresponding to sign or return nil on failure [CODESPLIT] def recover_x ( y , sign ) return nil if y >= @@p # x2 means x^2 x2 = ( y y - 1 ) * modp_inv ( @@d y y + 1 ) # when x2==0 and sign!=0, these combination of arguments is illegal if x2 . equal? 0 then unless sign . equal? 0 then return nil else return 0 end end # Compute square root of x2 x = pow_mod ( x2 , ( ( @@p + 3 ) / 8 ) , @@p ) x = x * @@modp_sqrt_m1 % @@p unless ( ( x x - x2 ) % @@p ) . equal? 0 return nil unless ( ( x x - x2 ) % @@p ) . equal? 0 x = @@p - x unless ( x & 1 ) . equal? sign return x end


Input: compress element [ point ] of ed25519 curve [CODESPLIT] def point_compress ( p ) zinv = modp_inv ( p [ 2 ] ) x = p [ 0 ] * zinv % @@p y = p [ 1 ] * zinv % @@p # OR can be used to set the least significant bit of x to the most significant bit of y # because the most significant bit of "y" is always zero c = y | ( ( x & 1 ) << 255 ) return int_to_bytes ( y | ( ( x & 1 ) << 255 ) , 32 ) end


Input: decompress point that is compressed into 32bytes [CODESPLIT] def point_decompress ( s ) # check argument raise ArgumentError , "Invalid input length for decompression" unless s . length . equal? 32 y = int_form_bytes ( s ) sign = y >> 255 y &= ( 1 << 255 ) - 1 x = recover_x ( y , sign ) if x . nil? then return nil else return [ x , y , 1 , x y % @@p ] end end


Input: region key manipulation hash512 ( secret ) = > HASH ( 512bit ) = > [ LH ( 256bit ) ] / [ RH ( 256bit ) ] = > LH - > ( set some bits ) - > a return ( a RH ) [CODESPLIT] def secret_expand ( secret ) raise "Bad size of private key" unless secret . length . equal? 32 h = hash512 ( secret ) a = int_form_bytes ( h [ 0 , 32 ] ) a &= ( 1 << 254 ) - 8 a |= ( 1 << 254 ) return [ a , h [ 32 , 32 ] ] end


Input: region sign and verify [ signature format ] | compressed data of _R | s | < - concatnate [CODESPLIT] def p_sign ( secret , message ) a , prefix = secret_expand ( secret ) _A = point_compress ( point_mul ( a , @@G ) ) r = hash512_modq ( prefix + message ) _R = point_mul ( r , @@G ) _Rs = point_compress ( _R ) h = hash512_modq ( _Rs + _A + message ) s = ( r + h * a ) % @@q return _Rs + int_to_bytes ( s , 32 ) end


Input: public_keyKey = aG a is generated form a secret [CODESPLIT] def p_secret_to_public ( secret ) expanded = secret_expand ( secret ) a = expanded . first return point_compress ( point_mul ( a , @@G ) ) end


Input: get part by its name param [CODESPLIT] def part ( name ) parts . select { | p | p . name . downcase == name . to_s . downcase } . first end