idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
2,500 | def background_image = ( bg_image ) warn 'background_image= has no effect in nested RVG objects' if @nested raise ArgumentError , "background image must be an Image (got #{bg_image.class})" if bg_image && ! bg_image . is_a? ( Magick :: Image ) @background_image = bg_image end | Sets an image to use as the canvas background . See background_position = for layout options . |
2,501 | def add_outermost_primitives ( gc ) add_transform_primitives ( gc ) gc . push add_viewbox_primitives ( @width , @height , gc ) add_style_primitives ( gc ) @content . each { | element | element . add_primitives ( gc ) } gc . pop self end | Primitives for the outermost RVG object |
2,502 | def add_primitives ( gc ) raise ArgumentError , 'RVG width or height undefined' if @width . nil? || @height . nil? return self if @width . zero? || @height . zero? gc . push add_outermost_primitives ( gc ) gc . pop end | Primitives for nested RVG objects |
2,503 | def to_s str = '' if @width > 0 fmt = @width . truncate == @width ? '%d' : '%.2f' str << format ( fmt , @width ) str << '%' if @flag == PercentGeometry end str << 'x' if ( @width > 0 && @flag != PercentGeometry ) || ( @height > 0 ) if @height > 0 fmt = @height . truncate == @height ? '%d' : '%.2f' str << format ( fmt , @height ) str << '%' if @flag == PercentGeometry end str << format ( '%+d%+d' , @x , @y ) if @x != 0 || @y != 0 str << FLAGS [ @flag . to_i ] if @flag != PercentGeometry str end | Convert object to a geometry string |
2,504 | def arc ( start_x , start_y , end_x , end_y , start_degrees , end_degrees ) primitive 'arc ' + format ( '%g,%g %g,%g %g,%g' , start_x , start_y , end_x , end_y , start_degrees , end_degrees ) end | Draw an arc . |
2,505 | def circle ( origin_x , origin_y , perim_x , perim_y ) primitive 'circle ' + format ( '%g,%g %g,%g' , origin_x , origin_y , perim_x , perim_y ) end | Draw a circle |
2,506 | def clip_rule ( rule ) Kernel . raise ArgumentError , "Unknown clipping rule #{rule}" unless %w[ evenodd nonzero ] . include? ( rule . downcase ) primitive "clip-rule #{rule}" end | Define the clipping rule . |
2,507 | def clip_units ( unit ) Kernel . raise ArgumentError , "Unknown clip unit #{unit}" unless %w[ userspace userspaceonuse objectboundingbox ] . include? ( unit . downcase ) primitive "clip-units #{unit}" end | Define the clip units |
2,508 | def color ( x , y , method ) Kernel . raise ArgumentError , "Unknown PaintMethod: #{method}" unless PAINT_METHOD_NAMES . key? ( method . to_i ) primitive "color #{x},#{y},#{PAINT_METHOD_NAMES[method.to_i]}" end | Set color in image according to specified colorization rule . Rule is one of point replace floodfill filltoborder reset |
2,509 | def ellipse ( origin_x , origin_y , width , height , arc_start , arc_end ) primitive 'ellipse ' + format ( '%g,%g %g,%g %g,%g' , origin_x , origin_y , width , height , arc_start , arc_end ) end | Draw an ellipse |
2,510 | def interline_spacing ( space ) begin Float ( space ) rescue ArgumentError Kernel . raise ArgumentError , 'invalid value for interline_spacing' rescue TypeError Kernel . raise TypeError , "can't convert #{space.class} into Float" end primitive "interline-spacing #{space}" end | IM 6 . 5 . 5 - 8 and later |
2,511 | def line ( start_x , start_y , end_x , end_y ) primitive 'line ' + format ( '%g,%g %g,%g' , start_x , start_y , end_x , end_y ) end | Draw a line |
2,512 | def opacity ( opacity ) if opacity . is_a? ( Numeric ) Kernel . raise ArgumentError , 'opacity must be >= 0 and <= 1.0' if opacity < 0 || opacity > 1.0 end primitive "opacity #{opacity}" end | Specify drawing fill and stroke opacities . If the value is a string ending with a % the number will be multiplied by 0 . 01 . |
2,513 | def pattern ( name , x , y , width , height ) push ( 'defs' ) push ( "pattern #{name} #{x} #{y} #{width} #{height}" ) push ( 'graphic-context' ) yield ensure pop ( 'graphic-context' ) pop ( 'pattern' ) pop ( 'defs' ) end | Define a pattern . In the block call primitive methods to draw the pattern . Reference the pattern by using its name as the argument to the fill or stroke methods |
2,514 | def polygon ( * points ) if points . length . zero? Kernel . raise ArgumentError , 'no points specified' elsif points . length . odd? Kernel . raise ArgumentError , 'odd number of points specified' end primitive 'polygon ' + points . join ( ',' ) end | Draw a polygon |
2,515 | def rectangle ( upper_left_x , upper_left_y , lower_right_x , lower_right_y ) primitive 'rectangle ' + format ( '%g,%g %g,%g' , upper_left_x , upper_left_y , lower_right_x , lower_right_y ) end | Draw a rectangle |
2,516 | def roundrectangle ( center_x , center_y , width , height , corner_width , corner_height ) primitive 'roundrectangle ' + format ( '%g,%g,%g,%g,%g,%g' , center_x , center_y , width , height , corner_width , corner_height ) end | Draw a rectangle with rounded corners |
2,517 | def stroke_dasharray ( * list ) if list . length . zero? primitive 'stroke-dasharray none' else list . each do | x | Kernel . raise ArgumentError , "dash array elements must be > 0 (#{x} given)" if x <= 0 end primitive "stroke-dasharray #{list.join(',')}" end end | Specify a stroke dash pattern |
2,518 | def text ( x , y , text ) Kernel . raise ArgumentError , 'missing text argument' if text . to_s . empty? if text . length > 2 && / \A \" \" \" \' \' \' \{ \} \} \z / . match ( text ) elsif ! text [ '\'' ] text = '\'' + text + '\'' elsif ! text [ '"' ] text = '"' + text + '"' elsif ! ( text [ '{' ] || text [ '}' ] ) text = '{' + text + '}' else text = '{' + text . gsub ( / / ) { | b | '\\' + b } + '}' end primitive "text #{x},#{y} #{text}" end | Draw text at position x y . Add quotes to text that is not already quoted . |
2,519 | def text_align ( alignment ) Kernel . raise ArgumentError , "Unknown alignment constant: #{alignment}" unless ALIGN_TYPE_NAMES . key? ( alignment . to_i ) primitive "text-align #{ALIGN_TYPE_NAMES[alignment.to_i]}" end | Specify text alignment relative to a given point |
2,520 | def text_anchor ( anchor ) Kernel . raise ArgumentError , "Unknown anchor constant: #{anchor}" unless ANCHOR_TYPE_NAMES . key? ( anchor . to_i ) primitive "text-anchor #{ANCHOR_TYPE_NAMES[anchor.to_i]}" end | SVG - compatible version of text_align |
2,521 | def color_point ( x , y , fill ) f = copy f . pixel_color ( x , y , fill ) f end | Set the color at x y |
2,522 | def color_floodfill ( x , y , fill ) target = pixel_color ( x , y ) color_flood_fill ( target , fill , x , y , Magick :: FloodfillMethod ) end | Set all pixels that have the same color as the pixel at x y and are neighbors to the fill color |
2,523 | def color_fill_to_border ( x , y , fill ) color_flood_fill ( border_color , fill , x , y , Magick :: FillToBorderMethod ) end | Set all pixels that are neighbors of x y and are not the border color to the fill color |
2,524 | def each_pixel get_pixels ( 0 , 0 , columns , rows ) . each_with_index do | p , n | yield ( p , n % columns , n / columns ) end self end | Thanks to Russell Norris! |
2,525 | def matte_fill_to_border ( x , y ) f = copy f . opacity = Magick :: OpaqueOpacity unless f . alpha? f . matte_flood_fill ( border_color , TransparentOpacity , x , y , FillToBorderMethod ) end | Make transparent any neighbor pixel that is not the border color . |
2,526 | def texture_floodfill ( x , y , texture ) target = pixel_color ( x , y ) texture_flood_fill ( target , texture , x , y , FloodfillMethod ) end | Replace matching neighboring pixels with texture pixels |
2,527 | def texture_fill_to_border ( x , y , texture ) texture_flood_fill ( border_color , texture , x , y , FillToBorderMethod ) end | Replace neighboring pixels to border color with texture pixels |
2,528 | def view ( x , y , width , height ) view = View . new ( self , x , y , width , height ) return view unless block_given? begin yield ( view ) ensure view . sync end nil end | Construct a view . If a block is present yield and pass the view object otherwise return the view object . |
2,529 | def set_current ( current ) if length . zero? self . scene = nil return elsif scene . nil? || scene >= length self . scene = length - 1 return elsif ! current . nil? self . scene = length - 1 each_with_index do | f , i | self . scene = i if f . __id__ == current end return end self . scene = length - 1 end | Find old current image update scene number current is the id of the old current image . |
2,530 | def scene = ( n ) if n . nil? Kernel . raise IndexError , 'scene number out of bounds' unless @images . length . zero? @scene = nil return @scene elsif @images . length . zero? Kernel . raise IndexError , 'scene number out of bounds' end n = Integer ( n ) Kernel . raise IndexError , 'scene number out of bounds' if n < 0 || n > length - 1 @scene = n @scene end | Allow scene to be set to nil |
2,531 | def copy ditto = self . class . new @images . each { | f | ditto << f . copy } ditto . scene = @scene ditto . taint if tainted? ditto end | Make a deep copy |
2,532 | def delay = ( d ) raise ArgumentError , 'delay must be greater than or equal to 0' if Integer ( d ) < 0 @images . each { | f | f . delay = Integer ( d ) } end | Set same delay for all images |
2,533 | def insert ( index , * args ) args . each { | image | is_an_image image } current = get_current @images . insert ( index , * args ) set_current current self end | Initialize new instances |
2,534 | def inspect img = [ ] @images . each { | image | img << image . inspect } img = '[' + img . join ( ",\n" ) + "]\nscene=#{@scene}" end | Call inspect for all the images |
2,535 | def iterations = ( n ) n = Integer ( n ) Kernel . raise ArgumentError , 'iterations must be between 0 and 65535' if n < 0 || n > 65_535 @images . each { | f | f . iterations = n } self end | Set the number of iterations of an animated GIF |
2,536 | def new_image ( cols , rows , * fill , & info_blk ) self << Magick :: Image . new ( cols , rows , * fill , & info_blk ) end | Create a new image and add it to the end |
2,537 | def read ( * files , & block ) Kernel . raise ArgumentError , 'no files given' if files . length . zero? files . each do | f | Magick :: Image . read ( f , & block ) . each { | n | @images << n } end @scene = length - 1 self end | Read files and concatenate the new images |
2,538 | def reject ( & block ) current = get_current ilist = self . class . new a = @images . reject ( & block ) a . each { | image | ilist << image } ilist . set_current current ilist end | override Enumerable s reject |
2,539 | def alpha_hist ( freqs , scale , fg , bg ) histogram = Image . new ( HISTOGRAM_COLS , HISTOGRAM_ROWS ) do self . background_color = bg self . border_color = fg end gc = Draw . new gc . affine ( 1 , 0 , 0 , - scale , 0 , HISTOGRAM_ROWS ) gc . fill ( 'white' ) HISTOGRAM_COLS . times do | x | gc . point ( x , freqs [ x ] ) end gc . draw ( histogram ) histogram [ 'Label' ] = 'Alpha' histogram end | The alpha frequencies are shown as white dots . |
2,540 | def color_hist ( fg , bg ) img = number_colors > 256 ? quantize ( 256 ) : self begin hist = img . color_histogram rescue NotImplementedError warn 'The color_histogram method is not supported by this version ' 'of ImageMagick/GraphicsMagick' else pixels = hist . keys . sort_by { | pixel | hist [ pixel ] } scale = HISTOGRAM_ROWS / ( hist . values . max * AIR_FACTOR ) histogram = Image . new ( HISTOGRAM_COLS , HISTOGRAM_ROWS ) do self . background_color = bg self . border_color = fg end x = 0 pixels . each do | pixel | column = Array . new ( HISTOGRAM_ROWS ) . fill { Pixel . new } HISTOGRAM_ROWS . times do | y | column [ y ] = pixel if y >= HISTOGRAM_ROWS - ( hist [ pixel ] * scale ) end histogram . store_pixels ( x , 0 , 1 , HISTOGRAM_ROWS , column ) x = x . succ end histogram [ 'Label' ] = 'Color Frequency' return histogram end end | Make the color histogram . Quantize the image to 256 colors if necessary . |
2,541 | def pixel_intensity ( pixel ) ( 306 * ( pixel . red & MAX_QUANTUM ) + 601 * ( pixel . green & MAX_QUANTUM ) + 117 * ( pixel . blue & MAX_QUANTUM ) ) / 1024 end | Returns a value between 0 and MAX_QUANTUM . Same as the PixelIntensity macro . |
2,542 | def histogram ( fg = 'white' , bg = 'black' ) red = Array . new ( HISTOGRAM_COLS , 0 ) green = Array . new ( HISTOGRAM_COLS , 0 ) blue = Array . new ( HISTOGRAM_COLS , 0 ) alpha = Array . new ( HISTOGRAM_COLS , 0 ) int = Array . new ( HISTOGRAM_COLS , 0 ) rows . times do | row | pixels = get_pixels ( 0 , row , columns , 1 ) pixels . each do | pixel | red [ pixel . red & MAX_QUANTUM ] += 1 green [ pixel . green & MAX_QUANTUM ] += 1 blue [ pixel . blue & MAX_QUANTUM ] += 1 alpha [ pixel . opacity & MAX_QUANTUM ] += 1 unless opaque? v = pixel_intensity ( pixel ) int [ v ] += 1 end end max = [ red . max , green . max , blue . max , alpha . max , int . max ] . max scale = HISTOGRAM_ROWS / ( max * AIR_FACTOR ) charts = ImageList . new thumb = copy thumb [ 'Label' ] = File . basename ( filename ) charts << thumb channel_hists = channel_histograms ( red , green , blue , int , scale , fg , bg ) charts << channel_hists . shift charts << channel_hists . shift charts << channel_hists . shift charts << if ! opaque? alpha_hist ( alpha , scale , fg , bg ) else info_text ( fg , bg ) end charts << channel_hists . shift charts << intensity_hist ( channel_hists . shift ) charts << color_hist ( fg , bg ) histogram = charts . montage do self . background_color = bg self . stroke = 'transparent' self . fill = fg self . border_width = 1 self . tile = '4x2' self . geometry = "#{HISTOGRAM_COLS}x#{HISTOGRAM_ROWS}+10+10" end histogram end | Create the histogram montage . |
2,543 | def get_cas ( key ) ( value , cas ) = perform ( :cas , key ) value = ( ! value || value == 'Not found' ) ? nil : value if block_given? yield value , cas else [ value , cas ] end end | Get the value and CAS ID associated with the key . If a block is provided value and CAS will be passed to the block . |
2,544 | def set_cas ( key , value , cas , ttl = nil , options = nil ) ttl ||= @options [ :expires_in ] . to_i perform ( :set , key , value , ttl , cas , options ) end | Set the key - value pair verifying existing CAS . Returns the resulting CAS value if succeeded and falsy otherwise . |
2,545 | def fetch ( key , ttl = nil , options = nil ) options = options . nil? ? CACHE_NILS : options . merge ( CACHE_NILS ) if @options [ :cache_nils ] val = get ( key , options ) not_found = @options [ :cache_nils ] ? val == Dalli :: Server :: NOT_FOUND : val . nil? if not_found && block_given? val = yield add ( key , val , ttl_or_default ( ttl ) , options ) end val end | Fetch the value associated with the key . If a value is found then it is returned . |
2,546 | def cas ( key , ttl = nil , options = nil , & block ) cas_core ( key , false , ttl , options , & block ) end | compare and swap values using optimistic locking . Fetch the existing value for key . If it exists yield the value to the block . Add the block s return value as the new value for the key . Add will fail if someone else changed the value . |
2,547 | def incr ( key , amt = 1 , ttl = nil , default = nil ) raise ArgumentError , "Positive values only: #{amt}" if amt < 0 perform ( :incr , key , amt . to_i , ttl_or_default ( ttl ) , default ) end | Incr adds the given amount to the counter on the memcached server . Amt must be a positive integer value . |
2,548 | def touch ( key , ttl = nil ) resp = perform ( :touch , key , ttl_or_default ( ttl ) ) resp . nil? ? nil : true end | Touch updates expiration time for a given key . |
2,549 | def version values = { } ring . servers . each do | server | values [ "#{server.name}" ] = server . alive? ? server . request ( :version ) : nil end values end | Version of the memcache servers . |
2,550 | def get_multi_yielder ( keys ) perform do return { } if keys . empty? ring . lock do begin groups = groups_for_keys ( keys ) if unfound_keys = groups . delete ( nil ) Dalli . logger . debug { "unable to get keys for #{unfound_keys.length} keys because no matching server was found" } end make_multi_get_requests ( groups ) servers = groups . keys return if servers . empty? servers = perform_multi_response_start ( servers ) start = Time . now while true servers . delete_if { | s | s . sock . nil? } break if servers . empty? elapsed = Time . now - start timeout = servers . first . options [ :socket_timeout ] time_left = ( elapsed > timeout ) ? 0 : timeout - elapsed sockets = servers . map ( & :sock ) readable , _ = IO . select ( sockets , nil , nil , time_left ) if readable . nil? servers . each do | server | Dalli . logger . debug { "memcached at #{server.name} did not response within timeout" } server . multi_response_abort end break else readable . each do | sock | server = sock . server begin server . multi_response_nonblock . each_pair do | key , value_list | yield key_without_namespace ( key ) , value_list end if server . multi_response_completed? servers . delete ( server ) end rescue NetworkError servers . delete ( server ) end end end end end end end end | Yields one at a time keys and their values + attributes . |
2,551 | def delete_entity ( resource_name , name , namespace = nil , delete_options : { } ) delete_options_hash = delete_options . to_hash ns_prefix = build_namespace_prefix ( namespace ) payload = delete_options_hash . to_json unless delete_options_hash . empty? response = handle_exception do rs = rest_client [ ns_prefix + resource_name + "/#{name}" ] RestClient :: Request . execute ( rs . options . merge ( method : :delete , url : rs . url , headers : { 'Content-Type' => 'application/json' } . merge ( @headers ) , payload : payload ) ) end format_response ( @as , response . body ) end | delete_options are passed as a JSON payload in the delete request |
2,552 | def format_datetime ( value ) case value when DateTime , Time value . strftime ( '%FT%T.%9N%:z' ) when String value else raise ArgumentError , "unsupported type '#{value.class}' of time value '#{value}'" end end | Format datetime according to RFC3339 |
2,553 | def extract ( uri , processor = nil ) match_data = self . match ( uri , processor ) return ( match_data ? match_data . mapping : nil ) end | Extracts a mapping from the URI using a URI Template pattern . |
2,554 | def match ( uri , processor = nil ) uri = Addressable :: URI . parse ( uri ) mapping = { } expansions , expansion_regexp = parse_template_pattern ( pattern , processor ) return nil unless uri . to_str . match ( expansion_regexp ) unparsed_values = uri . to_str . scan ( expansion_regexp ) . flatten if uri . to_str == pattern return Addressable :: Template :: MatchData . new ( uri , self , mapping ) elsif expansions . size > 0 index = 0 expansions . each do | expansion | _ , operator , varlist = * expansion . match ( EXPRESSION ) varlist . split ( ',' ) . each do | varspec | _ , name , modifier = * varspec . match ( VARSPEC ) mapping [ name ] ||= nil case operator when nil , '+' , '#' , '/' , '.' unparsed_value = unparsed_values [ index ] name = varspec [ VARSPEC , 1 ] value = unparsed_value value = value . split ( JOINERS [ operator ] ) if value && modifier == '*' when ';' , '?' , '&' if modifier == '*' if unparsed_values [ index ] value = unparsed_values [ index ] . split ( JOINERS [ operator ] ) value = value . inject ( { } ) do | acc , v | key , val = v . split ( '=' ) val = "" if val . nil? acc [ key ] = val acc end end else if ( unparsed_values [ index ] ) name , value = unparsed_values [ index ] . split ( '=' ) value = "" if value . nil? end end end if processor != nil && processor . respond_to? ( :restore ) value = processor . restore ( name , value ) end if processor == nil if value . is_a? ( Hash ) value = value . inject ( { } ) { | acc , ( k , v ) | acc [ Addressable :: URI . unencode_component ( k ) ] = Addressable :: URI . unencode_component ( v ) acc } elsif value . is_a? ( Array ) value = value . map { | v | Addressable :: URI . unencode_component ( v ) } else value = Addressable :: URI . unencode_component ( value ) end end if ! mapping . has_key? ( name ) || mapping [ name ] . nil? mapping [ name ] = value end index = index + 1 end end return Addressable :: Template :: MatchData . new ( uri , self , mapping ) else return nil end end | Extracts match data from the URI using a URI Template pattern . |
2,555 | def partial_expand ( mapping , processor = nil , normalize_values = true ) result = self . pattern . dup mapping = normalize_keys ( mapping ) result . gsub! ( EXPRESSION ) do | capture | transform_partial_capture ( mapping , capture , processor , normalize_values ) end return Addressable :: Template . new ( result ) end | Expands a URI template into another URI template . |
2,556 | def expand ( mapping , processor = nil , normalize_values = true ) result = self . pattern . dup mapping = normalize_keys ( mapping ) result . gsub! ( EXPRESSION ) do | capture | transform_capture ( mapping , capture , processor , normalize_values ) end return Addressable :: URI . parse ( result ) end | Expands a URI template into a full URI . |
2,557 | def generate ( params = { } , recall = { } , options = { } ) merged = recall . merge ( params ) if options [ :processor ] processor = options [ :processor ] elsif options [ :parameterize ] processor = Object . new class << processor attr_accessor :block def transform ( name , value ) block . call ( name , value ) end end processor . block = options [ :parameterize ] else processor = nil end result = self . expand ( merged , processor ) result . to_s if result end | Generates a route result for a given set of parameters . Should only be used by rack - mount . |
2,558 | def transform_partial_capture ( mapping , capture , processor = nil , normalize_values = true ) _ , operator , varlist = * capture . match ( EXPRESSION ) vars = varlist . split ( "," ) if operator == "?" first_to_expand = vars . find { | varspec | _ , name , _ = * varspec . match ( VARSPEC ) mapping . key? ( name ) && ! mapping [ name ] . nil? } vars = [ first_to_expand ] + vars . reject { | varspec | varspec == first_to_expand } if first_to_expand end vars . inject ( "" . dup ) do | acc , varspec | _ , name , _ = * varspec . match ( VARSPEC ) next_val = if mapping . key? name transform_capture ( mapping , "{#{operator}#{varspec}}" , processor , normalize_values ) else "{#{operator}#{varspec}}" end operator = "&" if ( operator == "?" ) && ( next_val != "" ) acc << next_val end end | Loops through each capture and expands any values available in mapping |
2,559 | def normalize_keys ( mapping ) return mapping . inject ( { } ) do | accu , pair | name , value = pair if Symbol === name name = name . to_s elsif name . respond_to? ( :to_str ) name = name . to_str else raise TypeError , "Can't convert #{name.class} into String." end accu [ name ] = value accu end end | Generates a hash with string keys |
2,560 | def freeze self . normalized_scheme self . normalized_user self . normalized_password self . normalized_userinfo self . normalized_host self . normalized_port self . normalized_authority self . normalized_site self . normalized_path self . normalized_query self . normalized_fragment self . hash super end | Creates a new uri object from component parts . |
2,561 | def normalized_scheme return nil unless self . scheme @normalized_scheme ||= begin if self . scheme =~ / \s \+ \s /i "svn+ssh" . dup else Addressable :: URI . normalize_component ( self . scheme . strip . downcase , Addressable :: URI :: CharacterClasses :: SCHEME ) end end @normalized_scheme . force_encoding ( Encoding :: UTF_8 ) if @normalized_scheme @normalized_scheme end | The scheme component for this URI normalized . |
2,562 | def scheme = ( new_scheme ) if new_scheme && ! new_scheme . respond_to? ( :to_str ) raise TypeError , "Can't convert #{new_scheme.class} into String." elsif new_scheme new_scheme = new_scheme . to_str end if new_scheme && new_scheme !~ / \A \. \+ \- \z /i raise InvalidURIError , "Invalid scheme format: #{new_scheme}" end @scheme = new_scheme @scheme = nil if @scheme . to_s . strip . empty? remove_instance_variable ( :@normalized_scheme ) if defined? ( @normalized_scheme ) remove_composite_values validate ( ) end | Sets the scheme component for this URI . |
2,563 | def user = ( new_user ) if new_user && ! new_user . respond_to? ( :to_str ) raise TypeError , "Can't convert #{new_user.class} into String." end @user = new_user ? new_user . to_str : nil if password != nil @user = EMPTY_STR if @user . nil? end remove_instance_variable ( :@userinfo ) if defined? ( @userinfo ) remove_instance_variable ( :@normalized_userinfo ) if defined? ( @normalized_userinfo ) remove_instance_variable ( :@authority ) if defined? ( @authority ) remove_instance_variable ( :@normalized_user ) if defined? ( @normalized_user ) remove_composite_values validate ( ) end | Sets the user component for this URI . |
2,564 | def normalized_password return nil unless self . password return @normalized_password if defined? ( @normalized_password ) @normalized_password ||= begin if self . normalized_scheme =~ / / && self . password . strip . empty? && ( ! self . user || self . user . strip . empty? ) nil else Addressable :: URI . normalize_component ( self . password . strip , Addressable :: URI :: CharacterClasses :: UNRESERVED ) end end if @normalized_password @normalized_password . force_encoding ( Encoding :: UTF_8 ) end @normalized_password end | The password component for this URI normalized . |
2,565 | def password = ( new_password ) if new_password && ! new_password . respond_to? ( :to_str ) raise TypeError , "Can't convert #{new_password.class} into String." end @password = new_password ? new_password . to_str : nil @password ||= nil @user ||= nil if @password != nil @user = EMPTY_STR if @user . nil? end remove_instance_variable ( :@userinfo ) if defined? ( @userinfo ) remove_instance_variable ( :@normalized_userinfo ) if defined? ( @normalized_userinfo ) remove_instance_variable ( :@authority ) if defined? ( @authority ) remove_instance_variable ( :@normalized_password ) if defined? ( @normalized_password ) remove_composite_values validate ( ) end | Sets the password component for this URI . |
2,566 | def userinfo current_user = self . user current_password = self . password ( current_user || current_password ) && @userinfo ||= begin if current_user && current_password "#{current_user}:#{current_password}" elsif current_user && ! current_password "#{current_user}" end end end | The userinfo component for this URI . Combines the user and password components . |
2,567 | def normalized_userinfo return nil unless self . userinfo return @normalized_userinfo if defined? ( @normalized_userinfo ) @normalized_userinfo ||= begin current_user = self . normalized_user current_password = self . normalized_password if ! current_user && ! current_password nil elsif current_user && current_password "#{current_user}:#{current_password}" . dup elsif current_user && ! current_password "#{current_user}" . dup end end if @normalized_userinfo @normalized_userinfo . force_encoding ( Encoding :: UTF_8 ) end @normalized_userinfo end | The userinfo component for this URI normalized . |
2,568 | def userinfo = ( new_userinfo ) if new_userinfo && ! new_userinfo . respond_to? ( :to_str ) raise TypeError , "Can't convert #{new_userinfo.class} into String." end new_user , new_password = if new_userinfo [ new_userinfo . to_str . strip [ / / , 1 ] , new_userinfo . to_str . strip [ / / , 1 ] ] else [ nil , nil ] end self . password = new_password self . user = new_user remove_instance_variable ( :@authority ) if defined? ( @authority ) remove_composite_values validate ( ) end | Sets the userinfo component for this URI . |
2,569 | def normalized_host return nil unless self . host @normalized_host ||= begin if ! self . host . strip . empty? result = :: Addressable :: IDNA . to_ascii ( URI . unencode_component ( self . host . strip . downcase ) ) if result =~ / \. \. / result = result [ 0 ... - 1 ] end result = Addressable :: URI . normalize_component ( result , CharacterClasses :: HOST ) result else EMPTY_STR . dup end end @normalized_host . force_encoding ( Encoding :: UTF_8 ) if @normalized_host @normalized_host end | The host component for this URI normalized . |
2,570 | def host = ( new_host ) if new_host && ! new_host . respond_to? ( :to_str ) raise TypeError , "Can't convert #{new_host.class} into String." end @host = new_host ? new_host . to_str : nil remove_instance_variable ( :@authority ) if defined? ( @authority ) remove_instance_variable ( :@normalized_host ) if defined? ( @normalized_host ) remove_composite_values validate ( ) end | Sets the host component for this URI . |
2,571 | def authority self . host && @authority ||= begin authority = String . new if self . userinfo != nil authority << "#{self.userinfo}@" end authority << self . host if self . port != nil authority << ":#{self.port}" end authority end end | The authority component for this URI . Combines the user password host and port components . |
2,572 | def normalized_authority return nil unless self . authority @normalized_authority ||= begin authority = String . new if self . normalized_userinfo != nil authority << "#{self.normalized_userinfo}@" end authority << self . normalized_host if self . normalized_port != nil authority << ":#{self.normalized_port}" end authority end if @normalized_authority @normalized_authority . force_encoding ( Encoding :: UTF_8 ) end @normalized_authority end | The authority component for this URI normalized . |
2,573 | def authority = ( new_authority ) if new_authority if ! new_authority . respond_to? ( :to_str ) raise TypeError , "Can't convert #{new_authority.class} into String." end new_authority = new_authority . to_str new_userinfo = new_authority [ / \[ \] / , 1 ] if new_userinfo new_user = new_userinfo . strip [ / / , 1 ] new_password = new_userinfo . strip [ / / , 1 ] end new_host = new_authority . sub ( / \[ \] / , EMPTY_STR ) . sub ( / \[ \] / , EMPTY_STR ) new_port = new_authority [ / \[ \] / , 1 ] end self . password = defined? ( new_password ) ? new_password : nil self . user = defined? ( new_user ) ? new_user : nil self . host = defined? ( new_host ) ? new_host : nil self . port = defined? ( new_port ) ? new_port : nil remove_instance_variable ( :@userinfo ) if defined? ( @userinfo ) remove_instance_variable ( :@normalized_userinfo ) if defined? ( @normalized_userinfo ) remove_composite_values validate ( ) end | Sets the authority component for this URI . |
2,574 | def origin = ( new_origin ) if new_origin if ! new_origin . respond_to? ( :to_str ) raise TypeError , "Can't convert #{new_origin.class} into String." end new_origin = new_origin . to_str new_scheme = new_origin [ / \/ \/ \/ / , 1 ] unless new_scheme raise InvalidURIError , 'An origin cannot omit the scheme.' end new_host = new_origin [ / \/ \/ \/ / , 1 ] unless new_host raise InvalidURIError , 'An origin cannot omit the host.' end new_port = new_origin [ / \[ \] \/ / , 1 ] end self . scheme = defined? ( new_scheme ) ? new_scheme : nil self . host = defined? ( new_host ) ? new_host : nil self . port = defined? ( new_port ) ? new_port : nil self . userinfo = nil remove_instance_variable ( :@userinfo ) if defined? ( @userinfo ) remove_instance_variable ( :@normalized_userinfo ) if defined? ( @normalized_userinfo ) remove_instance_variable ( :@authority ) if defined? ( @authority ) remove_instance_variable ( :@normalized_authority ) if defined? ( @normalized_authority ) remove_composite_values validate ( ) end | Sets the origin for this URI serialized to ASCII as per RFC 6454 section 6 . 2 . This assignment will reset the userinfo component . |
2,575 | def port = ( new_port ) if new_port != nil && new_port . respond_to? ( :to_str ) new_port = Addressable :: URI . unencode_component ( new_port . to_str ) end if new_port . respond_to? ( :valid_encoding? ) && ! new_port . valid_encoding? raise InvalidURIError , "Invalid encoding in port" end if new_port != nil && ! ( new_port . to_s =~ / \d / ) raise InvalidURIError , "Invalid port number: #{new_port.inspect}" end @port = new_port . to_s . to_i @port = nil if @port == 0 remove_instance_variable ( :@authority ) if defined? ( @authority ) remove_instance_variable ( :@normalized_port ) if defined? ( @normalized_port ) remove_composite_values validate ( ) end | Sets the port component for this URI . |
2,576 | def site ( self . scheme || self . authority ) && @site ||= begin site_string = "" . dup site_string << "#{self.scheme}:" if self . scheme != nil site_string << "//#{self.authority}" if self . authority != nil site_string end end | The combination of components that represent a site . Combines the scheme user password host and port components . Primarily useful for HTTP and HTTPS . |
2,577 | def normalized_site return nil unless self . site @normalized_site ||= begin site_string = "" . dup if self . normalized_scheme != nil site_string << "#{self.normalized_scheme}:" end if self . normalized_authority != nil site_string << "//#{self.normalized_authority}" end site_string end @normalized_site . force_encoding ( Encoding :: UTF_8 ) if @normalized_site @normalized_site end | The normalized combination of components that represent a site . Combines the scheme user password host and port components . Primarily useful for HTTP and HTTPS . |
2,578 | def site = ( new_site ) if new_site if ! new_site . respond_to? ( :to_str ) raise TypeError , "Can't convert #{new_site.class} into String." end new_site = new_site . to_str self . scheme = new_site [ / \/ \/ \/ \/ / , 1 ] self . authority = new_site [ / \/ \/ \/ \/ / , 1 ] else self . scheme = nil self . authority = nil end end | Sets the site value for this URI . |
2,579 | def normalized_path @normalized_path ||= begin path = self . path . to_s if self . scheme == nil && path =~ NORMPATH path = path . sub ( ":" , "%2F" ) end result = path . strip . split ( SLASH , - 1 ) . map do | segment | Addressable :: URI . normalize_component ( segment , Addressable :: URI :: CharacterClasses :: PCHAR ) end . join ( SLASH ) result = URI . normalize_path ( result ) if result . empty? && [ "http" , "https" , "ftp" , "tftp" ] . include? ( self . normalized_scheme ) result = SLASH . dup end result end @normalized_path . force_encoding ( Encoding :: UTF_8 ) if @normalized_path @normalized_path end | The path component for this URI normalized . |
2,580 | def path = ( new_path ) if new_path && ! new_path . respond_to? ( :to_str ) raise TypeError , "Can't convert #{new_path.class} into String." end @path = ( new_path || EMPTY_STR ) . to_str if ! @path . empty? && @path [ 0 .. 0 ] != SLASH && host != nil @path = "/#{@path}" end remove_instance_variable ( :@normalized_path ) if defined? ( @normalized_path ) remove_composite_values validate ( ) end | Sets the path component for this URI . |
2,581 | def normalized_query ( * flags ) return nil unless self . query return @normalized_query if defined? ( @normalized_query ) @normalized_query ||= begin modified_query_class = Addressable :: URI :: CharacterClasses :: QUERY . dup modified_query_class . sub! ( "\\&" , "" ) . sub! ( "\\;" , "" ) pairs = ( self . query || "" ) . split ( "&" , - 1 ) pairs . sort! if flags . include? ( :sorted ) component = pairs . map do | pair | Addressable :: URI . normalize_component ( pair , modified_query_class , "+" ) end . join ( "&" ) component == "" ? nil : component end @normalized_query . force_encoding ( Encoding :: UTF_8 ) if @normalized_query @normalized_query end | The query component for this URI normalized . |
2,582 | def query = ( new_query ) if new_query && ! new_query . respond_to? ( :to_str ) raise TypeError , "Can't convert #{new_query.class} into String." end @query = new_query ? new_query . to_str : nil remove_instance_variable ( :@normalized_query ) if defined? ( @normalized_query ) remove_composite_values end | Sets the query component for this URI . |
2,583 | def query_values ( return_type = Hash ) empty_accumulator = Array == return_type ? [ ] : { } if return_type != Hash && return_type != Array raise ArgumentError , "Invalid return type. Must be Hash or Array." end return nil if self . query == nil split_query = self . query . split ( "&" ) . map do | pair | pair . split ( "=" , 2 ) if pair && ! pair . empty? end . compact return split_query . inject ( empty_accumulator . dup ) do | accu , pair | pair [ 0 ] = URI . unencode_component ( pair [ 0 ] ) if pair [ 1 ] . respond_to? ( :to_str ) pair [ 1 ] = URI . unencode_component ( pair [ 1 ] . to_str . gsub ( / \+ / , " " ) ) end if return_type == Hash accu [ pair [ 0 ] ] = pair [ 1 ] else accu << pair end accu end end | Converts the query component to a Hash value . |
2,584 | def query_values = ( new_query_values ) if new_query_values == nil self . query = nil return nil end if ! new_query_values . is_a? ( Array ) if ! new_query_values . respond_to? ( :to_hash ) raise TypeError , "Can't convert #{new_query_values.class} into Hash." end new_query_values = new_query_values . to_hash new_query_values = new_query_values . map do | key , value | key = key . to_s if key . kind_of? ( Symbol ) [ key , value ] end new_query_values . sort! end buffer = "" . dup new_query_values . each do | key , value | encoded_key = URI . encode_component ( key , CharacterClasses :: UNRESERVED ) if value == nil buffer << "#{encoded_key}&" elsif value . kind_of? ( Array ) value . each do | sub_value | encoded_value = URI . encode_component ( sub_value , CharacterClasses :: UNRESERVED ) buffer << "#{encoded_key}=#{encoded_value}&" end else encoded_value = URI . encode_component ( value , CharacterClasses :: UNRESERVED ) buffer << "#{encoded_key}=#{encoded_value}&" end end self . query = buffer . chop end | Sets the query component for this URI from a Hash object . An empty Hash or Array will result in an empty query string . |
2,585 | def request_uri = ( new_request_uri ) if ! new_request_uri . respond_to? ( :to_str ) raise TypeError , "Can't convert #{new_request_uri.class} into String." end if self . absolute? && self . scheme !~ / /i raise InvalidURIError , "Cannot set an HTTP request URI for a non-HTTP URI." end new_request_uri = new_request_uri . to_str path_component = new_request_uri [ / \? \? / , 1 ] query_component = new_request_uri [ / \? \? / , 1 ] path_component = path_component . to_s path_component = ( ! path_component . empty? ? path_component : SLASH ) self . path = path_component self . query = query_component remove_composite_values end | Sets the HTTP request URI for this URI . |
2,586 | def normalized_fragment return nil unless self . fragment return @normalized_fragment if defined? ( @normalized_fragment ) @normalized_fragment ||= begin component = Addressable :: URI . normalize_component ( self . fragment , Addressable :: URI :: CharacterClasses :: FRAGMENT ) component == "" ? nil : component end if @normalized_fragment @normalized_fragment . force_encoding ( Encoding :: UTF_8 ) end @normalized_fragment end | The fragment component for this URI normalized . |
2,587 | def fragment = ( new_fragment ) if new_fragment && ! new_fragment . respond_to? ( :to_str ) raise TypeError , "Can't convert #{new_fragment.class} into String." end @fragment = new_fragment ? new_fragment . to_str : nil remove_instance_variable ( :@normalized_fragment ) if defined? ( @normalized_fragment ) remove_composite_values validate ( ) end | Sets the fragment component for this URI . |
2,588 | def join ( uri ) if ! uri . respond_to? ( :to_str ) raise TypeError , "Can't convert #{uri.class} into String." end if ! uri . kind_of? ( URI ) uri = URI . parse ( uri . to_str ) end if uri . to_s . empty? return self . dup end joined_scheme = nil joined_user = nil joined_password = nil joined_host = nil joined_port = nil joined_path = nil joined_query = nil joined_fragment = nil if uri . scheme != nil joined_scheme = uri . scheme joined_user = uri . user joined_password = uri . password joined_host = uri . host joined_port = uri . port joined_path = URI . normalize_path ( uri . path ) joined_query = uri . query else if uri . authority != nil joined_user = uri . user joined_password = uri . password joined_host = uri . host joined_port = uri . port joined_path = URI . normalize_path ( uri . path ) joined_query = uri . query else if uri . path == nil || uri . path . empty? joined_path = self . path if uri . query != nil joined_query = uri . query else joined_query = self . query end else if uri . path [ 0 .. 0 ] == SLASH joined_path = URI . normalize_path ( uri . path ) else base_path = self . path . dup base_path = EMPTY_STR if base_path == nil base_path = URI . normalize_path ( base_path ) if base_path =~ / \/ / base_path . sub! ( / \/ \/ / , SLASH ) else base_path = EMPTY_STR end if base_path . empty? && self . authority != nil base_path = SLASH end joined_path = URI . normalize_path ( base_path + uri . path ) end joined_query = uri . query end joined_user = self . user joined_password = self . password joined_host = self . host joined_port = self . port end joined_scheme = self . scheme end joined_fragment = uri . fragment return self . class . new ( :scheme => joined_scheme , :user => joined_user , :password => joined_password , :host => joined_host , :port => joined_port , :path => joined_path , :query => joined_query , :fragment => joined_fragment ) end | Joins two URIs together . |
2,589 | def normalize if normalized_scheme == "feed" if self . to_s =~ / \/ \/ / return URI . parse ( self . to_s [ / \/ \/ / , 1 ] ) . normalize end end return self . class . new ( :scheme => normalized_scheme , :authority => normalized_authority , :path => normalized_path , :query => normalized_query , :fragment => normalized_fragment ) end | Returns a normalized URI object . |
2,590 | def defer_validation ( & block ) raise LocalJumpError , "No block given." unless block @validation_deferred = true block . call ( ) @validation_deferred = false validate return nil end | This method allows you to make several changes to a URI simultaneously which separately would cause validation errors but in conjunction are valid . The URI will be revalidated as soon as the entire block has been executed . |
2,591 | def validate return if ! ! @validation_deferred if self . scheme != nil && self . ip_based? && ( self . host == nil || self . host . empty? ) && ( self . path == nil || self . path . empty? ) raise InvalidURIError , "Absolute URI missing hierarchical segment: '#{self.to_s}'" end if self . host == nil if self . port != nil || self . user != nil || self . password != nil raise InvalidURIError , "Hostname not supplied: '#{self.to_s}'" end end if self . path != nil && ! self . path . empty? && self . path [ 0 .. 0 ] != SLASH && self . authority != nil raise InvalidURIError , "Cannot have a relative path with an authority set: '#{self.to_s}'" end if self . path != nil && ! self . path . empty? && self . path [ 0 .. 1 ] == SLASH + SLASH && self . authority == nil raise InvalidURIError , "Cannot have a path with two leading slashes " + "without an authority set: '#{self.to_s}'" end unreserved = CharacterClasses :: UNRESERVED sub_delims = CharacterClasses :: SUB_DELIMS if ! self . host . nil? && ( self . host =~ / \/ \\ \? \# \@ / || ( self . host [ / \[ \] / , 1 ] != nil && self . host [ / \[ \] / , 1 ] !~ Regexp . new ( "^[#{unreserved}#{sub_delims}:]*$" ) ) ) raise InvalidURIError , "Invalid character in host: '#{self.host.to_s}'" end return nil end | Ensures that the URI is valid . |
2,592 | def replace_self ( uri ) instance_variables . each do | var | if instance_variable_defined? ( var ) && var != :@validation_deferred remove_instance_variable ( var ) end end @scheme = uri . scheme @user = uri . user @password = uri . password @host = uri . host @port = uri . port @path = uri . path @query = uri . query @fragment = uri . fragment return self end | Replaces the internal state of self with the specified URI s state . Used in destructive operations to avoid massive code repetition . |
2,593 | def write_attribute ( name , value ) name = name . to_sym if association = @associations [ name ] association . reset end @attributes_before_type_cast [ name ] = value value_casted = TypeCasting . cast_field ( value , self . class . attributes [ name ] ) attributes [ name ] = value_casted end | Write an attribute on the object . Also marks the previous value as dirty . |
2,594 | def set_created_at self . created_at ||= DateTime . now . in_time_zone ( Time . zone ) if Dynamoid :: Config . timestamps end | Automatically called during the created callback to set the created_at time . |
2,595 | def set_updated_at if Dynamoid :: Config . timestamps && ! updated_at_changed? self . updated_at = DateTime . now . in_time_zone ( Time . zone ) end end | Automatically called during the save callback to set the updated_at time . |
2,596 | def reload options = { consistent_read : true } if self . class . range_key options [ :range_key ] = range_value end self . attributes = self . class . find ( hash_key , options ) . attributes @associations . values . each ( & :reset ) self end | An object is equal to another object if their ids are equal . |
2,597 | def evaluate_default_value ( val ) if val . respond_to? ( :call ) val . call elsif val . duplicable? val . dup else val end end | Evaluates the default value given this is used by undump when determining the value of the default given for a field options . |
2,598 | def touch ( name = nil ) now = DateTime . now self . updated_at = now attributes [ name ] = now if name save end | Set updated_at and any passed in field to current DateTime . Useful for things like last_login_at etc . |
2,599 | def save ( _options = { } ) self . class . create_table if new_record? conditions = { unless_exists : [ self . class . hash_key ] } conditions [ :unless_exists ] << range_key if range_key run_callbacks ( :create ) { persist ( conditions ) } else persist end end | Run the callbacks and then persist this object in the datastore . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.