idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
9,000
def lookup ( item ) items = item if item . is_a? String items = [ item ] end results = [ ] items . each do | item | sent = 0 @starttime = Time . now . to_f itemtype = ( item =~ / \d \. \d \. \d \. \d / ) ? 'ip' : 'domain' @dnsbls . each do | name , config | next if config [ 'disabled' ] next unless config [ 'type' ] ==...
lookup performs the sending of DNS queries for the given items returns an array of DNSBLResult
9,001
def _decode_response ( buf ) reply = Resolv :: DNS :: Message . decode ( buf ) results = [ ] reply . each_answer do | name , ttl , data | if name . to_s =~ / \d \. \d \. \d \. \d \. / ip = [ $4 , $3 , $2 , $1 ] . join ( "." ) domain = $5 @dnsbls . each do | dnsblname , config | next unless data . is_a? Resolv :: DNS ::...
takes a DNS response and converts it into a DNSBLResult
9,002
def __phpot_decoder ( ip ) octets = ip . split ( / \. / ) if octets . length != 4 or octets [ 0 ] != "127" return "invalid response" elsif octets [ 3 ] == "0" search_engines = [ "undocumented" , "AltaVista" , "Ask" , "Baidu" , "Excite" , "Google" , "Looksmart" , "Lycos" , "MSN" , "Yahoo" , "Cuil" , "InfoSeek" , "Miscel...
decodes the response from Project Honey Pot s service
9,003
def FlagValues ( * params ) if params . size == 1 && params . first . kind_of? ( FlagValues ) params . first else FlagValues . new ( * params ) end end
Constructor for FlagValues
9,004
def Flags ( * params ) if params . size == 1 && params . first . kind_of? ( Flags ) params . first else Flags . new ( * params ) end end
Constructor for Flags
9,005
def integer ( x ) r = x . round ( ( x - r ) . abs <= relative_to ( x ) ) ? r : nil end
If the argument is close to an integer it rounds it
9,006
def mount ( path , opts = { } ) route , folder = path . first if path . size > 1 other_opts = path . dup other_opts . delete ( route ) opts = opts . merge ( other_opts ) end application . mount ( route , opts . merge ( { :path => folder } ) ) end
mount a folder for browsing
9,007
def size case self . body when String then self . body . length when StringIO then self . body . length when File then self . body . size else 0 end end
get the size in bytes of the response . used for logging
9,008
def run! EventMachine :: run do Signal . trap ( "INT" ) { puts "It's a trap!" EventMachine . stop } Signal . trap ( "TERM" ) { puts "It's a trap!" EventMachine . stop } EventMachine . kqueue = true if EventMachine . kqueue? EventMachine . epoll = true if EventMachine . epoll? STDERR . puts "start server at #{host} #{po...
main app loop . called via at_exit block defined in DSL
9,009
def should_reload? ! last_reload . nil? && self . scripts . any? do | f | File . mtime ( f ) > last_reload end end
check if our script has been updated since the last reload
9,010
def reload_stale reload_check = should_reload? self . last_reload = Time . now return if ! reload_check reset! self . scripts . each do | f | debug_log "reload #{f}" load f end end
reload scripts if needed
9,011
def mount ( path , opts = { } , klass = Gopher :: Handlers :: DirectoryHandler ) debug_log "MOUNT #{path} #{opts.inspect}" opts [ :mount_point ] = path handler = klass . new ( opts ) handler . application = self route ( globify ( path ) ) do handler . call ( params , request ) end end
mount a directory for browsing via gopher
9,012
def lookup ( selector ) unless routes . nil? routes . each do | pattern , keys , block | if match = pattern . match ( selector ) match = match . to_a url = match . shift params = to_params_hash ( keys , match ) @params = params return params , block end end end unless @default_route . nil? return { } , @default_route e...
lookup an incoming path
9,013
def dispatch ( req ) debug_log ( req ) response = Response . new @request = req if ! @request . valid? response . body = handle_invalid_request response . code = :error else begin debug_log ( "do lookup for #{@request.selector}" ) @params , block = lookup ( @request . selector ) response . body = block . bind ( self ) ...
find and run the first route which matches the incoming request
9,014
def find_template ( t ) x = menus [ t ] if x return x , Gopher :: Rendering :: Menu end x = text_templates [ t ] if x return x , Gopher :: Rendering :: Text end end
find a template
9,015
def render ( template , * arguments ) block , handler = find_template ( template ) raise TemplateNotFound if block . nil? ctx = handler . new ( self ) ctx . params = @params ctx . request = @request ctx . instance_exec ( * arguments , & block ) end
Find the desired template and call it within the proper context
9,016
def compile! ( path , & block ) method_name = path route_method = Application . generate_method ( method_name , & block ) pattern , keys = compile path [ pattern , keys , route_method ] end
compile a route
9,017
def init_access_log return if access_log_dest . nil? log = :: Logging . logger [ 'access_log' ] pattern = :: Logging . layouts . pattern ( :pattern => ACCESS_LOG_PATTERN ) log . add_appenders ( :: Logging . appenders . rolling_file ( access_log_dest , :level => :debug , :age => 'daily' , :layout => pattern ) ) log end
initialize a Logger for tracking hits to the server
9,018
def access_log ( request , response ) return if access_log_dest . nil? @@access_logger ||= init_access_log code = response . respond_to? ( :code ) ? response . code . to_s : "success" size = response . respond_to? ( :size ) ? response . size : response . length output = [ request . ip_address , request . selector , req...
write out an entry to our access log
9,019
def to_params_hash ( keys , values ) hash = { } keys . size . times { | i | hash [ keys [ i ] . to_sym ] = values [ i ] } hash end
zip up two arrays of keys and values from an incoming request
9,020
def call! ( request ) operation = proc { app . dispatch ( request ) } callback = proc { | result | send_response result close_connection_after_writing } if app . non_blocking? EventMachine . defer ( operation , callback ) else callback . call ( operation . call ) end end
generate a request object from an incoming selector and dispatch it to the app
9,021
def send_response ( response ) case response when Gopher :: Response then send_response ( response . body ) when String then send_data ( response + end_of_transmission ) when StringIO then send_data ( response . read + end_of_transmission ) when File while chunk = response . read ( 8192 ) do send_data ( chunk ) end res...
send the response back to the client
9,022
def perform_with_result status = perform result = case status when "200" "AppSignal has confirmed authorization!" when "401" "API key not valid with AppSignal..." else "Could not confirm authorization: " "#{status.nil? ? "nil" : status}" end [ status , result ] rescue => e result = "Something went wrong while trying to...
Perform push api validation request and return a descriptive response tuple .
9,023
def maintain_backwards_compatibility ( configuration ) configuration . tap do | config | DEPRECATED_CONFIG_KEY_MAPPING . each do | old_key , new_key | old_config_value = config . delete ( old_key ) next unless old_config_value deprecation_message "Old configuration key found. Please update the " "'#{old_key}' to '#{new...
Maintain backwards compatibility with config files generated by earlier versions of the gem
9,024
def background_queue_start env = environment return unless env queue_start = env [ :queue_start ] return unless queue_start ( queue_start . to_f * 1000.0 ) . to_i end
Returns calculated background queue start time in milliseconds based on environment values .
9,025
def http_queue_start env = environment return unless env env_var = env [ "HTTP_X_QUEUE_START" . freeze ] || env [ "HTTP_X_REQUEST_START" . freeze ] return unless env_var cleaned_value = env_var . tr ( "^0-9" . freeze , "" . freeze ) return if cleaned_value . empty? value = cleaned_value . to_i if value > 4_102_441_200_...
Returns HTTP queue start time in milliseconds .
9,026
def sanitized_environment env = environment return if env . empty? { } . tap do | out | Appsignal . config [ :request_headers ] . each do | key | out [ key ] = env [ key ] if env [ key ] end end end
Returns sanitized environment for a transaction .
9,027
def sanitized_session_data return if Appsignal . config [ :skip_session_data ] || ! request . respond_to? ( :session ) session = request . session return unless session Appsignal :: Utils :: HashSanitizer . sanitize ( session . to_hash , Appsignal . config [ :filter_session_data ] ) end
Returns sanitized session data .
9,028
def for_each_time_range ( t ) RedisAnalytics . redis_key_timestamps . map { | x , y | t . strftime ( x ) } . each do | ts | yield ( ts ) end end
This class represents one unique visit User may have never visited the site User may have visited before but his visit is expired Everything counted here is unique for a visit helpers
9,029
def record if @current_visit_seq track ( "visit_time" , @t . to_i - @last_visit_end_time . to_i ) else @current_visit_seq ||= counter ( "visits" ) track ( "visits" , 1 ) if @first_visit_seq track ( "repeat_visits" , 1 ) else @first_visit_seq ||= counter ( "unique_visits" ) track ( "first_visits" , 1 ) track ( "unique_v...
method used in analytics . rb to initialize visit called from analytics . rb
9,030
def reset @adapter = DEFAULT_ADAPTER @http_verb = DEFAULT_HTTP_VERB @faraday_options = { } @max_retries = DEFAULT_MAX_RETRIES @logger = :: Logger . new ( STDOUT ) @log_requests = DEFAULT_LOGGER_OPTIONS [ :requests ] @log_errors = DEFAULT_LOGGER_OPTIONS [ :errors ] @log_responses = DEFAULT_LOGGER_OPTIONS [ :responses ] ...
Reset all configuration options to defaults .
9,031
def call ( args = { } , & block ) response = API . call ( full_name , args , token ) Result . process ( response , type , block ) end
Calling the API method . It delegates the network request to API . call and result processing to Result . process .
9,032
def authorization_url ( options = { } ) type = options . delete ( :type ) || :site options [ :redirect_uri ] ||= VkontakteApi . redirect_uri options [ :scope ] = VkontakteApi :: Utils . flatten_argument ( options [ :scope ] ) if options [ :scope ] case type when :site client . auth_code . authorize_url ( options ) when...
URL for redirecting the user to VK where he gives the application all the requested access rights .
9,033
def add_series ( params ) unless params . has_key? ( :values ) raise "Must specify ':values' in add_series" end if @requires_category != 0 && ! params . has_key? ( :categories ) raise "Must specify ':categories' in add_series for this chart type" end @series << Series . new ( self , params ) x2_axis = params [ :x2_axis...
Add a series and it s properties to a chart .
9,034
def set_size ( params = { } ) @width = params [ :width ] if params [ :width ] @height = params [ :height ] if params [ :height ] @x_scale = params [ :x_scale ] if params [ :x_scale ] @y_scale = params [ :y_scale ] if params [ :y_scale ] @x_offset = params [ :x_offset ] if params [ :x_offset ] @y_offset = params [ :y_of...
Set dimensions for scale for the chart .
9,035
def set_up_down_bars ( params = { } ) [ :up , :down ] . each do | up_down | if params [ up_down ] params [ up_down ] [ :line ] = params [ up_down ] [ :border ] if params [ up_down ] [ :border ] else params [ up_down ] = { } end end @up_down_bars = { :_up => Chartline . new ( params [ :up ] ) , :_down => Chartline . new...
Set properties for the chart up - down bars .
9,036
def convert_font_args ( params ) return unless params font = params_to_font ( params ) font [ :_size ] *= 100 if font [ :_size ] && font [ :_size ] != 0 if ptrue? ( font [ :_rotation ] ) font [ :_rotation ] = 60_000 * font [ :_rotation ] . to_i end font end
Convert user defined font values into private hash values .
9,037
def process_names ( name = nil , name_formula = nil ) if name . respond_to? ( :to_ary ) cell = xl_rowcol_to_cell ( name [ 1 ] , name [ 2 ] , 1 , 1 ) name_formula = "#{quote_sheetname(name[0])}!#{cell}" name = '' elsif name && name =~ / \$ / name_formula = name name = '' end [ name , name_formula ] end
Switch name and name_formula parameters if required .
9,038
def get_data_type ( data ) return 'none' unless data return 'none' if data . empty? return 'multi_str' if data . first . kind_of? ( Array ) data . each do | token | next unless token return 'str' unless token . kind_of? ( Numeric ) end 'num' end
Find the overall type of the data associated with a series .
9,039
def color ( color_code ) if color_code and color_code =~ / / color_code . sub ( / / , '' ) . upcase else index = Format . color ( color_code ) raise "Unknown color '#{color_code}' used in chart formatting." unless index palette_color ( index ) end end
Convert the user specified colour index or string to a rgb colour .
9,040
def get_font_style_attributes ( font ) return [ ] unless font attributes = [ ] attributes << [ 'sz' , font [ :_size ] ] if ptrue? ( font [ :_size ] ) attributes << [ 'b' , font [ :_bold ] ] if font [ :_bold ] attributes << [ 'i' , font [ :_italic ] ] if font [ :_italic ] attributes << [ 'u' , 'sng' ] if font [ :_underl...
Get the font style attributes from a font hash .
9,041
def get_font_latin_attributes ( font ) return [ ] unless font attributes = [ ] attributes << [ 'typeface' , font [ :_name ] ] if ptrue? ( font [ :_name ] ) attributes << [ 'pitchFamily' , font [ :_pitch_family ] ] if font [ :_pitch_family ] attributes << [ 'charset' , font [ :_charset ] ] if font [ :_charset ] attribut...
Get the font latin attributes from a font hash .
9,042
def write_series_name ( series ) if series . name_formula write_tx_formula ( series . name_formula , series . name_id ) elsif series . name write_tx_value ( series . name ) end end
Write the series name .
9,043
def write_axis_font ( font ) return unless font @writer . tag_elements ( 'c:txPr' ) do write_a_body_pr ( font [ :_rotation ] ) write_a_lst_style @writer . tag_elements ( 'a:p' ) do write_a_p_pr_rich ( font ) write_a_end_para_rpr end end end
Write the axis font elements .
9,044
def write_error_bars ( error_bars ) return unless ptrue? ( error_bars ) if error_bars [ :_x_error_bars ] write_err_bars ( 'x' , error_bars [ :_x_error_bars ] ) end if error_bars [ :_y_error_bars ] write_err_bars ( 'y' , error_bars [ :_y_error_bars ] ) end end
Write the X and Y error bars .
9,045
def write_custom_error ( error_bars ) if ptrue? ( error_bars . plus_values ) write_custom_error_base ( 'c:plus' , error_bars . plus_values , error_bars . plus_data ) write_custom_error_base ( 'c:minus' , error_bars . minus_values , error_bars . minus_data ) end end
Write the custom error bars type .
9,046
def protect ( password = nil , options = { } ) check_parameter ( options , protect_default_settings . keys , 'protect' ) @protect = protect_default_settings . merge ( options ) @protect [ :password ] = sprintf ( "%X" , encode_password ( password ) ) if password && password != '' end
Set the worksheet protection flags to prevent modification of worksheet objects .
9,047
def set_header ( string = '' , margin = 0.3 , options = { } ) raise 'Header string must be less than 255 characters' if string . length >= 255 @page_setup . header = string . gsub ( / \[ \] / , '&G' ) if string . size >= 255 raise 'Header string must be less than 255 characters' end if options [ :align_with_margins ] @...
Set the page header caption and optional margin .
9,048
def set_footer ( string = '' , margin = 0.3 , options = { } ) raise 'Footer string must be less than 255 characters' if string . length >= 255 @page_setup . footer = string . dup @page_setup . footer = string . gsub ( / \[ \] / , '&G' ) if string . size >= 255 raise 'Header string must be less than 255 characters' end ...
Set the page footer caption and optional margin .
9,049
def repeat_rows ( row_min , row_max = nil ) row_max ||= row_min row_min += 1 row_max += 1 area = "$#{row_min}:$#{row_max}" sheetname = quote_sheetname ( @name ) @page_setup . repeat_rows = "#{sheetname}!#{area}" end
Set the number of rows to repeat at the top of each printed page .
9,050
def print_across ( across = true ) if across @page_setup . across = true @page_setup . page_setup_changed = true else @page_setup . across = false end end
Set the order in which pages are printed .
9,051
def filter_column ( col , expression ) raise "Must call autofilter before filter_column" unless @autofilter_area col = prepare_filter_column ( col ) tokens = extract_filter_tokens ( expression ) unless tokens . size == 3 || tokens . size == 7 raise "Incorrect number of tokens in expression '#{expression}'" end tokens =...
Set the column filter criteria .
9,052
def filter_column_list ( col , * tokens ) tokens . flatten! raise "Incorrect number of arguments to filter_column_list" if tokens . empty? raise "Must call autofilter before filter_column_list" unless @autofilter_area col = prepare_filter_column ( col ) @filter_cols [ col ] = tokens @filter_type [ col ] = 1 @filter_on ...
Set the column filter criteria in Excel 2007 list style .
9,053
def set_h_pagebreaks ( * args ) breaks = args . collect do | brk | Array ( brk ) end . flatten @page_setup . hbreaks += breaks end
Store the horizontal page breaks on a worksheet .
9,054
def get_range_data ( row_start , col_start , row_end , col_end ) data = [ ] ( row_start .. row_end ) . each do | row_num | if ! @cell_data_table [ row_num ] data << nil next end ( col_start .. col_end ) . each do | col_num | if cell = @cell_data_table [ row_num ] [ col_num ] data << cell . data else data << nil end end...
Returns a range of data from the worksheet _table to be used in chart cached data . Strings are returned as SST ids and decoded in the workbook . Return nils for data that doesn t exist since Excel can chart series with data missing .
9,055
def position_object_pixels ( col_start , row_start , x1 , y1 , width , height ) if @col_size_changed x_abs = ( 0 .. col_start - 1 ) . inject ( 0 ) { | sum , col | sum += size_col ( col ) } else x_abs = @default_col_pixels * col_start end x_abs += x1 if @row_size_changed y_abs = ( 0 .. row_start - 1 ) . inject ( 0 ) { |...
Calculate the vertices that define the position of a graphical object within the worksheet in pixels .
9,056
def prepare_vml_objects ( vml_data_id , vml_shape_id , vml_drawing_id , comment_id ) set_external_vml_links ( vml_drawing_id ) set_external_comment_links ( comment_id ) if has_comments? data = "#{vml_data_id}" ( 1 .. num_comments_block ) . each do | i | data += ",#{vml_data_id + i}" end @vml_data_id = data @vml_shape_i...
Turn the HoH that stores the comments into an array for easier handling and set the external links for comments and buttons .
9,057
def prepare_tables ( table_id ) if tables_count > 0 id = table_id tables . each do | table | table . prepare ( id ) @external_table_links << [ '/table' , "../tables/table#{id}.xml" ] id += 1 end end tables_count || 0 end
Set the table ids for the worksheet tables .
9,058
def write_formatted_blank_to_area ( row_first , row_last , col_first , col_last , format ) ( row_first .. row_last ) . each do | row | ( col_first .. col_last ) . each do | col | next if row == row_first && col == col_first write_blank ( row , col , format ) end end end
Pad out the rest of the area with formatted blank cells .
9,059
def parse_filter_tokens ( expression , tokens ) operators = { '==' => 2 , '=' => 2 , '=~' => 2 , 'eq' => 2 , '!=' => 5 , '!~' => 5 , 'ne' => 5 , '<>' => 5 , '<' => 1 , '<=' => 3 , '>' => 4 , '>=' => 6 , } operator = operators [ tokens [ 1 ] ] token = tokens [ 2 ] if tokens [ 0 ] =~ / /i value = tokens [ 1 ] if ( value ...
Parse the 3 tokens of a filter expression and return the operator and token .
9,060
def position_object_emus ( col_start , row_start , x1 , y1 , width , height , x_dpi = 96 , y_dpi = 96 ) col_start , row_start , x1 , y1 , col_end , row_end , x2 , y2 , x_abs , y_abs = position_object_pixels ( col_start , row_start , x1 , y1 , width , height ) x1 = ( 0.5 + 9_525 * x1 ) . to_i y1 = ( 0.5 + 9_525 * y1 ) ....
Calculate the vertices that define the position of a graphical object within the worksheet in EMUs .
9,061
def size_col ( col ) if @col_sizes [ col ] width = @col_sizes [ col ] if width == 0 pixels = 0 elsif width < 1 pixels = ( width * ( MAX_DIGIT_WIDTH + PADDING ) + 0.5 ) . to_i else pixels = ( width * MAX_DIGIT_WIDTH + 0.5 ) . to_i + PADDING end else pixels = @default_col_pixels end pixels end
Convert the width of a cell from user s units to pixels . Excel rounds the column width to the nearest pixel . If the width hasn t been set by the user we use the default value . If the column is hidden it has a value of zero .
9,062
def size_row ( row ) if @row_sizes [ row ] height = @row_sizes [ row ] if height == 0 pixels = 0 else pixels = ( 4 / 3.0 * height ) . to_i end else pixels = ( 4 / 3.0 * @default_row_height ) . to_i end pixels end
Convert the height of a cell from user s units to pixels . If the height hasn t been set by the user we use the default value . If the row is hidden it has a value of zero .
9,063
def prepare_shape ( index , drawing_id ) shape = @shapes [ index ] unless drawing? @drawing = Drawing . new @drawing . embedded = 1 @external_drawing_links << [ '/drawing' , "../drawings/drawing#{drawing_id}.xml" ] @has_shapes = true end shape . validate ( index ) shape . calc_position_emus ( self ) drawing_type = 3 dr...
Set up drawing shapes
9,064
def button_params ( row , col , params ) button = Writexlsx :: Package :: Button . new button_number = 1 + @buttons_array . size caption = params [ :caption ] || "Button #{button_number}" button . font = { :_caption => caption } if params [ :macro ] button . macro = "[0]!#{params[:macro]}" else button . macro = "[0]!Bu...
This method handles the parameters passed to insert_button as well as calculating the comment object position and vertices .
9,065
def write_rows calculate_spans ( @dim_rowmin .. @dim_rowmax ) . each do | row_num | next if not_contain_formatting_or_data? ( row_num ) span_index = row_num / 16 span = @row_spans [ span_index ] if @cell_data_table [ row_num ] args = @set_rows [ row_num ] || [ ] write_row_element ( row_num , span , * args ) do write_ce...
Write out the worksheet data as a series of rows and cells .
9,066
def calculate_x_split_width ( width ) if width < 1 pixels = int ( width * 12 + 0.5 ) else pixels = ( width * MAX_DIGIT_WIDTH + 0.5 ) . to_i + PADDING end points = pixels * 3 / 4 twips = points * 20 twips + 390 end
Convert column width from user units to pane split width .
9,067
def write_autofilters col1 , col2 = @filter_range ( col1 .. col2 ) . each do | col | next unless @filter_cols [ col ] tokens = @filter_cols [ col ] type = @filter_type [ col ] write_filter_column ( col - col1 , type , * tokens ) end end
Function to iterate through the columns that form part of an autofilter range and write the appropriate filters .
9,068
def calc_position_emus ( worksheet ) c_start , r_start , xx1 , yy1 , c_end , r_end , xx2 , yy2 , x_abslt , y_abslt = worksheet . position_object_pixels ( @column_start , @row_start , @x_offset , @y_offset , @width * @scale_x , @height * @scale_y ) @width_emu = ( @width * 9_525 ) . abs . to_i @height_emu = ( @height * 9...
Calculate the vertices that define the position of a shape object within the worksheet in EMUs . Save the vertices with the object .
9,069
def auto_locate_connectors ( shapes , shape_hash ) connector_shapes = { :straightConnector => 1 , :Connector => 1 , :bentConnector => 1 , :curvedConnector => 1 , :line => 1 } shape_base = @type . chop . to_sym @connect = connector_shapes [ shape_base ] ? 1 : 0 return if @connect == 0 return if @start == 0 && @end == 0 ...
Re - size connector shapes if they are connected to other shapes .
9,070
def validate ( index ) unless %w[ l ctr r just ] . include? ( @align ) raise "Shape #{index} (#{@type}) alignment (#{@align}) not in ['l', 'ctr', 'r', 'just']\n" end unless %w[ t ctr b ] . include? ( @valign ) raise "Shape #{index} (#{@type}) vertical alignment (#{@valign}) not in ['t', 'ctr', 'v']\n" end end
Check shape attributes to ensure they are valid .
9,071
def copy ( other ) reserve = [ :xf_index , :dxf_index , :xdf_format_indices , :palette ] ( instance_variables - reserve ) . each do | v | instance_variable_set ( v , other . instance_variable_get ( v ) ) end end
Copy the attributes of another Format object .
9,072
def layout_properties ( args , is_text = false ) return unless ptrue? ( args ) properties = is_text ? [ :x , :y ] : [ :x , :y , :width , :height ] args . keys . each do | key | unless properties . include? ( key . to_sym ) raise "Property '#{key}' not allowed in layout options\n" end end layout = Hash . new properties ...
Convert user defined layout properties to the format required internally .
9,073
def pixels_to_points ( vertices ) col_start , row_start , x1 , y1 , col_end , row_end , x2 , y2 , left , top , width , height = vertices . flatten left *= 0.75 top *= 0.75 width *= 0.75 height *= 0.75 [ left , top , width , height ] end
Convert vertices from pixels to points .
9,074
def write_spark_color ( element , color ) attr = [ ] attr << [ 'rgb' , color [ :_rgb ] ] if color [ :_rgb ] attr << [ 'theme' , color [ :_theme ] ] if color [ :_theme ] attr << [ 'tint' , color [ :_tint ] ] if color [ :_tint ] @writer . empty_tag ( element , attr ) end
Helper function for the sparkline color functions below .
9,075
def assemble_xml_file return unless @writer prepare_format_properties write_xml_declaration do write_workbook do write_file_version write_workbook_pr write_book_views @worksheets . write_sheets ( @writer ) write_defined_names write_calc_pr end end end
user must not use . it is internal method .
9,076
def add_format ( property_hash = { } ) properties = { } if @excel2003_style properties . update ( :font => 'Arial' , :size => 10 , :theme => - 1 ) end properties . update ( property_hash ) format = Format . new ( @formats , properties ) @formats . formats . push ( format ) format end
The + add_format + method can be used to create new Format objects which are used to apply formatting to a cell . You can either define the properties at creation time via a hash of property values or later via method calls .
9,077
def add_shape ( properties = { } ) shape = Shape . new ( properties ) shape . palette = @palette @shapes ||= [ ] @shapes << shape shape end
The + add_shape + method can be used to create new shapes that may be inserted into a worksheet .
9,078
def set_properties ( params ) return - 1 if params . empty? valid = { :title => 1 , :subject => 1 , :author => 1 , :keywords => 1 , :comments => 1 , :last_author => 1 , :created => 1 , :category => 1 , :manager => 1 , :company => 1 , :status => 1 } params . each_key do | key | return - 1 unless valid . has_key? ( key )...
The set_properties method can be used to set the document properties of the Excel file created by WriteXLSX . These properties are visible when you use the Office Button - > Prepare - > Properties option in Excel and are also available to external applications that read or index windows files .
9,079
def set_custom_color ( index , red = 0 , green = 0 , blue = 0 ) if red =~ / \w \w \w \w \w \w / red = $1 . hex green = $2 . hex blue = $3 . hex end if index < 8 || index > 64 raise "Color index #{index} outside range: 8 <= index <= 64" end if ( red < 0 || red > 255 ) || ( green < 0 || green > 255 ) || ( blue < 0 || blu...
Change the RGB components of the elements in the colour palette .
9,080
def store_workbook add_worksheet if @worksheets . empty? @worksheets . visible_first . select if @activesheet == 0 @activesheet = @worksheets . visible_first . index if @activesheet == 0 @worksheets [ @activesheet ] . activate prepare_vml_objects prepare_defined_names prepare_drawings add_chart_data prepare_tables pack...
Assemble worksheets into a workbook .
9,081
def prepare_formats @formats . formats . each do | format | xf_index = format . xf_index dxf_index = format . dxf_index @xf_formats [ xf_index ] = format if xf_index @dxf_formats [ dxf_index ] = format if dxf_index end end
Iterate through the XF Format objects and separate them into XF and DXF formats .
9,082
def prepare_fonts fonts = { } @xf_formats . each { | format | format . set_font_info ( fonts ) } @font_count = fonts . size @dxf_formats . each do | format | if format . color? || format . bold? || format . italic? || format . underline? || format . strikeout? format . has_dxf_font ( true ) end end end
Iterate through the XF Format objects and give them an index to non - default font elements .
9,083
def prepare_num_formats num_formats = { } index = 164 num_format_count = 0 ( @xf_formats + @dxf_formats ) . each do | format | num_format = format . num_format if num_format . to_s =~ / \d / && num_format . to_s !~ / \d / format . num_format_index = num_format next end if num_formats [ num_format ] format . num_format_...
Iterate through the XF Format objects and give them an index to non - default number format elements .
9,084
def prepare_borders borders = { } @xf_formats . each { | format | format . set_border_info ( borders ) } @border_count = borders . size @dxf_formats . each do | format | key = format . get_border_key format . has_dxf_border ( true ) if key =~ / / end end
Iterate through the XF Format objects and give them an index to non - default border elements .
9,085
def prepare_fills fills = { } index = 2 fills [ '0:0:0' ] = 0 fills [ '17:0:0' ] = 1 @dxf_formats . each do | format | if format . pattern != 0 || format . bg_color != 0 || format . fg_color != 0 format . has_dxf_fill ( true ) format . dxf_bg_color = format . bg_color format . dxf_fg_color = format . fg_color end end @...
Iterate through the XF Format objects and give them an index to non - default fill elements .
9,086
def prepare_defined_names @worksheets . each do | sheet | if sheet . autofilter_area @defined_names << [ '_xlnm._FilterDatabase' , sheet . index , sheet . autofilter_area , 1 ] end if ! sheet . print_area . empty? @defined_names << [ '_xlnm.Print_Area' , sheet . index , sheet . print_area ] end if ! sheet . print_repea...
Iterate through the worksheets and store any defined names in addition to any user defined names . Stores the defined names for the Workbook . xml and the named ranges for App . xml .
9,087
def prepare_vml_objects comment_id = 0 vml_drawing_id = 0 vml_data_id = 1 vml_header_id = 0 vml_shape_id = 1024 comment_files = 0 has_button = false @worksheets . each do | sheet | next if ! sheet . has_vml? && ! sheet . has_header_vml? if sheet . has_vml? if sheet . has_comments? comment_files += 1 comment_id += 1 end...
Iterate through the worksheets and set up the VML objects .
9,088
def extract_named_ranges ( defined_names ) named_ranges = [ ] defined_names . each do | defined_name | name , index , range = defined_name next if name == '_xlnm._FilterDatabase' if range =~ / / sheet_name = $1 if name =~ / \. / xlnm_type = $1 name = "#{sheet_name}!#{xlnm_type}" elsif index != - 1 name = "#{sheet_name}...
Extract the named ranges from the sorted list of defined names . These are used in the App . xml file .
9,089
def prepare_drawings chart_ref_id = 0 image_ref_id = 0 drawing_id = 0 @worksheets . each do | sheet | chart_count = sheet . charts . size image_count = sheet . images . size shape_count = sheet . shapes . size header_image_count = sheet . header_images . size footer_image_count = sheet . footer_images . size has_drawin...
Iterate through the worksheets and set up any chart or image drawings .
9,090
def get_image_properties ( filename ) x_dpi = 96 y_dpi = 96 data = File . binread ( filename ) if data . unpack ( 'x A3' ) [ 0 ] == 'PNG' type , width , height , x_dpi , y_dpi = process_png ( data ) @image_types [ :png ] = 1 elsif data . unpack ( 'n' ) [ 0 ] == 0xFFD8 type , width , height , x_dpi , y_dpi = process_jpg...
Extract information from the image file such as dimension type filename and extension . Also keep track of previously seen images to optimise out any duplicates .
9,091
def process_png ( data ) type = 'png' width = 0 height = 0 x_dpi = 96 y_dpi = 96 offset = 8 data_length = data . size while offset < data_length length = data [ offset + 0 , 4 ] . unpack ( "N" ) [ 0 ] png_type = data [ offset + 4 , 4 ] . unpack ( "A4" ) [ 0 ] case png_type when "IHDR" width = data [ offset + 8 , 4 ] . ...
Extract width and height information from a PNG file .
9,092
def process_bmp ( data , filename ) type = 'bmp' raise "#{filename} doesn't contain enough data." if data . bytesize <= 0x36 width , height = data . unpack ( "x18 V2" ) raise "#{filename}: largest image width #{width} supported is 65k." if width > 0xFFFF raise "#{filename}: largest image height supported is 65k." if he...
Extract width and height information from a BMP file .
9,093
def daemon_address = ( v ) v = ENV [ DaemonConfig :: DAEMON_ADDRESS_KEY ] || v config = DaemonConfig . new ( addr : v ) emitter . daemon_config = config sampler . daemon_config = config if sampler . respond_to? ( :daemon_config= ) end
setting daemon address for components communicate with X - Ray daemon .
9,094
def all_children_count size = subsegments . count subsegments . each { | v | size += v . all_children_count } size end
Returns the number of its direct and indirect children . This is useful when we remove the reference to a subsegment and need to keep remaining subsegment size accurate .
9,095
def sample_request? ( sampling_req ) sample = sample? return sample if sampling_req . nil? || sampling_req . empty? @custom_rules ||= [ ] @custom_rules . each do | c | return should_sample? ( c ) if c . applies? ( sampling_req ) end sample end
Return True if the sampler decide to sample based on input information and sampling rules . It will first check if any custom rule should be applied if not it falls back to the default sampling rule . All arugments are extracted from incoming requests by X - Ray middleware to perform path based sampling .
9,096
def begin_segment ( name , trace_id : nil , parent_id : nil , sampled : nil ) seg_name = name || config . name raise SegmentNameMissingError if seg_name . to_s . empty? sample = sampled . nil? ? config . sample? : sampled if sample segment = Segment . new name : seg_name , trace_id : trace_id , parent_id : parent_id po...
Begin a segment for the current context . The recorder only keeps one segment at a time . Create a second one without closing existing one will overwrite the existing one .
9,097
def end_segment ( end_time : nil ) segment = current_segment return unless segment segment . close end_time : end_time context . clear! emitter . send_entity entity : segment if segment . ready_to_send? end
End the current segment and send it to X - Ray daemon if it is ready .
9,098
def begin_subsegment ( name , namespace : nil , segment : nil ) entity = segment || current_entity return unless entity if entity . sampled subsegment = Subsegment . new name : name , segment : entity . segment , namespace : namespace else subsegment = DummySubsegment . new name : name , segment : entity . segment end ...
Begin a new subsegment and add it to be the child of the current active subsegment or segment . Also tie the new created subsegment to the current context . Its sampling decision will follow its parent .
9,099
def end_subsegment ( end_time : nil ) entity = current_entity return unless entity . is_a? ( Subsegment ) entity . close end_time : end_time if entity . parent . closed? context . clear! else context . store_entity entity : entity . parent end segment = entity . segment if segment . ready_to_send? emitter . send_entity...
End the current active subsegment . It also send the entire segment if this subsegment is the last one open or stream out subsegments of its parent segment if the stream threshold is breached .