idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
21,500
def [] ( key ) case key when Element , MissingElement raise ArgumentError , "wrong type" unless key . type == self key when Symbol elements_by_name . fetch ( key ) else key = normalize_value ( key ) elements_by_value . fetch ( key ) { MissingElement . new key , self } end end
Initialize takes a single hash of name to value .
21,501
def unshorten ( url , opts = { } ) options = { max_level : opts . fetch ( :max_level , 10 ) , timeout : opts . fetch ( :timeout , 2 ) , use_cache : opts . fetch ( :use_cache , true ) } url = ( url =~ / /i ) ? url : "http://#{url}" __unshorten__ ( url , options ) end
Unshorten a shortened URL .
21,502
def format_string ( message , max_characters = 80 ) max_characters = 5 if max_characters < 5 m = message . gsub ( / \r \n \n \r /m , ";" ) return ( m [ 0 .. max_characters - 4 ] + "..." ) if m . size > max_characters return m end
replaces CR LF CRLF with ; and cut s string to requied length by adding ... if string would be longer
21,503
def analyze ( text , features = default_features ) if text . nil? || features . nil? raise ArgumentError . new ( NIL_ARGUMENT_ERROR ) end response = self . class . post ( "#{@url}/analyze?version=#{@version}" , body : { text : text . to_s , features : features } . to_json , basic_auth : auth , headers : { "Content-Type" => CONTENT_TYPE } ) response . parsed_response end
Initialize instance variables for use later Sends a POST request to analyze text with certain features enabled
21,504
def default_features { entities : { emotion : true , sentiment : true , limit : 2 } , keywords : { emotion : true , sentiment : true , limit : 2 } } end
Default features if no features specified
21,505
def visit raise :: CapybaraObjects :: Exceptions :: MissingUrl unless url . present? page . visit url validate! self end
Visits the pre configured URL to make this page available
21,506
def curl puts "fetching #{@uri.to_s}" . green . on_black start_time = Time . now begin c = @c c . url = @uri . to_s c . perform end_time = Time . now case c . response_code when 200 then page = Page . new ( @uri , response_code : c . response_code , response_head : c . header_str , response_body : c . body_str , response_time : ( ( end_time - start_time ) * 1000 ) . round , crawled_time : ( Time . now . to_f * 1000 ) . to_i ) when 300 .. 307 then page = Page . new ( @uri , response_code : c . response_code , response_head : c . header_str , response_body : c . body_str , response_time : ( ( end_time - start_time ) * 1000 ) . round , redirect_url : c . redirect_url ) when 404 then page = Page . new ( @uri , response_code : c . response_code , response_time : ( ( end_time - start_time ) * 1000 ) . round ) end rescue Exception => e puts e . inspect puts e . backtrace end end
Fetch a page from the given url using libcurl
21,507
def validate_each ( record , attribute , value ) unless value . blank? record . errors [ attribute ] << ( options [ :message ] || 'is not a valid email address' ) unless value =~ VALID_EMAIL_REGEX end end
Validates attributes to determine if they contain valid email addresses .
21,508
def interpolate ( item = self , parent = nil ) item = render item , parent item . is_a? ( Hash ) ? :: Mash . new ( item ) : item end
Interpolate provides a means of externally using Ruby string interpolation mechinism .
21,509
def render ( item , parent = nil ) item = item . to_hash if item . respond_to? ( :to_hash ) if item . is_a? ( Hash ) item = item . inject ( { } ) { | memo , ( k , v ) | memo [ sym ( k ) ] = v ; memo } item . inject ( { } ) { | memo , ( k , v ) | memo [ sym ( k ) ] = render ( v , item ) ; memo } elsif item . is_a? ( Array ) item . map { | i | render ( i , parent ) } elsif item . is_a? ( String ) item % parent rescue item else item end end
Provides recursive interpolation of node objects using standard string interpolation methods .
21,510
def execute ( result ) if ActiveRecord :: Base . connection . open_transactions >= 1 super ( result ) else result . info ( 'start_transaction' ) ActiveRecord :: Base . transaction do super ( result ) if result . ok? result . info ( 'end_transaction' ) else result . info ( 'rollback_transaction' ) raise ActiveRecord :: Rollback , 'rollback transaction' end end end end
starts a transaction only if we are not already within one .
21,511
def element_collection ( collection_name , * find_args ) build collection_name , * find_args do define_method collection_name . to_s do | * runtime_args , & element_block | self . class . raise_if_block ( self , collection_name . to_s , ! element_block . nil? ) page . all ( * find_args ) end end end
why define this method? if we use the elements method directly it will be conflicted with RSpec . Mather . BuiltIn . All . elements . I have not found one good method to solve the confliction .
21,512
def define_elements_js ( model_class , excluded_props = [ ] ) attributes = model_class . new . attributes . keys attributes . each do | attri | unless excluded_props . include? attri selector = "#" + attri element attri , selector end end end
instead of the rails traditional form in js mode there is no prefix before the element name
21,513
def range_for column_name , field_name column = @@bitfields [ column_name ] raise ArgumentError , "Unknown column for bitfield: #{column_name}" if column . nil? return column [ field_name ] if column [ field_name ] raise ArugmentError , "Unknown field: #{field_name} for column #{column_name}" end
Returns the column by name
21,514
def reset_mask_for column_name , * fields fields = bitfields if fields . empty? max = bitfield_max ( column_name ) ( 0 .. max ) . sum { | i | 2 ** i } - only_mask_for ( column_name , * fields ) end
Returns a reset mask for a list of fields
21,515
def increment_mask_for column_name , * fields fields = bitfields if fields . empty? column = @@bitfields [ column_name ] raise ArgumentError , "Unknown column for bitfield: #{column_name}" if column . nil? fields . sum do | field_name | raise ArugmentError , "Unknown field: #{field_name} for column #{column_name}" if column [ field_name ] . nil? 2 ** ( bitfield_max ( column_name ) - column [ field_name ] . last ) end end
Returns an increment mask for a list of fields
21,516
def only_mask_for column_name , * fields fields = bitfields if fields . empty? column = @@bitfields [ column_name ] max = bitfield_max ( column_name ) raise ArgumentError , "Unknown column for bitfield: #{column_name}" if column . nil? column . sum do | field_name , range | fields . include? ( field_name ) ? range . invert ( max ) . sum { | i | 2 ** i } : 0 end end
Returns an only mask for a list of fields
21,517
def count_by column_name , field inc = increment_mask_for column_name , field only = only_mask_for column_name , field sql = arel_table . project ( "count(#{primary_key}) as #{field}_count, (#{column_name} & #{only})/#{inc} as #{field}" ) . group ( field ) . to_sql connection . send :select , sql , 'AREL' end
Counts resources grouped by a bitfield
21,518
def reset_bitfields column_name , * fields mask = self . class . reset_mask_for column_name , * fields self [ column_name ] = self [ column_name ] & mask save end
Sets one or more bitfields to 0 within a column
21,519
def increment_bitfields column_name , * fields mask = self . class . increment_mask_for column_name , * fields self [ column_name ] = self [ column_name ] += mask save end
Increases one or more bitfields by 1 value
21,520
def connect_current_user = ( user ) @connect_current_user = user || User . anonymous @app_current_user = user_provider . connect_user_to_app_user ( @connect_current_user ) if @connect_current_user . is_anonymous? @session [ :user_id ] = nil @cookies . delete ( :secure_user_id ) else @session [ :user_id ] = @connect_current_user . id @cookies . signed [ :secure_user_id ] = { secure : true , value : "secure#{@connect_current_user.id}" } end @connect_current_user end
Sets the current connect user updates the app user and also updates the session and cookie state .
21,521
def register_format ( name , processor ) unless processor . new . is_a? ( Vidibus :: Encoder :: Base ) raise ( ArgumentError , 'The processor must inherit Vidibus::Encoder::Base' ) end @formats ||= { } @formats [ name ] = processor end
Register a new encoder format .
21,522
def read_conf_file conf = { } if File . exists? ( CONF_PATH ) && File . size? ( CONF_PATH ) YAML . load_file ( CONF_PATH ) . each do | key , value | if VALID_KEYS . include? key conf [ key ] = value else say "Invalid configuration key: #{key}" end end end conf end
Read the config options from RComp s configuration file
21,523
def rebase ( image ) new_path = @router . baseline_dir ( image . name ) create_path_for_file ( new_path ) FileUtils . move ( image . path , new_path ) Monet :: Image . new ( new_path ) end
returns a new image for the moved image
21,524
def save ( * args ) return false unless valid? ActiveRecord :: Base . transaction do begin associates . all? do | associate | send ( associate . name ) . send ( :save! , * args ) end rescue ActiveRecord :: RecordInvalid false end end end
Persists each associated model
21,525
def connections ( * roles ) if roles . empty? @connections else @connections . select { | c | c . roles . empty? or ! ( c . roles & roles ) . empty? } end end
return all connections or those matching list of roles ; connections with no roles match all or find intersection with roles list
21,526
def extract_data item , text_limit : 1200 link = item . link desc = item . description title = item . title . force_encoding ( 'UTF-8' ) case when desc . match ( / \| \| /m ) img , terms , text = desc . split ( '|' ) when desc . include? ( '|' ) img , text = desc . split ( '|' ) terms = nil when desc . match ( / \" / ) img = desc . match ( / \" / ) [ 1 ] text = desc terms = nil else img , terms , text = nil , nil , desc end categories = if terms terms . split ( / \n / ) . select { | g | g . match / / } . map { | c | c . match ( / \n / ) [ 1 ] } else [ ] end short_text = strip_tags ( text ) [ 0 .. text_limit ] short_text = short_text . gsub ( / \A \s / , "" ) . gsub ( / \n / , "\n\n" ) short_text = short_text [ 0 .. short_text . rindex ( / \. \n / ) ] [ title , link , img , short_text , categories ] end
Extract news data from a feed item
21,527
def start_pairing @gtv = GoogleAnymote :: TV . new ( @cert , host , 9551 + 1 ) send_message ( pair , OuterMessage :: MessageType :: MESSAGE_TYPE_PAIRING_REQUEST ) options = Options . new encoding = Options :: Encoding . new encoding . type = Options :: Encoding :: EncodingType :: ENCODING_TYPE_HEXADECIMAL encoding . symbol_length = 4 options . input_encodings << encoding options . output_encodings << encoding send_message ( options , OuterMessage :: MessageType :: MESSAGE_TYPE_OPTIONS ) config = Configuration . new encoding = Options :: Encoding . new encoding . type = Options :: Encoding :: EncodingType :: ENCODING_TYPE_HEXADECIMAL config . encoding = encoding config . encoding . symbol_length = 4 config . client_role = Options :: RoleType :: ROLE_TYPE_INPUT outer = send_message ( config , OuterMessage :: MessageType :: MESSAGE_TYPE_CONFIGURATION ) raise PairingFailed , outer . status unless OuterMessage :: Status :: STATUS_OK == outer . status end
Initializes the Pair class
21,528
def complete_pairing ( code ) secret = Secret . new secret . secret = encode_hex_secret ( code ) outer = send_message ( secret , OuterMessage :: MessageType :: MESSAGE_TYPE_SECRET ) @gtv . ssl_client . close raise PairingFailed , outer . status unless OuterMessage :: Status :: STATUS_OK == outer . status end
Complete the pairing process
21,529
def send_message ( msg , type ) message = wrap_message ( msg , type ) . serialize_to_string message_size = [ message . length ] . pack ( 'N' ) @gtv . ssl_client . write ( message_size + message ) data = "" @gtv . ssl_client . readpartial ( 1000 , data ) @gtv . ssl_client . readpartial ( 1000 , data ) outer = OuterMessage . new outer . parse_from_string ( data ) return outer end
Format and send the message to the GoogleTV
21,530
def wrap_message ( msg , type ) outer = OuterMessage . new outer . protocol_version = 1 outer . status = OuterMessage :: Status :: STATUS_OK outer . type = type outer . payload = msg . serialize_to_string return outer end
Wrap the message in an OuterMessage
21,531
def encode_hex_secret secret encoded_secret = [ secret . to_i ( 16 ) ] . pack ( "N" ) . unpack ( "cccc" ) [ 2 .. 3 ] . pack ( "c*" ) digest = OpenSSL :: Digest :: Digest . new ( 'sha256' ) digest << @gtv . ssl_client . cert . public_key . n . to_s ( 2 ) digest << @gtv . ssl_client . cert . public_key . e . to_s ( 2 ) digest << @gtv . ssl_client . peer_cert . public_key . n . to_s ( 2 ) digest << @gtv . ssl_client . peer_cert . public_key . e . to_s ( 2 ) digest << encoded_secret [ encoded_secret . size / 2 ] return digest . digest end
Encode the secret from the TV into an OpenSSL Digest
21,532
def free ( id ) enclosing_range_index = @allocated_ranges . index { | range | range . last >= id && range . first <= id } enclosing_range = @allocated_ranges [ enclosing_range_index ] if enclosing_range . size == 1 @allocated_ranges . delete ( enclosing_range ) elsif enclosing_range . first == id @allocated_ranges [ enclosing_range_index ] = ( enclosing_range . first . succ .. enclosing_range . last ) elsif enclosing_range . last == id @allocated_ranges [ enclosing_range_index ] = ( enclosing_range . first .. enclosing_range . last . pred ) else @allocated_ranges [ enclosing_range_index ] = ( enclosing_range . first .. id . pred ) @allocated_ranges . insert ( enclosing_range_index . succ , ( id . succ .. enclosing_range . last ) ) end end
Return + id + back to the allocator so it can be allocated again in the future .
21,533
def full_title ( page_title = '' ) aname = Rails . application . app_name . strip return aname if page_title . blank? "#{page_title.strip} | #{aname}" end
Gets the full title of the page .
21,534
def glyph ( name , size = '' ) size = case size . to_s . downcase when 'small' , 'sm' 'glyphicon-small' when 'large' , 'lg' 'glyphicon-large' else nil end name = name . to_s . strip return nil if name . blank? result = '<i class="glyphicon glyphicon-' + CGI :: escape_html ( name ) result += ' ' + size unless size . blank? result += '"></i>' result . html_safe end
Shows a glyph with an optional size .
21,535
def fmt_num ( value , places = 2 ) return nil if value . blank? value = if value . respond_to? ( :to_f ) value . to_f else nil end return nil unless value . is_a? ( :: Float ) "%0.#{places}f" % value . round ( places ) end
Formats a number with the specified number of decimal places .
21,536
def panel ( title , options = { } , & block ) options = { type : 'primary' , size : 6 , offset : 3 , open_body : true } . merge ( options || { } ) options [ :type ] = options [ :type ] . to_s . downcase options [ :type ] = 'primary' unless %w( primary success info warning danger ) . include? ( options [ :type ] ) options [ :size ] = 6 unless ( 1 .. 12 ) . include? ( options [ :size ] ) options [ :offset ] = 3 unless ( 0 .. 12 ) . include? ( options [ :offset ] ) ret = "<div class=\"col-md-#{options[:size]} col-md-offset-#{options[:offset]}\"><div class=\"panel panel-#{options[:type]}\"><div class=\"panel-heading\"><h4 class=\"panel-title\">#{h title}</h4></div>" ret += '<div class="panel-body">' if options [ :open_body ] if block_given? content = capture { block . call } content = CGI :: escape_html ( content ) unless content . html_safe? ret += content end ret += '</div>' if options [ :open_body ] ret += '</div></div>' ret . html_safe end
Creates a panel with the specified title .
21,537
def delete if self . class . hooks [ :active ] self . class . hooks [ :before_delete ] . each do | block | self . class . hooks [ :active ] = false block . yield self self . class . hooks [ :active ] = true end end st = prepare ( "DELETE FROM #{table} WHERE #{pk_clause}" ) num_deleted = st . execute ( * pk_values ) . affected_count st . finish if num_deleted != 1 false else if self . class . hooks [ :active ] self . class . hooks [ :after_delete ] . each do | block | self . class . hooks [ :active ] = false block . yield self self . class . hooks [ :active ] = true end end true end end
Returns true iff the record and only the record was successfully deleted .
21,538
def subscribe ( subscription ) @logger . info "Subscribing to: #{subscription + '*'}" pubsub . psubscribe ( subscription + '*' ) do | chan , msg | @logger . info "pushing c: #{chan} msg: #{msg}" channel ( chan ) . push ( msg ) end end
subscribe fires a event on a EM channel whenever a message is fired on a pattern matching name .
21,539
def nav_link ( options = { } , & block ) c , a = fetch_controller_and_action ( options ) p = options . delete ( :params ) || { } klass = page_active? ( c , a , p ) ? 'active' : '' o = options . delete ( :html_options ) || { } o [ :class ] = "#{o[:class]} #{klass}" . strip if block_given? content_tag ( :li , capture ( & block ) , o ) else content_tag ( :li , nil , o ) end end
Navigation link helper
21,540
def get_or_set ( key , pool_options = { } , & client_block ) unless @_staged [ key ] @mutex . synchronize do @_staged [ key ] ||= [ pool_options , client_block ] end end get ( key ) end
Adds session unless it already exists and returns the session
21,541
def delete ( key ) deleted = false pool = nil @mutex . synchronize do pool = @_sessions . delete ( key ) end if pool pool . shutdown! deleted = true HotTub . logger . info "[HotTub] #{key} was deleted from #{@name}." if HotTub . logger end deleted end
Deletes and shutdowns the pool if its found .
21,542
def reap! HotTub . logger . info "[HotTub] Reaping #{@name}!" if HotTub . log_trace? @mutex . synchronize do @_sessions . each_value do | pool | break if @shutdown pool . reap! end end nil end
Remove and close extra clients
21,543
def emit_signal ( signal_name , node ) @subscriptions ||= Hash . new ( ) @runner ||= BetterRailsDebugger :: Parser :: Ruby :: ContextRunner . new self ( @subscriptions [ signal_name ] || { } ) . values . each do | block | @runner . node = node @runner . instance_eval & block end end
Call all subscriptions for the given signal
21,544
def subscribe_signal ( signal_name , step = :first_pass , & block ) key = SecureRandom . hex ( 5 ) @subscriptions ||= Hash . new ( ) @subscriptions [ signal_name ] ||= Hash . new @subscriptions [ signal_name ] [ key ] = block key end
Subscribe to a particular signal
21,545
def add ( method_name , * args ) return if error? ( method_name , * args ) has_do_block = args . include? ( 'block@d' ) has_brace_block = args . include? ( 'block@b' ) args = delete_block_args args @target_methods << TargetMethod . new do | t | t . method_name = method_name t . args = args t . has_do_block = has_do_block t . has_brace_block = has_brace_block end end
init default values add sunippet information
21,546
def send_message ( data ) data = prepare_data ( data ) logger . debug { "Sending request to #{url.to_s}:\n#{data}" } if logger http = Net :: HTTP :: Proxy ( proxy_host , proxy_port , proxy_user , proxy_pass ) . new ( url . host , url . port ) http . read_timeout = http_read_timeout http . open_timeout = http_open_timeout http . use_ssl = secure response = begin http . post ( url . path , data , HEADERS ) rescue * HTTP_ERRORS => e log :error , "Timeout while contacting the Whoops server." nil end case response when Net :: HTTPSuccess then log :info , "Success: #{response.class}" , response else log :error , "Failure: #{response.class}" , response end if response && response . respond_to? ( :body ) error_id = response . body . match ( %r{ } ) error_id [ 1 ] if error_id end end
Sends the notice data off to Whoops for processing .
21,547
def status ( inserter_id ) status_hash = Hash . new xml = Builder :: XmlMarkup . new xml . instruct! xml . Request ( :xmlns => "urn:sbx:apis:SbxBaseComponents" ) do | xml | connection . requester_credentials_block ( xml ) xml . GetDocumentStatusCall do | xml | xml . InserterId ( inserter_id ) end end response = connection . post_xml ( xml ) document = REXML :: Document . new ( response ) status_hash [ :status ] = document . elements [ "GetDocumentStatusCallResponse" ] . elements [ "Status" ] . text status_hash [ :document_id ] = document . elements [ "GetDocumentStatusCallResponse" ] . elements [ "DocumentId" ] . text status_hash [ :document_type ] = document . elements [ "GetDocumentStatusCallResponse" ] . elements [ "DocumentType" ] . text status_hash end
Requires an inserter id from an upload call
21,548
def rjs_check ( path = @options [ :rjs ] ) rjs_command = rjs_file ( path ) || rjs_bin ( path ) if ! ( rjs_command ) raise RuntimeError , "Could not find r.js optimizer in #{path.inspect} - try updating this by npm install -g requirejs" end rjs_command end
Incase both a file and bin version are availble file version is taken
21,549
def match_type? ( object ) result = object . kind_of_any? self . type_classes if not result result = object . type_of_any? self . type_types end return result end
Matches object is of this type .
21,550
def create data if data . kind_of? ( Array ) data . map { | item | self . create ( item ) } else @client . post @segments , data end end
Create an item into the collection
21,551
def where fields = { } , operation = 'and' fields . each_pair do | k , value | field = ( k . respond_to? ( :field ) ? k . field : k ) . to_s comparation = k . respond_to? ( :comparation ) ? k . comparation : '=' value = [ value . first , value . last ] if value . kind_of? ( Range ) @wheres << [ field , comparation , value , operation ] end self end
Add where clause to the current query .
21,552
def order fields by_num = { 1 => 'asc' , - 1 => 'desc' } ordering = [ ] fields . each_pair do | key , value | ordering << [ key . to_s , by_num [ value ] || value ] end @ordering = ordering self end
Add order clause to the query .
21,553
def claim_interface devices = usb . devices ( :idVendor => VENDOR_ID , :idProduct => PRODUCT_ID ) unless devices . first then return end @device = devices . first @handle = @device . open @handle . detach_kernel_driver ( HID_INTERFACE ) @handle . claim_interface ( HID_INTERFACE ) end
Creates a new URIx interface . Claim the USB interface for this program . Must be called to begin using the interface .
21,554
def set_output pin , state state = false if state == :low state = true if state == :high if ( @pin_states >> ( pin - 1 ) ) . odd? && ( state == false ) or ( @pin_states >> ( pin - 1 ) ) . even? && ( state == true ) then mask = 0 + ( 1 << ( pin - 1 ) ) @pin_states ^= mask end write_output end
Sets the state of a GPIO pin .
21,555
def set_pin_mode pin , mode if ( @pin_modes >> ( pin - 1 ) ) . odd? && ( mode == :input ) or ( @pin_modes >> ( pin - 1 ) ) . even? && ( mode == :output ) then mask = 0 + ( 1 << ( pin - 1 ) ) @pin_modes ^= mask end end
Sets the mode of a GPIO pin to input or output .
21,556
def auth build_response ( "token" ) do connection . post do | req | req . headers . delete ( "Authorization" ) req . url "auth/" req . body = { username : username , password : password } . to_json end end end
Attempts to authenticate with the Montage API
21,557
def build_response ( resource_name ) response = yield resource = response_successful? ( response ) ? resource_name : "error" response_object = Montage :: Response . new ( response . status , response . body , resource ) set_token ( response_object . token . value ) if resource_name == "token" && response . success? response_object end
Instantiates a response object based on the yielded block
21,558
def connection @connect ||= Faraday . new do | f | f . adapter :net_http f . headers = connection_headers f . url_prefix = "#{default_url_prefix}/api/v#{api_version}/" f . response :json , content_type : / \b / end end
Creates an Faraday connection instance for requests
21,559
def write_note ( options ) url = "#{Base}note" note = Org :: Familysearch :: Ws :: Familytree :: V2 :: Schema :: Note . new note . build ( options ) familytree = Org :: Familysearch :: Ws :: Familytree :: V2 :: Schema :: FamilyTree . new familytree . notes = [ note ] res = @fs_communicator . post ( url , familytree . to_json ) familytree = Org :: Familysearch :: Ws :: Familytree :: V2 :: Schema :: FamilyTree . from_json JSON . parse ( res . body ) return familytree . notes . first end
Writes a note attached to the value ID of the specific person or relationship .
21,560
def combine ( person_array ) url = Base + 'person' version_persons = self . person person_array , :genders => 'none' , :events => 'none' , :names => 'none' combine_person = Org :: Familysearch :: Ws :: Familytree :: V2 :: Schema :: Person . new combine_person . create_combine ( version_persons ) familytree = Org :: Familysearch :: Ws :: Familytree :: V2 :: Schema :: FamilyTree . new familytree . persons = [ combine_person ] res = @fs_communicator . post ( url , familytree . to_json ) familytree = Org :: Familysearch :: Ws :: Familytree :: V2 :: Schema :: FamilyTree . from_json JSON . parse ( res . body ) return familytree . persons [ 0 ] end
Combines person into a new person
21,561
def edit add_breadcrumb I18n . t ( "controllers.admin.comments.edit.breadcrumb" ) set_title ( I18n . t ( "controllers.admin.comments.edit.title" ) ) @comment = Comment . find ( params [ :id ] ) end
get and disply certain comment
21,562
def update @comment = Comment . find ( params [ :id ] ) atts = comments_params respond_to do | format | if @comment . update_attributes ( atts ) format . html { redirect_to edit_admin_comment_path ( @comment ) , notice : I18n . t ( "controllers.admin.comments.update.flash.success" ) } else format . html { add_breadcrumb I18n . t ( "controllers.admin.comments.edit.breadcrumb" ) render action : "edit" } end end end
update the comment . You are able to update everything about the comment as an admin
21,563
def destroy @comment = Comment . find ( params [ :id ] ) @comment . destroy respond_to do | format | format . html { redirect_to admin_comments_path , notice : I18n . t ( "controllers.admin.comments.destroy.flash.success" ) } end end
delete the comment
21,564
def bulk_update func = Comment . bulk_update params respond_to do | format | format . html { redirect_to admin_comments_path , notice : func == 'ntd' ? I18n . t ( "controllers.admin.comments.bulk_update.flash.nothing_to_do" ) : I18n . t ( "controllers.admin.comments.bulk_update.flash.success" , func : func ) } end end
bulk_update function takes all of the checked options and updates them with the given option selected . The options for the bulk update in comments area are - Unapprove - Approve - Mark as Spam - Destroy
21,565
def mark_as_spam comment = Comment . find ( params [ :id ] ) comment . comment_approved = "S" comment . is_spam = "S" respond_to do | format | if comment . save format . html { redirect_to admin_comments_path , notice : I18n . t ( "controllers.admin.comments.mark_as_spam.flash.success" ) } else format . html { render action : "index" } end end end
mark_as_spam function is a button on the ui and so need its own function . The function simply marks the comment as spam against the record in the database . the record is then not visable unless you explicity tell the system that you want to see spam records .
21,566
def sort_by_tag by_tag = Hash [ @routes [ :paths ] . sort_by do | _key , value | value . first [ 1 ] [ 'tags' ] end ] place_readme_first ( by_tag ) end
Sort routes by tags
21,567
def method_missing ( m , * args , & block ) if @tracker_names . include? m @tracker_blocks [ m ] = block else super ( name , * args , & block ) end end
store tracker code blocks
21,568
def truncate ( numeral , round_up = nil ) check_base numeral unless simplifying? n = precision ( numeral ) if n == 0 return numeral if numeral . repeating? n = numeral . digits . size end unless n >= numeral . digits . size && numeral . approximate? if n < numeral . digits . size - 1 rest_digits = numeral . digits [ n + 1 .. - 1 ] else rest_digits = [ ] end if numeral . repeating? && numeral . repeat < numeral . digits . size && n >= numeral . repeat rest_digits += numeral . digits [ numeral . repeat .. - 1 ] end digits = numeral . digits [ 0 , n ] if digits . size < n digits += ( digits . size ... n ) . map { | i | numeral . digit_value_at ( i ) } end if numeral . base % 2 == 0 tie_digit = numeral . base / 2 max_lo = tie_digit - 1 else max_lo = numeral . base / 2 end next_digit = numeral . digit_value_at ( n ) if next_digit == 0 unless round_up . nil? && rest_digits . all? { | d | d == 0 } round_up = :lo end elsif next_digit <= max_lo round_up = :lo elsif next_digit == tie_digit if round_up || rest_digits . any? { | d | d != 0 } round_up = :hi else round_up = :tie end else round_up = :hi end numeral = Numeral [ digits , point : numeral . point , sign : numeral . sign , base : numeral . base , normalize : :approximate ] end end [ numeral , round_up ] end
Truncate a numeral and return also a round_up value with information about the digits beyond the truncation point that can be used to round the truncated numeral . If the numeral has already been truncated the round_up result of that prior truncation should be passed as the second argument .
21,569
def adjust ( numeral , round_up ) check_base numeral point , digits = Flt :: Support . adjust_digits ( numeral . point , numeral . digits . digits_array , round_mode : @mode , negative : numeral . sign == - 1 , round_up : round_up , base : numeral . base ) if numeral . zero? && simplifying? digits = [ ] point = 0 end normalization = simplifying? ? :exact : :approximate Numeral [ digits , point : point , base : numeral . base , sign : numeral . sign , normalize : normalization ] end
Adjust a truncated numeral using the round - up information
21,570
def column ( name , sql_type = :text , default = nil , null = true ) columns << ActiveRecord :: ConnectionAdapters :: Column . new ( name . to_s , default , sql_type . to_s , null ) end
Creates an attribute corresponding to a database column . N . B No table is created in the database
21,571
def create_user ( username , rsa_pub_key , rsa_pub_key_name ) key_name = "#{username}@#{rsa_pub_key_name}" key_path = @configuration . user_key_path ( key_name ) if users_public_keys ( ) . include? ( key_path ) raise :: Gitolite :: Duplicate , "Public key (#{rsa_pub_key_name}) already exists for user (#{username}) on gitolite server" end add_commit_file ( key_path , rsa_pub_key , "Added public key (#{rsa_pub_key_name}) for user (#{username}) " ) key_path end
this should be depracated
21,572
def send_messages ( messages , opts = { } ) data , _status_code , _headers = send_messages_with_http_info ( messages , opts ) return data end
Enqueues new messages
21,573
def real_path ( aPath ) ( path = Pathname . new ( :: File . expand_path ( aPath ) ) ) && path . realpath . to_s end
make path real according to file system
21,574
def expand_magic_path ( aPath , aBasePath = nil ) aBasePath ||= Dir . pwd path = aPath if path . begins_with? ( '...' ) rel_part = path . split3 ( / \. \. \. \/ \\ / ) [ 2 ] return find_upwards ( aBasePath , rel_part ) end path_combine ( aBasePath , aPath ) end
allows special symbols in path currently only ... supported which looks upward in the filesystem for the following relative path from the basepath
21,575
def container ( inner_html ) html = '' html << before_container html << template . tag ( 'div' , container_attributes , true ) + "\n" html << inner_html html << "</div>\n" html << after_container return html . html_safe end
Wrap the table in a div
21,576
def add_marks ( marks = nil ) marks . each_pair { | k , v | self [ k ] = v } if marks if block_given? result = yield self add_marks ( result ) if Hash === result end end
Add all marks provided by a Hash instance _marks_ .
21,577
def to_h ( nonil = true ) return { } unless @marks marks = @marks . dup if nonil marks . delete_if { | k , v | v . nil? } end marks end
Converts this Markable to a Hash . When _nonil_ is true nil mark values do not lead to hash entries .
21,578
def author author_elements = @html . xpath ( '//meta[@name = "dc.creator"]' ) unless author_elements . empty? author_elements . each do | element | if element [ 'content' ] return element [ 'content' ] . strip end end end author_elements = @html . xpath ( '//*[contains(@class, "vcard")]//*[contains(@class, "fn")]' ) unless author_elements . empty? author_elements . each do | element | if element . text return element . text . strip end end end author_elements = @html . xpath ( '//a[@rel = "author"]' ) unless author_elements . empty? author_elements . each do | element | if element . text return element . text . strip end end end author_elements = @html . xpath ( '//*[@id = "author"]' ) unless author_elements . empty? author_elements . each do | element | if element . text return element . text . strip end end end end
Look through the
21,579
def gravatar_for ( user , options = { } ) options = { size : 80 , default : :identicon } . merge ( options || { } ) options [ :default ] = options [ :default ] . to_s . to_sym unless options [ :default ] . nil? || options [ :default ] . is_a? ( Symbol ) gravatar_id = Digest :: MD5 :: hexdigest ( user . email . downcase ) size = options [ :size ] default = [ :mm , :identicon , :monsterid , :wavatar , :retro ] . include? ( options [ :default ] ) ? "&d=#{options[:default]}" : '' gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}#{default}" image_tag ( gravatar_url , alt : user . name , class : 'gravatar' , style : "width: #{size}px, height: #{size}px" ) end
Returns the Gravatar for the given user .
21,580
def extract_session ( args ) if args . last . is_a? ( Session :: Rest ) || args . last . is_a? ( Session :: Embedded ) args . pop else Session . current end end
Extracts a session from the array of arguments if one exists at the end .
21,581
def mirrors return [ ] unless self . site . is_mirrored? ( Cms :: Site . mirrored - [ self . site ] ) . collect do | site | case self when Cms :: Layout then site . layouts . find_by_identifier ( self . identifier ) when Cms :: Page then site . pages . find_by_full_path ( self . full_path ) when Cms :: Snippet then site . snippets . find_by_identifier ( self . identifier ) end end . compact end
Mirrors of the object found on other sites
21,582
def sync_mirror return if self . is_mirrored || ! self . site . is_mirrored? ( Cms :: Site . mirrored - [ self . site ] ) . each do | site | mirror = case self when Cms :: Layout m = site . layouts . find_by_identifier ( self . identifier_was || self . identifier ) || site . layouts . new m . attributes = { :identifier => self . identifier , :parent_id => site . layouts . find_by_identifier ( self . parent . try ( :identifier ) ) . try ( :id ) } m when Cms :: Page m = site . pages . find_by_full_path ( self . full_path_was || self . full_path ) || site . pages . new m . attributes = { :slug => self . slug , :label => self . slug . blank? ? self . label : m . label , :parent_id => site . pages . find_by_full_path ( self . parent . try ( :full_path ) ) . try ( :id ) , :layout => site . layouts . find_by_identifier ( self . layout . try ( :identifier ) ) } m when Cms :: Snippet m = site . snippets . find_by_identifier ( self . identifier_was || self . identifier ) || site . snippets . new m . attributes = { :identifier => self . identifier } m end mirror . is_mirrored = true begin mirror . save! rescue ActiveRecord :: RecordInvalid logger . detailed_error ( $! ) end end end
Creating or updating a mirror object . Relationships are mirrored but content is unique . When updating need to grab mirrors based on self . slug_was new objects will use self . slug .
21,583
def destroy_mirror return if self . is_mirrored || ! self . site . is_mirrored? mirrors . each do | mirror | mirror . is_mirrored = true mirror . destroy end end
Mirrors should be destroyed
21,584
def read_file ( path , use_method = nil ) if use_method use_method = use_method . to_sym raise ArgumentError , "use_method (#{use_method.inspect}) is not a valid method." unless file_methods . include? ( use_method ) raise Shells :: ShellError , "The #{use_method} binary is not available with this shell." unless which ( use_method ) send "read_file_#{use_method}" , path elsif default_file_method return send "read_file_#{default_file_method}" , path else raise Shells :: ShellError , 'No supported binary to encode/decode files.' end end
Reads from a file on the device .
21,585
def sudo_exec ( command , options = { } , & block ) sudo_prompt = '[sp:' sudo_match = / \n \[ /m sudo_strip = / \[ \n \n /m ret = exec ( "sudo -p \"#{sudo_prompt}\" bash -c \"#{command.gsub('"', '\\"')}\"" , options ) do | data , type | test_data = data . to_s desired_length = sudo_prompt . length + 1 if test_data . length > 0 && test_data . length < desired_length test_data = stdout [ - desired_length .. - 1 ] . to_s end if test_data =~ sudo_match self . options [ :password ] else if block block . call ( data , type ) else nil end end end ret . gsub ( sudo_strip , '' ) end
Executes an elevated command using the sudo command .
21,586
def setup_prompt command = "PS1=#{options[:prompt]}" sleep 1.0 exec_ignore_code command , silence_timeout : 10 , command_timeout : 10 , timeout_error : true , get_output : false end
Uses the PS1 = command to set the prompt for the shell .
21,587
def getData ( datadictionary_id ) parameter = { basic_auth : @auth } response = self . class . get ( "/datadictionaries/#{datadictionary_id}/data" , parameter ) if response . success? response [ 'Data' ] else raise response . response end end
Returns a hashed value with data
21,588
def at ( point ) ipoint = point . to_i target = ( ipoint < 0 ) ? ( version + ipoint ) : ipoint return unless ( 0 .. version ) . include? target detect { | state | target . equal? state . version } end
Returns the state of the object at some point in the past
21,589
def fetch ( key , * default ) trees . lazy . each do | tree | catch do | ball | return tree . fetch ( key ) { throw ball } end end return yield ( key ) if block_given? return default . first unless default . empty? raise KeyError , %(key not found: "#{key}") end
Fetch a value from a forest
21,590
def flatten ( & merger ) trees . reverse_each . reduce ( Tree [ ] ) do | result , tree | result . merge! ( tree , & merger ) end end
Flattening a forest produces a tree with the equivalent view of key paths
21,591
def trees Enumerator . new do | yielder | remaining = [ self ] remaining . each do | woods | next yielder << woods if woods . is_a? ( Tree ) woods . each { | wood | remaining << wood } end end end
Return a breadth - first Enumerator for all the trees in the forest and any nested forests
21,592
def key_paths trees . reduce ( Set . new ) { | result , tree | result . merge ( tree . key_paths ) } end
Return all visible key paths in the forest
21,593
def to_byte_string ret = self . gsub ( / \s / , '' ) raise 'Hex string must have even number of characters.' unless ret . size % 2 == 0 raise 'Hex string must only contain 0-9 and A-F characters.' if ret =~ / / [ ret ] . pack ( 'H*' ) . force_encoding ( 'ascii-8bit' ) end
Converts a hex string into a byte string .
21,594
def remember ( user ) user . remember cookies . permanent . signed [ :user_id ] = user . id cookies . permanent [ :remember_token ] = user . remember_token end
Remembers a user in a persistent session .
21,595
def current_user if ( user_id = session [ :user_id ] ) @current_user ||= User . find_by ( id : user_id ) elsif ( user_id = cookies . signed [ :user_id ] ) user = User . find_by ( id : user_id ) if user && user . authenticated? ( cookies [ :remember_token ] ) log_in user @current_user = user end end end
Returns the user corresponding to the remember token cookie .
21,596
def makeAuthAPICall ( url = API_BASE ) request_url = "#{url}/client/#{@client_id}/authenticate?apikey=#{@api_key}" begin response = RestClient . get ( request_url ) return response rescue RestClient :: Exception => error begin response = JSON . parse ( error . response ) unless response raise InvalidRequestException , "The Import API returned: #{error.http_code} #{error.message}" end raise InvalidRequestException , "The Import API returned: #{response['code']} #{response['message']}. Reasons: #{response['reasons']}" rescue JSON :: ParserError , TypeError => json_parse_error raise InvalidResponseException , "RestClientError: #{error.class}\n Message: #{error.message}\n Response Code: #{error.http_code}\n Full Response: #{error.response}" end end end
Authenticates with the RJMetrics Data Import API
21,597
def column ( index ) index = parse_index ( index ) columns = [ ] @data . each do | row | columns << row_to_array ( row ) [ index ] . value end columns end
Retrieves the column at the given index . Aliases can be used
21,598
def header = ( header ) header = [ header ] unless header . respond_to? :each @header = normalize ( header ) @aliases = header . map do | n | n . downcase . gsub ( ' ' , '_' ) . gsub ( "\n" , '_' ) . to_sym end if @aliases . empty? end
Sets the table header . If no aliases are defined they will be defined as the texts in lowercase with line breaks and spaces replaced by underscores .
21,599
def colorize ( indexes , params = { } , & block ) [ * indexes ] . each do | index | index = parse_index ( index ) if index obj = extract_component ( params , & block ) component [ :colorizers ] [ index ] = obj else colorize_null params , & block end end end
Sets a component to colorize a column .