idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
14,000
def multi_eq ( * values ) values = values . first if values . first . is_a? ( Array ) && values . size == 1 raise ArgumentError . new ( "Must be called with at least 2 parameters; was: #{values.inspect}" ) if values . size < 2 values [ 1 .. - 1 ] . all? { | value | value == values . first } end
Returns whether or not all passed values are equal
14,001
def exists? ( pos = nil ) machines = pos . nil? ? list : get ( pos ) ! machines . nil? end
Returns true if any machine metadata exists for this group
14,002
def running? ( pos = nil ) group = pos . nil? ? list : [ get ( pos ) ] . compact return false if group . nil? || group . empty? group . collect! { | m | m . instance_running? } ! group . member? ( false ) end
Returns true if all machines in the group are running instances
14,003
def create_auth_message ( remote_pubkey , ephemeral_privkey = nil , nonce = nil ) raise RLPxSessionError , 'must be initiator' unless initiator? raise InvalidKeyError , 'invalid remote pubkey' unless Crypto :: ECCx . valid_key? ( remote_pubkey ) @remote_pubkey = remote_pubkey token = @ecc . get_ecdh_key remote_pubkey f...
Handshake Auth Message Handling
14,004
def create_auth_ack_message ( ephemeral_pubkey = nil , nonce = nil , version = SUPPORTED_RLPX_VERSION , eip8 = false ) raise RLPxSessionError , 'must not be initiator' if initiator? ephemeral_pubkey = ephemeral_pubkey || @ephemeral_ecc . raw_pubkey @responder_nonce = nonce || Crypto . keccak256 ( Utils . int_to_big_end...
Handshake ack message handling
14,005
def setup_cipher raise RLPxSessionError , 'missing responder nonce' unless @responder_nonce raise RLPxSessionError , 'missing initiator_nonce' unless @initiator_nonce raise RLPxSessionError , 'missing auth_init' unless @auth_init raise RLPxSessionError , 'missing auth_ack' unless @auth_ack raise RLPxSessionError , 'mis...
Handshake Key Derivation
14,006
def decode_auth_plain ( ciphertext ) message = begin @ecc . ecies_decrypt ciphertext [ 0 , 307 ] rescue raise AuthenticationError , $! end raise RLPxSessionError , 'invalid message length' unless message . size == 194 sig = message [ 0 , 65 ] pubkey = message [ 65 + 32 , 64 ] raise InvalidKeyError , 'invalid initiator ...
decode legacy pre - EIP - 8 auth message format
14,007
def decode_auth_eip8 ( ciphertext ) size = ciphertext [ 0 , 2 ] . unpack ( 'S>' ) . first + 2 raise RLPxSessionError , 'invalid ciphertext size' unless ciphertext . size >= size message = begin @ecc . ecies_decrypt ciphertext [ 2 ... size ] , ciphertext [ 0 , 2 ] rescue raise AuthenticationError , $! end values = RLP ....
decode EIP - 8 auth message format
14,008
def decode_ack_plain ( ciphertext ) message = begin @ecc . ecies_decrypt ciphertext [ 0 , 210 ] rescue raise AuthenticationError , $! end raise RLPxSessionError , 'invalid message length' unless message . size == 64 + 32 + 1 ephemeral_pubkey = message [ 0 , 64 ] nonce = message [ 64 , 32 ] known = message [ - 1 ] . ord...
decode legacy pre - EIP - 8 ack message format
14,009
def decode_ack_eip8 ( ciphertext ) size = ciphertext [ 0 , 2 ] . unpack ( 'S>' ) . first + 2 raise RLPxSessionError , 'invalid ciphertext length' unless ciphertext . size == size message = begin @ecc . ecies_decrypt ( ciphertext [ 2 ... size ] , ciphertext [ 0 , 2 ] ) rescue raise AuthenticationError , $! end values = ...
decode EIP - 8 ack message format
14,010
def apply_system_defaults if @region . nil? && @zone . nil? @region , @zone = Rudy :: DEFAULT_REGION , Rudy :: DEFAULT_ZONE elsif @region . nil? @region = @zone . to_s . gsub ( / / , '' ) . to_sym elsif @zone . nil? @zone = "#{@region}b" . to_sym end @environment ||= Rudy :: DEFAULT_ENVIRONMENT @role ||= Rudy :: DEFAUL...
Apply defaults for parameters that must have values
14,011
def clear_system_defaults @region = nil if @region == Rudy :: DEFAULT_REGION @zone = nil if @zone == Rudy :: DEFAULT_ZONE @environment = nil if @environment == Rudy :: DEFAULT_ENVIRONMENT @role = nil if @role == Rudy :: DEFAULT_ROLE @localhost = nil if @localhost == ( Rudy . sysinfo . hostname || 'localhost' ) @auto = ...
Unapply defaults for parameters that must have values . This is important when reloading configuration since we don t overwrite existing values . If the default ones remained the configuration would not be applied .
14,012
def print_command ( user , host , cmd ) cmd ||= "" cmd , user = cmd . to_s , user . to_s prompt = user == "root" ? "#" : "$" li ( "%s@%s%s %s" % [ user , host , prompt , cmd . bright ] ) end
Returns a formatted string for printing command info
14,013
def parse ( artifacts : , queries : ) raise ArgumentError , 'Error: Must have artifacts' if artifacts . nil? raise ArgumentError , 'Error: Must have queries' unless queries . is_a? ( Array ) results = ResultSet . new artifacts . body . each do | artifact | url = artifact [ 'url' ] if url . nil? STDERR . puts "Warning: ...
Internal method for extracting results
14,014
def get ( permalink , kclass_name , relationship_name = nil ) case kclass_name when 'Person' person ( permalink , relationship_name ) when 'Organization' organization ( permalink , relationship_name ) end end
Get information by permalink with optional one relationship
14,015
def scrapify ( options = { } ) uri , meta = find_uri ( options [ :which ] ) , { } return meta if uri . nil? if ! ( uri =~ sf_regex ( :image ) ) meta = sf_eval_uri ( uri , options [ :images ] ) elsif ! sf_check_img_ext ( uri , options [ :images ] ) . empty? [ :title , :description , :uri , :images ] . each { | k | meta ...
Get metadata from an URI using the screen scraping technique .
14,016
def find_uri ( which = 0 ) which = scan ( sf_regex ( :uri ) ) [ which . to_i ] [ 0 ] which =~ sf_regex ( :protocol ) ? which : "http://#{which}" rescue NoMethodError nil end
Find URIs in the String .
14,017
def previewed_host_param host_param = @host_param . dup enable_mode = @enable_mode @enable_mode = false host_param [ :username ] = embed_user_name host_param [ :password ] = embed_password host_param [ :ipaddr ] = embed_ipaddr @enable_mode = true host_param [ :enable ] = embed_password @enable_mode = enable_mode host_p...
Setup parameters for a host to preview
14,018
def reset self . repetitions = 0 self . interval = 0 self . due = Date . today self . studied_at = Date . today save end
Bad recall quality start over
14,019
def output ( filename , options = { } ) options = options . dup overwrite = options . delete :overwrite case overwrite when true , nil when false raise FileExistsError , filename if File . exist? ( filename ) when :ignore if File . exist? ( filename ) trace "Ignoring transcode to #{filename.inspect} because it already ...
Performs a conversion . This method immediately begins the transcoding process ; set all other options first .
14,020
def preset_list result = run ( '--preset-list' ) result . output . scan ( %r{ \< \n \> }m ) . inject ( { } ) { | h1 , ( cat , block ) | h1 [ cat . strip ] = block . scan ( / \+ \n / ) . inject ( { } ) { | h2 , ( name , args ) | h2 [ name . strip ] = args . strip h2 } h1 } end
Returns a structure describing the presets that the current HandBrake install knows about . The structure is a two - level hash . The keys in the first level are the preset categories . The keys in the second level are the preset names and the values are string representations of the arguments for that preset .
14,021
def method_missing ( name , * args ) copy = self . dup copy . instance_eval { @args << [ name , * ( args . collect { | a | a . to_s } ) ] } copy end
Copies this CLI instance and appends another command line switch plus optional arguments .
14,022
def retry_until_true_or_timeout ( sleep_interval , timeout_secs , output_stream = $stdout , predicate = nil ) test_preconditions = -> do if sleep_interval . respond_to? ( :call ) raise ArgumentError . new ( 'Sorry, method signature has changed to: ' '(sleep_interval, timeout_secs, output_stream = $stdout, predicate = n...
Calls a predicate proc repeatedly sleeping the specified interval between calls returning if the predicate returns true and giving up after the specified number of seconds . Displays elapsed and remaining times on the terminal . Outputs the time elapsed and the time to go .
14,023
def benchmark ( caption , out_stream = $stdout , & block ) return_value = nil bm = Benchmark . measure { return_value = block . call } out_stream << bm . to_s . chomp << ": #{caption}\n" return_value end
Executes the passed block with the Ruby Benchmark standard library . Prints the benchmark string to the specified output stream . Returns the passed block s return value .
14,024
def try_with_timeout ( max_seconds , check_interval_in_secs , & block ) raise "Must pass block to this method" unless block_given? end_time = Time . now + max_seconds block_return_value = nil thread = Thread . new { block_return_value = block . call } while Time . now < end_time unless thread . alive? return [ true , b...
Runs the passed block in a new thread ensuring that its execution time does not exceed the specified duration .
14,025
def create ( proto , * args ) options = args . last . is_a? ( Hash ) ? args . pop : { } raise ArgumentError , "proto #{proto} must be protocol" unless proto . is_a? ( Protocol ) raise ArgumentError , "command structure mismatch" if ! options . empty? && structure . instance_of? ( RLP :: Sedes :: CountableList ) options...
optionally implement create
14,026
def receive ( proto , data ) if structure . instance_of? ( RLP :: Sedes :: CountableList ) receive_callbacks . each { | cb | cb . call ( proto , data ) } else receive_callbacks . each { | cb | cb . call ( proto , ** data ) } end end
optionally implement receive
14,027
def write_pair ( field , value ) key = ( field . tag << 3 ) | field . wire_type stream << :: Protobuf :: Field :: VarintField . encode ( key ) stream << field . encode ( value ) end
Encode key and value and write to + stream + .
14,028
def get ( path ) tmp = Rudy :: Backup . new path backups = Rudy :: Backups . list :path => path return nil unless backups . is_a? ( Array ) && ! backups . empty? backups . first end
Returns the most recent backup object for the given path
14,029
def pop_frames protocols = @queues . keys idx = protocols . index next_protocol protocols = protocols [ idx .. - 1 ] + protocols [ 0 , idx ] protocols . each do | id | frames = pop_frames_for_protocol id return frames unless frames . empty? end [ ] end
Returns the frames for the next protocol up to protocol window size bytes .
14,030
def array_diff ( array1 , array2 , format = :text ) string1 = array1 . join ( "\n" ) + "\n" string2 = array2 . join ( "\n" ) + "\n" Diffy :: Diff . new ( string1 , string2 ) . to_s ( format ) end
Shows a visual diff of 2 arrays by comparing the string representations of the arrays with one element per line .
14,031
def encrypt ( data , raw_pubkey ) raise ArgumentError , "invalid pubkey of length #{raw_pubkey.size}" unless raw_pubkey . size == 64 Crypto :: ECIES . encrypt data , raw_pubkey end
Encrypt data with ECIES method using the public key of the recipient .
14,032
def sf_eval_uri ( uri , exts = [ ] ) doc = Nokogiri :: HTML ( open ( uri ) . read ) doc . encoding , meta = 'utf-8' , { uri : uri } [ :title , :description , :keywords , :lang , :encode , :reply_to , :author ] . each do | k | node = doc . xpath ( sf_xpaths [ k ] ) [ 0 ] meta [ k ] = node . nil? ? '-' : node . text end ...
Evaluate the URI s HTML document and get its metadata .
14,033
def sf_check_img_ext ( images , allowed = [ ] ) allowed ||= [ ] if images . is_a? ( String ) images = images . split elsif ! images . is_a? ( Array ) images = [ ] end images . select { | i | i =~ sf_regex ( :image , allowed ) } end
Filter images returning those with the allowed extentions .
14,034
def sf_regex ( type , * args ) type = type . to_sym unless type . is_a? Symbol type == :image && sf_img_regex ( args . flatten ) || sf_uri_regex [ type ] end
Select regexes for URIs protocols and image extensions .
14,035
def sf_xpaths { title : XPath :: TITLE , description : XPath :: DESC , keywords : XPath :: KEYWORDS , lang : XPath :: LANG , encode : XPath :: ENCODE , reply_to : XPath :: REPLY_TO , author : XPath :: AUTHOR , image : XPath :: IMG } end
Organize XPaths .
14,036
def sf_fix_imgs ( imgs , uri , exts = [ ] ) sf_check_img_ext ( imgs . map do | img | img = img . to_s unless img =~ sf_regex ( :protocol ) img = sf_fix_protocol ( img , sf_domain ( uri ) ) end img if img =~ sf_regex ( :image ) end . compact , exts ) end
Check and return only the valid image URIs .
14,037
def known_machine_group? raise NoConfig unless @@config return true if default_machine_group? raise NoMachinesConfig unless @@config . machines return false if ! @@config && ! @@global zon , env , rol = @@global . zone , @@global . environment , @@global . role conf = @@config . machines . find_deferred ( @@global . re...
Looks for ENV - ROLE configuration in machines . There must be at least one definition in the config for this to return true That s how Rudy knows the current group is defined .
14,038
def fetch_routine_config ( action ) raise "No action specified" unless action raise NoConfig unless @@config raise NoRoutinesConfig unless @@config . routines raise NoGlobal unless @@global action = action . to_s . tr ( '-:' , '_' ) zon , env , rol = @@global . zone , @@global . environment , @@global . role disk_defs ...
We grab the appropriate routines config and check the paths against those defined for the matching machine group . Disks that appear in a routine but not in a machine will be removed and a warning printed . Otherwise the routines config is merged on top of the machine config and that s what we return .
14,039
def default_machine_group? default_env = @@config . defaults . environment || Rudy :: DEFAULT_ENVIRONMENT default_rol = @@config . defaults . role || Rudy :: DEFAULT_ROLE @@global . environment == default_env && @@global . role == default_rol end
Returns true if this is the default machine environment and role
14,040
def check_embed_envvar ( param ) return unless param =~ / \s \[ \' \" \' \" \] \s / envvar_name = Regexp . last_match ( 1 ) if ! ENV . key? ( envvar_name ) @logger . error "Variable name: #{envvar_name} is not found in ENV" elsif ENV [ envvar_name ] =~ / \s / @logger . warn "Env var: #{envvar_name} exists, but null str...
Error checking of environment variable to embed
14,041
def embed_var ( param ) check_embed_envvar ( param ) erb = ERB . new ( param ) erb . result ( binding ) end
Embedding environment variable to parameter
14,042
def fill_pool threads = [ ] if ( @open ) @lock . synchronize do required = min - size if ( required > 0 ) required . times do thread = ActionPool :: Thread . new ( :pool => self , :respond_thread => @respond_to , :a_timeout => @action_timeout , :t_timeout => @thread_timeout , :logger => @logger , :autostart => false ) ...
Fills the pool with the minimum number of threads Returns array of created threads
14,043
def flush mon = Splib :: Monitor . new @threads . size . times { queue { mon . wait } } @queue . wait_empty sleep ( 0.01 ) mon . broadcast end
Flush the thread pool . Mainly used for forcibly resizing the pool if existing threads have a long thread life waiting for input .
14,044
def resize @logger . info ( "Pool is being resized to stated maximum: #{max}" ) until ( size <= max ) do t = nil t = @threads . find { | x | x . waiting? } t = @threads . shift unless t t . stop end flush nil end
Resize the pool
14,045
def open_interactive_process ( spawn_cmd ) @logger . info "Begin spawn: #{spawn_cmd}" PTY . spawn ( spawn_cmd ) do | reader , writer , _pid | @enable_mode = false @reader = reader @writer = writer @writer . sync = true yield end end
Spawn interactive process
14,046
def do_on_interactive_process until @reader . closed? || @reader . eof? @reader . expect ( expect_regexp , @timeout ) do | match | yield match end end rescue Errno :: EIO => error @logger . debug "PTY raises Errno::EIO, #{error.message}" end
Search prompt and send command while process is opened
14,047
def imgcheck ( imgurl , options = { } ) params = { :method => WebPurify :: Constants . methods [ :imgcheck ] , :imgurl => imgurl } parsed = WebPurify :: Request . query ( image_request_base , @query_base , params . merge ( options ) ) return parsed [ :imgid ] end
Check for existence of prohibited image content
14,048
def imgstatus ( imgid , options = { } ) params = { :method => WebPurify :: Constants . methods [ :imgstatus ] , :imgid => imgid } parsed = WebPurify :: Request . query ( image_request_base , @query_base , params . merge ( options ) ) return parsed [ :status ] end
Return status of image moderation
14,049
def imgaccount params = { :method => WebPurify :: Constants . methods [ :imgaccount ] } parsed = WebPurify :: Request . query ( image_request_base , @query_base , params ) return parsed [ :remaining ] . to_i end
Return number of image submissions remaining on license
14,050
def sxor ( s1 , s2 ) raise ArgumentError , "strings must have equal size" unless s1 . size == s2 . size s1 . bytes . zip ( s2 . bytes ) . map { | a , b | ( a ^ b ) . chr } . join end
String xor .
14,051
def colorize ( options ) if options . class == Array options . each do | opt | Capistrano :: Logger . add_color_matcher ( opt ) end else Capistrano :: Logger . add_color_matcher ( options ) end end
Add custom colormatchers
14,052
def start * args return self if attached? or running? @pid = :: Process . spawn Nutcracker . executable , * command Process . detach ( @pid ) sleep 2 raise "Nutcracker failed to start" unless running? Kernel . at_exit { kill if running? } self end
Initialize a new Nutcracker process wrappper
14,053
def use plugin , * args Nutcracker . const_get ( plugin . to_s . capitalize ) . start ( self , * args ) end
Syntactic sugar for initialize plugins
14,054
def overview data = { :clusters => [ ] , :config => config } stats . each do | cluster_name , cluster_data | unless cluster_data . is_a? Hash data [ cluster_name ] = cluster_data next end aliases = node_aliases cluster_name cluster = { nodes : [ ] , name : cluster_name } cluster_data . each do | node , node_value | if ...
Returns hash with server and node statistics See example . json
14,055
def redis_info url , password begin r = Redis . new url : url , password : password info = r . info . merge 'dbsize' => r . dbsize rescue Exception => e STDERR . puts "[ERROR][#{__FILE__}:#{__LINE__}] Failed to get data from Redis - " + "#{url.inspect} (using password #{password.inspect}): #{e.message}\n#{e.backtrace.j...
Returns hash with information about a given Redis
14,056
def check ( text , options = { } ) params = { :method => WebPurify :: Constants . methods [ :check ] , :text => text } parsed = WebPurify :: Request . query ( text_request_base , @query_base , params . merge ( options ) ) return parsed [ :found ] == '1' end
Check for existence of profanity
14,057
def check_count ( text , options = { } ) params = { :method => WebPurify :: Constants . methods [ :check_count ] , :text => text } parsed = WebPurify :: Request . query ( text_request_base , @query_base , params . merge ( options ) ) return parsed [ :found ] . to_i end
Check for existence of profanity and return number of profane words found
14,058
def replace ( text , symbol , options = { } ) params = { :method => WebPurify :: Constants . methods [ :replace ] , :text => text , :replacesymbol => symbol } parsed = WebPurify :: Request . query ( text_request_base , @query_base , params . merge ( options ) ) return parsed [ :text ] end
Replace any matched profanity with provided symbol
14,059
def return ( text , options = { } ) params = { :method => WebPurify :: Constants . methods [ :return ] , :text => text } parsed = WebPurify :: Request . query ( text_request_base , @query_base , params . merge ( options ) ) if parsed [ :expletive ] . is_a? ( String ) return [ ] << parsed [ :expletive ] else return pars...
Return an array of matched profanity
14,060
def to_s ( with_title = false ) lines = [ liner_note ] ( self . addresses || { } ) . each_pair do | address , rules | lines << "%18s -> %s" % [ address . to_s , rules . collect { | p | p . to_s } . join ( ', ' ) ] end lines . join ( $/ ) end
Print info about a security group
14,061
def start_thread begin @logger . info ( "New pool thread is starting (#{self})" ) until ( @kill ) do begin @action = nil if ( @pool . size > @pool . min && ! @thread_timeout . zero? ) Timeout :: timeout ( @thread_timeout ) do @action = @pool . action end else @action = @pool . action end run ( @action [ 0 ] , @action [...
Start our thread
14,062
def parse_timestamps super @next_capture_at = Time . at ( next_capture_at ) if next_capture_at @canceled_at = Time . at ( canceled_at ) if canceled_at @trial_start = Time . at ( trial_start ) if trial_start @trial_end = Time . at ( trial_end ) if trial_end end
Parses UNIX timestamps and creates Time objects
14,063
def challenge_record_valid? ( domain , key ) record = challenge_record ( domain ) return record && record . data == key end
Checks if the TXT record for a domain is valid .
14,064
def splash_composite max = size . min / 9 assets . each do | over | other = MiniMagick :: Image . open ( File . join ( src , over ) ) other . resize ( max ) if other . dimensions . max >= max self . img = compose ( other , over ) end end
Composite 9 gravity
14,065
def image ( out = nil ) splash_start splash_composite return img unless out FileUtils . mkdir_p File . dirname ( out ) img . write ( out ) rescue Errno :: ENOENT YAMG . puts_and_exit ( "Path not found '#{out}'" ) end
Outputs instance or writes image to disk
14,066
def manage_process name = nil name = @managed_process if name . nil? if name then begin Collins . const_get ( name ) . new ( self ) . run rescue Exception => e raise CollinsError . new ( e . message ) end else raise CollinsError . new ( "No managed process specified" ) end end
Create a collins client instance
14,067
def []= ( key , value ) if columns . key? ( key ) @array [ columns . index ( key ) ] = value else @array << value columns << key end hash [ key ] = value end
Set cell value . Adds cell to end of Row and adds new Column if there is no Column for + key_
14,068
def create_dictionary_representation dict = { storyboards : [ ] , table_cells : [ ] , collection_cells : [ ] , view_controllers : [ ] , segues : [ ] , prefix : @config . prefix } @project . resources . each do | group | dict [ :storyboards ] << group . storyboard dict [ :table_cells ] += group . table_cells dict [ :col...
Converts the resources into a Mustache - compatible template dictionary .
14,069
def work ( path ) out = "#{path}/#{@name}.png" @fetcher . fetch ( output : out , width : @size [ 0 ] , height : @size [ 1 ] , dpi : @dpi ) rescue Screencap :: Error puts "Fail to capture screenshot #{@url}" end
Take the screenshot Do we need pixel depth??
14,070
def << ( key ) column = Column . new ( @table , self , key ) return if is_blank? ( column . key ) || key? ( key ) @column_indexes [ column . key ] = @columns . size @column_indexes [ @columns . size ] = column @columns_by_key [ column . key ] = column @columns << column end
Add a new Column with + key +
14,071
def add_elm_dependencies ( filepath , context ) dirname = context . pathname . to_s . gsub Regexp . new ( context . logical_path + ".+$" ) , "" File . read ( filepath ) . each_line do | line | match = line . match ( / \s \s / ) next unless match module_name = match . captures [ 0 ] dependency_logical_name = module_name...
Add all Elm modules imported in the target file as dependencies then recursively do the same for each of those dependent modules .
14,072
def trace ( progname = nil , & block ) if logger . respond_to? ( :trace ) then logger . trace ( progname , & block ) else logger . debug ( progname , & block ) end end
Provides a safe wrapper for our monkeypatched logger
14,073
def surl ( service ) service_url = @env == :stable ? API_URL : SANDBOX_API_URL service_url = service_url + "/" + service service_url . gsub! ( 'www' , 'usercontent' ) if service . to_s == 'image' service_url end
Return the URL of a Freebase service
14,074
def get ( url , params = { } , options = { } ) FreebaseAPI . logger . debug ( "GET #{url}" ) params [ :key ] = @key if @key options = { format : options [ :format ] , query : params } options . merge! ( @proxy_options ) response = self . class . get ( url , options ) handle_response ( response ) end
Make a GET request
14,075
def handle_response ( response ) case response . code when 200 .. 299 response else if response . request . format == :json raise FreebaseAPI :: ServiceError . new ( response [ 'error' ] ) else raise FreebaseAPI :: NetError . new ( 'code' => response . code , 'message' => response . response . message ) end end end
Handle the response
14,076
def get_proxy_options ( url = nil ) options = { } if url = url || ENV [ 'HTTPS_PROXY' ] || ENV [ 'https_proxy' ] || ENV [ 'HTTP_PROXY' ] || ENV [ 'http_proxy' ] proxy_uri = URI . parse ( url ) options [ :http_proxyaddr ] = proxy_uri . host options [ :http_proxyport ] = proxy_uri . port options [ :http_proxyuser ] = pro...
Get the proxy options for HTTParty
14,077
def precision @precision ||= cells . map ( & :to_f ) . map { | n | n . round ( 3 ) } . map { | n | n . to_s . split ( "." ) . last . gsub ( / / , "" ) . length } . max end
Number of zeros to the right of the decimal point . Useful for formtting time data .
14,078
def apply_patch ( operations , node ) i = 0 operations . sort_by { | operation | i += 1 ; [ - operation . priority , i ] } . each do | operation | case operation when :: Markdiff :: Operations :: AddChildOperation operation . target_node . add_child ( operation . inserted_node ) mark_li_or_tr_as_changed ( operation . t...
Apply a given patch to a given node
14,079
def create_patch ( before_node , after_node ) if before_node . to_html == after_node . to_html [ ] else create_patch_from_children ( before_node , after_node ) end end
Creates a patch from given two nodes
14,080
def render ( before_string , after_string ) before_node = :: Nokogiri :: HTML . fragment ( before_string ) after_node = :: Nokogiri :: HTML . fragment ( after_string ) patch = create_patch ( before_node , after_node ) apply_patch ( patch , before_node ) end
Utility method to do both creating and applying a patch
14,081
def create_patch_from_children ( before_node , after_node ) operations = [ ] identity_map = { } inverted_identity_map = { } :: Diff :: LCS . sdiff ( before_node . children . map ( & :to_s ) , after_node . children . map ( & :to_s ) ) . each do | element | type , before , after = * element if type == "=" before_child = ...
1 . Create identity map and collect patches from descendants 1 - 1 . Detect exact - matched nodes 1 - 2 . Detect partial - matched nodes and recursively walk through its children 2 . Create remove operations from identity map 3 . Create insert operations from identity map 4 . Return operations as a patch
14,082
def delete_blank_columns! ( * options ) exceptions = extract_exceptions ( options ) ( columns . map ( & :key ) - exceptions ) . each do | key | if rows . all? { | row | is_blank? ( row [ key ] ) || is_zero? ( row [ key ] ) } delete_column key end end end
Remove all columns that only contain a blank string zero or nil
14,083
def delete_homogenous_columns! ( * options ) return if rows . size < 2 exceptions = extract_exceptions ( options ) ( columns . map ( & :key ) - exceptions ) . each do | key | value = rows . first [ key ] delete_column key if rows . all? { | row | row [ key ] == value } end end
Remove all columns that contain the same value in all rows
14,084
def strip! rows . each do | row | columns . each do | column | value = row [ column . key ] if value . respond_to? ( :strip ) row [ column . key ] = value . strip elsif value . is_a? ( Float ) row [ column . key ] = strip_decimal ( value ) end end end end
Remove preceding and trailing whitespace from all cells . By default Table does not strip whitespace from cells .
14,085
def gateway_address pool = "default" address = addresses . select { | a | a . pool == pool } . map { | a | a . gateway } . first return address if address if addresses . length > 0 then addresses . first . gateway else nil end end
Return the gateway address for the specified pool or the first gateway
14,086
def deep_copy_hash hash require_that ( hash . is_a? ( Hash ) , "deep_copy_hash requires a hash be specified, got #{hash.class}" ) Marshal . load Marshal . dump ( hash ) end
Create a deep copy of a hash
14,087
def require_non_empty value , message , return_value = false guard_value = if return_value == true then value elsif return_value != false then return_value else false end if value . is_a? ( String ) then require_that ( ! value . strip . empty? , message , guard_value ) elsif value . respond_to? ( :empty? ) then require...
Require that a value not be empty
14,088
def require_that guard , message , return_guard = false if not guard then raise ExpectationFailedError . new ( message ) end if return_guard == true then guard elsif return_guard != false then return_guard end end
Require that a guard condition passes
14,089
def get_asset_or_tag asset_or_tag asset = case asset_or_tag when Collins :: Asset then asset_or_tag when String then Collins :: Asset . new ( asset_or_tag ) when Symbol then Collins :: Asset . new ( asset_or_tag . to_s ) else error_message = "Expected Collins::Asset, String or Symbol. Got #{asset_or_tag.class}" raise E...
Resolve an asset from a string tag or collins asset
14,090
def symbolize_hash hash , options = { } return { } if ( hash . nil? or hash . empty? ) ( raise ExpectationFailedError . new ( "symbolize_hash called without a hash" ) ) unless hash . is_a? ( Hash ) hash . inject ( { } ) do | result , ( k , v ) | key = options [ :downcase ] ? k . to_s . downcase . to_sym : k . to_s . to...
Given a hash rewrite keys to symbols
14,091
def stringify_hash hash , options = { } ( raise ExpectationFailedError . new ( "stringify_hash called without a hash" ) ) unless hash . is_a? ( Hash ) hash . inject ( { } ) do | result , ( k , v ) | key = options [ :downcase ] ? k . to_s . downcase : k . to_s if v . is_a? ( Hash ) then result [ key ] = stringify_hash (...
Given a hash convert all keys to strings
14,092
def parse str chars = str . split ( / / ) nodes = Nodes . new ( chars . length + 2 , @mat ) nodes . add ( 0 , Node . mk_bos_eos ) nodes . add ( chars . length + 1 , Node . mk_bos_eos ) str . length . times { | i | @dic . possible_words ( str , i ) . each { | w | nodes . add ( i + 1 , Node . new ( w ) ) } } nodes end
- > Nodes
14,093
def define type_name , left , right , cost type = @char_types . named type_name ( @templates [ type_name ] ||= [ ] ) . push Word . new '' , left , right , cost end
String - > Feature - > Feature - > Integer - >
14,094
def key_to_sym ( key ) case key when Column key . key when String key . to_sym else key end end
Return Symbol for + key + . Translate Column and String . Return + key + unmodified for anything else .
14,095
def authorize_for_domain ( domain , options = { } ) authorization = client . authorize ( domain : domain ) if options [ :challenge ] == :dns challenge = authorization . dns01 unless options [ :skip_puts ] puts "====================================================================" puts "Record:" puts puts " - Name: #{ch...
Authorize the client for a domain name .
14,096
def method_missing meth , * args , & block if @client . respond_to? ( meth ) then method_parameters = @client . class . instance_method ( meth ) . parameters asset_idx = method_parameters . find_index do | item | item [ 1 ] == :asset_or_tag end if asset_idx . nil? then @client . send ( meth , * args , & block ) else ar...
Fill in the missing asset parameter on the dynamic method if needed
14,097
def get ( url , query_params = nil ) JSON . parse ( perform ( 'get' , url , query : query_params ) , symbolize_names : true , quirks_mode : true ) end
Initializes the client with the supplied Connection
14,098
def or_else * default if empty? then res = if block_given? then yield else default . first end if res . is_a? ( Option ) then res else :: Collins :: Option ( res ) end else self end end
Return this Option if non - empty otherwise return the result of evaluating the default
14,099
def map & block if empty? then None . new else Some . new ( block . call ( get ) ) end end
If the option value is defined apply the specified block to that value