idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
7,100
def check ( token , aud , cid = nil ) synchronize do payload = check_cached_certs ( token , aud , cid ) unless payload if refresh_certs payload = check_cached_certs ( token , aud , cid ) unless payload raise SignatureError , 'Token not verified as issued by Google' end else raise CertificateError , 'Unable to retrieve ...
If it validates returns a hash with the JWT payload from the ID Token . You have to provide an aud value which must match the token s field with that name and will similarly check cid if provided .
7,101
def check_cached_certs ( token , aud , cid ) payload = nil @certs . detect do | key , cert | begin public_key = cert . public_key decoded_token = JWT . decode ( token , public_key , ! ! public_key , { :algorithm => 'RS256' } ) payload = decoded_token . first if payload [ 'azp' ] payload [ 'cid' ] = payload [ 'azp' ] el...
tries to validate the token against each cached cert . Returns the token payload or raises a ValidationError or nil which means none of the certs validated .
7,102
def output_pdf ( html , filename ) args = command ( filename ) invoke = args . join ( ' ' ) IO . popen ( invoke , "wb+" ) do | pdf | pdf . puts ( html ) pdf . close_write pdf . gets ( nil ) end end
Set up options for wkhtmltopdf
7,103
def convert! merged_contents = [ ] @files . each do | file | markup = Markup :: Renderer . new file , @config . remove_front_matter html = convert_image_urls markup . render , file . filename if @config . merge html = "<div class=\"page-break\"></div>#{html}" unless merged_contents . empty? merged_contents << html else...
Initialize the converter with a File
7,104
def convert_image_urls ( html , filename ) dir_string = :: File . dirname ( :: File . expand_path ( filename ) ) html . scan ( / / ) . each do | url | html . gsub! ( url [ 0 ] , :: File . expand_path ( url [ 0 ] , dir_string ) ) unless url [ 0 ] =~ / / end html end
Rewrite relative image urls to absolute
7,105
def output_pdf ( html , filename ) html = add_head html load_stylesheets generate_cover! append_stylesheets html puts @wkhtmltopdf . command ( output_file ( filename ) ) . join ( ' ' ) if @config . debug @wkhtmltopdf . output_pdf html , output_file ( filename ) end
Create the pdf
7,106
def load_stylesheets style = :: File . expand_path ( "../../../config/style.css" , __FILE__ ) @stylesheets << style @stylesheets << stylesheet if :: File . exists? ( stylesheet ) end
Load the stylesheets to pdfkit loads the default and the user selected if any
7,107
def output_file ( file = nil ) if file output_filename = file . name if ! @config . output_filename . nil? && @files . length == 1 output_filename = @config . output_filename end else output_filename = Time . now . to_s . split ( ' ' ) . join ( '_' ) output_filename = @files . last . name if @files . length == 1 || @co...
Generate the name of the output file
7,108
def generate_cover! return unless @config . cover cover_file = MarkupFile . new @config . cover markup = Markup :: Renderer . new cover_file html = "<div class=\"cover\">\n#{markup.render}\n</div>" append_stylesheets ( html ) html = add_head ( html ) @coverfile . write ( html ) @coverfile . close end
Generate cover file if optional cover was given
7,109
def find_events_in_range ( start_min , start_max , options = { } ) formatted_start_min = encode_time ( start_min ) formatted_start_max = encode_time ( start_max ) query = "?timeMin=#{formatted_start_min}&timeMax=#{formatted_start_max}#{parse_options(options)}" event_lookup ( query ) end
Find all of the events associated with this calendar that start in the given time frame . The lower bound is inclusive whereas the upper bound is exclusive . Events that overlap the range are included .
7,110
def find_events_by_extended_properties ( extended_properties , options = { } ) query = "?" + parse_extended_properties ( extended_properties ) + parse_options ( options ) event_lookup ( query ) end
Find all events that match at least one of the specified extended properties .
7,111
def find_events_by_extended_properties_in_range ( extended_properties , start_min , start_max , options = { } ) formatted_start_min = encode_time ( start_min ) formatted_start_max = encode_time ( start_max ) base_query = parse_extended_properties ( extended_properties ) + parse_options ( options ) query = "?" + base_qu...
Find all events that match at least one of the specified extended properties within a given time frame . The lower bound is inclusive whereas the upper bound is exclusive . Events that overlap the range are included .
7,112
def find_or_create_event_by_id ( id , & blk ) event = id ? find_event_by_id ( id ) [ 0 ] : nil if event setup_event ( event , & blk ) elsif id event = Event . new ( id : id , new_event_with_id_specified : true ) setup_event ( event , & blk ) else event = Event . new setup_event ( event , & blk ) end end
Looks for the specified event id . If it is found it updates it s vales and returns it . If the event is no longer on the server it creates a new one with the specified values . Works like the create_event method .
7,113
def save_event ( event ) method = event . new_event? ? :post : :put body = event . use_quickadd? ? nil : event . to_json notifications = "sendNotifications=#{event.send_notifications?}" query_string = if event . use_quickadd? "/quickAdd?#{notifications}&text=#{event.title}" elsif event . new_event? "?#{notifications}" ...
Saves the specified event . This is a callback used by the Event class .
7,114
def parse_options ( options ) options [ :max_results ] ||= 25 options [ :order_by ] ||= 'startTime' options [ :expand_recurring_events ] ||= true query_string = "&orderBy=#{options[:order_by]}" query_string << "&maxResults=#{options[:max_results]}" query_string << "&singleEvents=#{options[:expand_recurring_events]}" qu...
Utility method used to centralize the parsing of common query parameters .
7,115
def parse_extended_properties ( extended_properties ) query_parts = [ ] [ 'shared' , 'private' ] . each do | prop_type | next unless extended_properties [ prop_type ] query_parts << extended_properties [ prop_type ] . map { | key , value | ( prop_type == "shared" ? "sharedExtendedProperty=" : "privateExtendedProperty="...
Utility method used to centralize the parsing of extended query parameters .
7,116
def event_lookup ( query_string = '' ) begin response = send_events_request ( query_string , :get ) parsed_json = JSON . parse ( response . body ) @summary = parsed_json [ 'summary' ] events = Event . build_from_google_feed ( parsed_json , self ) || [ ] return events if events . empty? events . length > 1 ? events : [ ...
Utility method used to centralize event lookup .
7,117
def json_for_query ( calendar_ids , start_time , end_time ) { } . tap { | obj | obj [ :items ] = calendar_ids . map { | id | Hash [ :id , id ] } obj [ :timeMin ] = start_time . utc . iso8601 obj [ :timeMax ] = end_time . utc . iso8601 } . to_json end
Prepare the JSON
7,118
def send ( path , method , content = '' ) uri = BASE_URI + path response = @client . fetch_protected_resource ( :uri => uri , :method => method , :body => content , :headers => { 'Content-type' => 'application/json' } ) check_for_errors ( response ) return response end
Send a request to google .
7,119
def parse_403_error ( response ) case JSON . parse ( response . body ) [ "error" ] [ "message" ] when "Forbidden" then raise ForbiddenError , response . body when "Daily Limit Exceeded" then raise DailyLimitExceededError , response . body when "User Rate Limit Exceeded" then raise UserRateLimitExceededError , response ...
Utility method to centralize handling of 403 errors .
7,120
def all_day? time = ( @start_time . is_a? String ) ? Time . parse ( @start_time ) : @start_time . dup . utc duration % ( 24 * 60 * 60 ) == 0 && time == Time . local ( time . year , time . month , time . day ) end
Returns whether the Event is an all - day event based on whether the event starts at the beginning and ends at the end of the day .
7,121
def to_json attributes = { "summary" => title , "visibility" => visibility , "transparency" => transparency , "description" => description , "location" => location , "start" => time_or_all_day ( start_time ) , "end" => time_or_all_day ( end_time ) , "reminders" => reminders_attributes , "guestsCanInviteOthers" => guest...
Google JSON representation of an event object .
7,122
def attendees_attributes return { } unless @attendees attendees = @attendees . map do | attendee | attendee . select { | k , _v | [ 'displayName' , 'email' , 'responseStatus' ] . include? ( k ) } end { "attendees" => attendees } end
Hash representation of attendees
7,123
def local_timezone_attributes tz = Time . now . getlocal . zone tz_name = TimezoneParser :: getTimezones ( tz ) . last { "timeZone" => tz_name } end
Hash representation of local timezone
7,124
def recurrence_attributes return { } unless is_recurring_event? @recurrence [ :until ] = @recurrence [ :until ] . strftime ( '%Y%m%dT%H%M%SZ' ) if @recurrence [ :until ] rrule = "RRULE:" + @recurrence . collect { | k , v | "#{k}=#{v}" } . join ( ';' ) . upcase @recurrence [ :until ] = Time . parse ( @recurrence [ :unti...
Hash representation of recurrence rules for repeating events
7,125
def fetch_entries response = @connection . send ( "/users/me/calendarList" , :get ) return nil if response . status != 200 || response . body . empty? CalendarListEntry . build_from_google_feed ( JSON . parse ( response . body ) , @connection ) end
Setup and connect to the user s list of Google Calendars .
7,126
def save data = dump data = Sidekiq . dump_json ( data ) Sidekiq . redis do | conn | conn . multi do conn . setex ( status_key , self . ttl , data ) conn . zadd ( self . class . statuses_key , Time . now . to_f . to_s , self . jid ) end end end
Save current container attribute values to redis
7,127
def delete Sidekiq . redis do | conn | conn . multi do conn . del ( status_key ) conn . zrem ( self . class . kill_key , self . jid ) conn . zrem ( self . class . statuses_key , self . jid ) end end end
Delete current container data from redis
7,128
def kill self . status = 'killed' Sidekiq . redis do | conn | conn . multi do save conn . zrem ( self . class . kill_key , self . jid ) end end end
Reflect the fact that a job has been killed in redis
7,129
def load ( data ) data = DEFAULTS . merge ( data ) @args , @worker , @queue = data . values_at ( 'args' , 'worker' , 'queue' ) @status , @at , @total , @message = data . values_at ( 'status' , 'at' , 'total' , 'message' ) @payload = data [ 'payload' ] @last_updated_at = data [ 'last_updated_at' ] && Time . at ( data [ ...
Merge - in given data to the current container
7,130
def dump { 'args' => self . args , 'worker' => self . worker , 'queue' => self . queue , 'status' => self . status , 'at' => self . at , 'total' => self . total , 'message' => self . message , 'payload' => self . payload , 'last_updated_at' => Time . now . to_i } end
Dump current container attribute values to json - serializable hash
7,131
def send_conversation_message ( from , to , params = { } ) ConversationMessage . new ( conversation_request ( :post , 'send' , params . merge ( { :from => from , :to => to , } ) ) ) end
Conversations Send a conversation message
7,132
def start_conversation ( to , channelId , params = { } ) Conversation . new ( conversation_request ( :post , 'conversations/start' , params . merge ( { :to => to , :channelId => channelId , } ) ) ) end
Start a conversation
7,133
def message_create ( originator , recipients , body , params = { } ) recipients = recipients . join ( ',' ) if recipients . kind_of? ( Array ) Message . new ( request ( :post , 'messages' , params . merge ( { :originator => originator . to_s , :body => body . to_s , :recipients => recipients } ) ) ) end
Create a new message .
7,134
def voice_message_create ( recipients , body , params = { } ) recipients = recipients . join ( ',' ) if recipients . kind_of? ( Array ) VoiceMessage . new ( request ( :post , 'voicemessages' , params . merge ( { :recipients => recipients , :body => body . to_s } ) ) ) end
Create a new voice message .
7,135
def method_missing ( method_sym , * args , & block ) if method_sym . to_s =~ / \d / generate_n_words ( $1 . to_i ) elsif method_sym . to_s =~ / \d / generate_n_sentences ( $1 . to_i ) else super end end
Dynamically call generate_n_words or generate_n_sentences if an Int is substituted for the n in the method call .
7,136
def run ( timeout = nil ) raise RuntimeError , "no watchers for this loop" if @watchers . empty? @running = true while @running and not @active_watchers . zero? run_once ( timeout ) end @running = false end
Run the event loop and dispatch events back to Ruby . If there are no watchers associated with the event loop it will return immediately . Otherwise run will continue blocking and making event callbacks to watchers until all watchers associated with the loop have been disabled or detached . The loop may be explicitly s...
7,137
def on_readable begin on_read @_io . read_nonblock ( INPUT_SIZE ) rescue Errno :: EAGAIN , Errno :: EINTR return rescue SystemCallError , EOFError , IOError , SocketError close end end
Read from the input buffer and dispatch to on_read
7,138
def on_writable begin @_write_buffer . write_to ( @_io ) rescue Errno :: EINTR return rescue SystemCallError , IOError , SocketError return close end if @_write_buffer . empty? disable_write_watcher on_write_complete end end
Write the contents of the output buffer
7,139
def send_request nameserver = @nameservers . shift @nameservers << nameserver begin @socket . send request_message , 0 , @nameservers . first , DNS_PORT rescue Errno :: EHOSTUNREACH end end
Send a request to the DNS server
7,140
def on_readable datagram = nil begin datagram = @socket . recvfrom_nonblock ( DATAGRAM_SIZE ) . first rescue Errno :: ECONNREFUSED end address = response_address datagram rescue nil address ? on_success ( address ) : on_failure detach end
Called by the subclass when the DNS response is available
7,141
def preinitialize ( addr , port , * args ) @_write_buffer = :: IO :: Buffer . new @remote_host , @remote_addr , @remote_port = addr , addr , port @_resolver = TCPConnectResolver . new ( self , addr , port , * args ) end
Called by precreate during asyncronous DNS resolution
7,142
def connect ( host , port , connection_name = nil , * initializer_args , & block ) if block_given? initializer_args . unshift connection_name if connection_name klass = Class . new Cool . io :: TCPSocket connection_builder = ConnectionBuilder . new klass connection_builder . instance_eval ( & block ) else raise Argumen...
Connect to the given host and port using the given connection class
7,143
def [] ( connection_name ) class_name = connection_name . to_s . split ( '_' ) . map { | s | s . capitalize } . join begin Coolio :: Connections . const_get class_name rescue NameError raise NameError , "No connection type registered for #{connection_name.inspect}" end end
Look up a connection class by its name
7,144
def safe_read ( path ) path = File . expand_path ( path ) name = File . basename ( path , '.*' ) contents = File . read ( path ) [ name , contents ] rescue Errno :: EACCES raise Error :: InsufficientFilePermissions . new ( path : path ) rescue Errno :: ENOENT raise Error :: FileNotFound . new ( path : path ) end
Safely read the contents of a file on disk catching any permission errors or not found errors and raising a nicer exception .
7,145
def fast_collect ( collection , & block ) collection . map do | item | Thread . new do Thread . current [ :result ] = block . call ( item ) end end . collect do | thread | thread . join thread [ :result ] end end
Quickly iterate over a collection using native Ruby threads preserving the original order of elements and being all thread - safe and stuff .
7,146
def save! validate! response = if new_resource? self . class . post ( to_json , _prefix ) else self . class . put ( id , to_json , _prefix ) end response . each do | key , value | update_attribute ( key , value ) if attribute? ( key ) end true end
Commit the resource and any changes to the remote Chef Server . Any errors will raise an exception in the main thread and the resource will not be committed back to the Chef Server .
7,147
def update_attribute ( key , value ) unless attribute? ( key . to_sym ) raise Error :: UnknownAttribute . new ( attribute : key ) end _attributes [ key . to_sym ] = value end
Update a single attribute in the attributes hash .
7,148
def validate! unless valid? sentence = errors . full_messages . join ( ', ' ) raise Error :: InvalidResource . new ( errors : sentence ) end true end
Run all of this resource s validations raising an exception if any validations fail .
7,149
def valid? errors . clear validators . each do | validator | validator . validate ( self ) end errors . empty? end
Determine if the current resource is valid . This relies on the validations defined in the schema at initialization .
7,150
def diff diff = { } remote = self . class . fetch ( id , _prefix ) || self . class . new ( { } , _prefix ) remote . _attributes . each do | key , value | unless _attributes [ key ] == value diff [ key ] = { local : _attributes [ key ] , remote : value } end end diff end
Calculate a differential of the attributes on the local resource with it s remote Chef Server counterpart .
7,151
def to_hash { } . tap do | hash | _attributes . each do | key , value | hash [ key ] = value . respond_to? ( :to_hash ) ? value . to_hash : value end end end
The hash representation of this resource . All attributes are serialized and any values that respond to + to_hash + are also serialized .
7,152
def inspect attrs = ( _prefix ) . merge ( _attributes ) . map do | key , value | if value . is_a? ( String ) "#{key}: #{Util.truncate(value, length: 50).inspect}" else "#{key}: #{value.inspect}" end end "#<#{self.class.classname} #{attrs.join(', ')}>" end
Custom inspect method for easier readability .
7,153
def validate ( resource ) value = resource . _attributes [ attribute ] if value && ! types . any? { | type | value . is_a? ( type ) } short_name = type . to_s . split ( '::' ) . last resource . errors . add ( attribute , "must be a kind of #{short_name}" ) end end
Overload the super method to capture the type attribute in the options hash .
7,154
def digest_io ( io ) digester = Digest :: SHA1 . new while buffer = io . read ( 1024 ) digester . update ( buffer ) end io . rewind Base64 . encode64 ( digester . digest ) end
Hash the given object .
7,155
def fetch ( id ) return nil unless exists? ( id ) cached ( id ) { klass . from_url ( get ( id ) , prefix ) } end
Fetch a specific resource in the collection by id .
7,156
def each ( & block ) collection . each do | id , url | object = cached ( id ) { klass . from_url ( url , prefix ) } block . call ( object ) if block end end
The custom iterator for looping over each object in this collection . For more information please see the + Enumerator + module in Ruby core .
7,157
def inspect objects = collection . map { | id , _ | cached ( id ) || klass . new ( klass . schema . primary_key => id ) } . map { | object | object . to_s } "#<#{self.class.name} [#{objects.join(', ')}]>" end
The detailed string representation of this collection proxy .
7,158
def add_request_headers ( request ) log . info "Adding request headers..." headers = { 'Accept' => 'application/json' , 'Content-Type' => 'application/json' , 'Connection' => 'keep-alive' , 'Keep-Alive' => '30' , 'User-Agent' => user_agent , 'X-Chef-Version' => '11.4.0' , } headers . each do | key , value | log . debug...
Adds the default headers to the request object .
7,159
def attribute ( key , options = { } ) if primary_key = options . delete ( :primary ) @primary_key = key . to_sym end @attributes [ key ] = options . delete ( :default ) options . each do | validation , options | if options @validators << Validator . find ( validation ) . new ( key , options ) end end key end
DSL method for defining an attribute .
7,160
def original_number if reverted_from . nil? number else version = versioned . versions . at ( reverted_from ) version . nil? ? 1 : version . original_number end end
Returns the original version number that this version was .
7,161
def update_version return create_version unless v = versions . last v . modifications_will_change! v . update_attribute ( :modifications , v . changes . append_changes ( version_changes ) ) reset_version_changes reset_version end
Updates the last version s changes by appending the current version changes .
7,162
def reset_to! ( value ) if saved = skip_version { revert_to! ( value ) } versions . send ( :delete , versions . after ( value ) ) reset_version end saved end
Adds the instance methods required to reset an object to a previous version . Similar to + revert_to! + the + reset_to! + method reverts an object to a previous version only instead of creating a new record in the version history + reset_to! + deletes all of the version history that occurs after the version reverted to...
7,163
def tag_version ( tag ) v = versions . at ( version ) || versions . build ( :number => 1 ) t = v . tag! ( tag ) versions . reload t end
Adds an instance method which allows version tagging through the parent object . Accepts a single string argument which is attached to the version record associated with the current version number of the parent object .
7,164
def revert_to ( value ) to_number = versions . number_at ( value ) changes_between ( version , to_number ) . each do | attribute , change | write_attribute ( attribute , change . last ) end reset_version ( to_number ) end
Accepts a value corresponding to a specific version record builds a history of changes between that version and the current version and then iterates over that history updating the object s attributes until the it s reverted to its prior state .
7,165
def zero last_event = stack . events . first @last_processed_event_id = last_event . id unless last_event . nil? nil rescue Aws :: CloudFormation :: Errors :: ValidationError end
Consume all new events
7,166
def on_event ( event_handler = nil , & block ) event_handler ||= block raise ArgumentError , "no event_handler provided" if event_handler . nil? @event_handler = event_handler end
Register a handler for reporting of stack events .
7,167
def create_or_update ( options ) options = options . dup if ( template_data = options . delete ( :template ) ) options [ :template_body ] = MultiJson . dump ( template_data ) end if ( parameters = options [ :parameters ] ) options [ :parameters ] = Parameters . new ( parameters ) . to_a end if ( tags = options [ :tags ...
Create or update the stack .
7,168
def modify_stack ( target_status , failure_message , & block ) if wait? status = modify_stack_synchronously ( & block ) raise StackUpdateError , failure_message unless target_status === status status else modify_stack_asynchronously ( & block ) end end
Execute a block to modify the stack .
7,169
def modify_stack_synchronously watch do | watcher | handling_cf_errors do yield end loop do watcher . each_new_event ( & event_handler ) status = self . status logger . debug ( "stack_status=#{status}" ) return status if status . nil? || status =~ / / sleep ( wait_poll_interval ) end end end
Execute a block reporting stack events until the stack is stable .
7,170
def extract_hash ( collection_name , key_name , value_name ) handling_cf_errors do { } . tap do | result | cf_stack . public_send ( collection_name ) . each do | item | key = item . public_send ( key_name ) value = item . public_send ( value_name ) result [ key ] = value end end end end
Extract data from a collection attribute of the stack .
7,171
def create ( options = { } ) options = options . dup options [ :stack_name ] = stack . name options [ :change_set_name ] = name options [ :change_set_type ] = stack . exists? ? "UPDATE" : "CREATE" force = options . delete ( :force ) options [ :template_body ] = MultiJson . dump ( options . delete ( :template ) ) if opt...
Create the change - set .
7,172
def static_rules cannot :manage , User can :read , Comment can :read , any ( / / ) can :read , Article can :write , any ( / / ) author_of ( Article ) do | author | author . can :manage end author_of ( Post ) do | author | author . can :manage end author_of ( Comment ) do | author | author . can :manage end end
should take user and options args here ???
7,173
def call ( req , args = { } , & block ) oauth_args = args . delete ( :oauth ) || { } http_response = @oauth_consumer . post_form ( REST_PATH , @access_secret , { :oauth_token => @access_token } . merge ( oauth_args ) , build_args ( args , req ) ) process_response ( req , http_response . body ) end
This is the central method . It does the actual request to the flickr server .
7,174
def get_access_token ( token , secret , verify ) access_token = @oauth_consumer . access_token ( FLICKR_OAUTH_ACCESS_TOKEN , secret , :oauth_token => token , :oauth_verifier => verify ) @access_token , @access_secret = access_token [ 'oauth_token' ] , access_token [ 'oauth_token_secret' ] access_token end
Get an oauth access token .
7,175
def capture_erb ( * args , & block ) buffer = _erb_buffer ( block . binding ) rescue nil if buffer . nil? block . call ( * args ) else pos = buffer . length block . call ( * args ) data = buffer [ pos .. - 1 ] buffer [ pos .. - 1 ] = "" data end end
This method is used to capture content from an ERB filter evaluation . It is useful to helpers that need to process chunks of data during ERB filter processing .
7,176
def dump_content_to_file_debug_text_erb ( content ) return content unless config . verbose? outname = "#{outdir}/#{@name}.debug.text.erb" puts " Dumping content before erb merge to #{outname}..." File . open ( outname , 'w' ) do | f | f . write ( content ) end content end
use it to dump content before erb merge
7,177
def ltree ( column = :path , options : { cascade : true } ) cattr_accessor :ltree_path_column self . ltree_path_column = column if options [ :cascade ] after_update :cascade_update after_destroy :cascade_destroy end extend ClassMethods include InstanceMethods end
Initialzie ltree for active model
7,178
def regenerate_rubocop_todo! before_version = scan_rubocop_version_in_rubocop_todo_file pull_request . commit! ':police_car: regenerate rubocop todo' do Rubocop :: Command . new . auto_gen_config end after_version = scan_rubocop_version_in_rubocop_todo_file [ before_version , after_version ] end
Re - generate . rubocop_todo . yml and run git commit .
7,179
def rubocop_challenge! ( before_version , after_version ) Rubocop :: Challenge . exec ( options [ :file_path ] , options [ :mode ] ) . tap do | rule | pull_request . commit! ":police_car: #{rule.title}" end rescue Errors :: NoAutoCorrectableRule => e create_another_pull_request! ( before_version , after_version ) raise...
Run rubocop challenge .
7,180
def add_to_ignore_list_if_challenge_is_incomplete ( rule ) return unless auto_correct_incomplete? ( rule ) pull_request . commit! ':police_car: add the rule to the ignore list' do config_editor = Rubocop :: ConfigEditor . new config_editor . add_ignore ( rule ) config_editor . save end color_puts DESCRIPTION_THAT_CHALL...
If still exist the rule after a challenge the rule regard as cannot correct automatically then add to ignore list and it is not chosen as target rule from next time .
7,181
def auto_correct_incomplete? ( rule ) todo_reader = Rubocop :: TodoReader . new ( options [ :file_path ] ) todo_reader . all_rules . include? ( rule ) end
Checks the challenge result . If the challenge is successed the rule should not exist in the . rubocop_todo . yml after regenerate .
7,182
def create_rubocop_challenge_pr! ( rule , template_file_path = nil ) create_pull_request! ( title : "#{rule.title}-#{timestamp}" , body : Github :: PrTemplate . new ( rule , template_file_path ) . generate , labels : labels ) end
Creates a pull request for the Rubocop Challenge
7,183
def create_regenerate_todo_pr! ( before_version , after_version ) create_pull_request! ( title : "Re-generate .rubocop_todo.yml with RuboCop v#{after_version}" , body : generate_pull_request_body ( before_version , after_version ) , labels : labels ) end
Creates a pull request which re - generate . rubocop_todo . yml with new version RuboCop .
7,184
def print_topics ( words_per_topic = 10 ) raise 'No vocabulary loaded.' unless @vocab beta . each_with_index do | topic , topic_num | indices = topic . zip ( ( 0 ... @vocab . size ) . to_a ) . sort { | x | x [ 0 ] } . map { | _i , j | j } . reverse [ 0 ... words_per_topic ] puts "Topic #{topic_num}" puts "\t#{indices.m...
Visualization method for printing out the top + words_per_topic + words for each topic .
7,185
def to_s outp = [ 'LDA Settings:' ] outp << ' Initial alpha: %0.6f' . format ( init_alpha ) outp << ' # of topics: %d' . format ( num_topics ) outp << ' Max iterations: %d' . format ( max_iter ) outp << ' Convergence: %0.6f' . format ( convergence ) outp << 'EM max iterations: %d' . format ( em_max_iter ...
String representation displaying current settings .
7,186
def super_delegate ( * args , & block ) method_name = name_of_calling_method ( caller ) owner = args . first || method_delegate ( method_name ) super_delegate_method = unbound_method_from_next_delegate ( method_name , owner ) if super_delegate_method . arity == 0 super_delegate_method . bind ( self ) . call else super_...
Call the method of the same name defined in the next delegate stored in your object
7,187
def merch_month merch_year = calendar . merch_year_from_date ( date ) @merch_month ||= ( 1 .. 12 ) . detect do | num | calendar . end_of_month ( merch_year , num ) >= date && date >= calendar . start_of_month ( merch_year , num ) end end
This returns the merch month number for a date Month 1 is Feb for the retail calendar Month 1 is August for the fiscal calendar
7,188
def end_of_year ( year ) year_end = Date . new ( ( year + 1 ) , Date :: MONTHNAMES . index ( LAST_MONTH_OF_THE_YEAR ) , LAST_DAY_OF_THE_YEAR ) wday = ( year_end . wday + 1 ) % 7 if wday > 3 year_end += 7 - wday else year_end -= wday end year_end end
The the first date of the retail year
7,189
def start_of_month ( year , merch_month ) start = start_of_year ( year ) + ( ( merch_month - 1 ) / 3 ) . to_i * 91 case merch_month when * FOUR_WEEK_MONTHS start = start + 28 when * FIVE_WEEK_MONTHS start = start + 63 end start end
The starting date of the given merch month
7,190
def start_of_quarter ( year , quarter ) case quarter when QUARTER_1 start_of_month ( year , 1 ) when QUARTER_2 start_of_month ( year , 4 ) when QUARTER_3 start_of_month ( year , 7 ) when QUARTER_4 start_of_month ( year , 10 ) else raise "invalid quarter" end end
Return the starting date for a particular quarter
7,191
def end_of_quarter ( year , quarter ) case quarter when QUARTER_1 end_of_month ( year , 3 ) when QUARTER_2 end_of_month ( year , 6 ) when QUARTER_3 end_of_month ( year , 9 ) when QUARTER_4 end_of_month ( year , 12 ) else raise "invalid quarter" end end
Return the ending date for a particular quarter
7,192
def merch_year_from_date ( date ) date_end_of_year = end_of_year ( date . year ) date_start_of_year = start_of_year ( date . year ) if date < date_start_of_year date . year - 1 else date . year end end
Given any julian date it will return what retail year it belongs to
7,193
def merch_months_in ( start_date , end_date ) merch_months = [ ] prev_date = start_date - 2 date = start_date while date <= end_date do date = MerchCalendar . start_of_month ( date . year , merch_month : date . month ) next if prev_date == date merch_months . push ( date ) prev_date = date date += 14 end merch_months e...
Given beginning and end dates it will return an array of Retail Month s Start date
7,194
def weeks_for_month ( year , month_param ) merch_month = get_merch_month_param ( month_param ) start_date = start_of_month ( year , merch_month ) weeks = ( end_of_month ( year , merch_month ) - start_date + 1 ) / 7 ( 1 .. weeks ) . map do | week_num | week_start = start_date + ( ( week_num - 1 ) * 7 ) week_end = week_s...
Returns an array of Merch Weeks that pertains to the Julian Month of a Retail Year
7,195
def merch_year_from_date ( date ) if end_of_year ( date . year ) >= date return date . year else return date . year + 1 end end
Given any julian date it will return what Fiscal Year it belongs to
7,196
def merch_months_in ( start_date , end_date ) merch_months_combos = merch_year_and_month_from_dates ( start_date , end_date ) merch_months_combos . map { | merch_month_combo | start_of_month ( merch_month_combo [ 0 ] , merch_month_combo [ 1 ] ) } end
Given beginning and end dates it will return an array of Fiscal Month s Start date
7,197
def merch_year_and_month_from_dates ( start_date , end_date ) merch_months = [ ] middle_of_start_month = Date . new ( start_date . year , start_date . month , 14 ) middle_of_end_month = Date . new ( end_date . year , end_date . month , 14 ) date = middle_of_start_month while date <= middle_of_end_month do merch_months ...
Returns an array of merch_months and year combination that falls in and between the start and end date
7,198
def start_of_week ( year , month , week ) retail_calendar . start_of_week ( year , julian_to_merch ( month ) , week ) end
The start date of the week
7,199
def end_of_week ( year , month , week ) retail_calendar . end_of_week ( year , julian_to_merch ( month ) , week ) end
The end date of the week