idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
24,000 | def tblRefs sql = [ ] @headers = %w{ RefID ActualYear Title PubID Verbatim } @name_collection . ref_collection . collection . each_with_index do | r , i | pub_id = @pub_collection [ r . publication ] ? @pub_collection [ r . publication ] : 0 note = [ ] if r . properties r . properties . keys . each do | k | note . push "#{k}: #{r.properties[k]}" if r . properties [ k ] && r . properties . length > 0 end end note = note . join ( "; " ) note = @empty_quotes if note . length == 0 cols = { RefID : r . id , ContainingRefID : 0 , Title : ( r . title . nil? ? @empty_quotes : r . title ) , PubID : pub_id , Series : @empty_quotes , Volume : ( r . volume ? r . volume : @empty_quotes ) , Issue : ( r . number ? r . number : @empty_quotes ) , RefPages : r . page_string , ActualYear : ( r . year ? r . year : @empty_quotes ) , StatedYear : @empty_quotes , AccessCode : 0 , Flags : 0 , Note : note , LastUpdate : @time , LinkID : 0 , ModifiedBy : @authorized_user_id , CiteDataStatus : 0 , Verbatim : ( r . full_citation ? r . full_citation : @empty_quotes ) } sql << sql_insert_statement ( 'tblRefs' , cols ) end sql . join ( "\n" ) end | Generate a tblRefs string . |
24,001 | def tblPubs sql = [ ] @headers = %w{ PubID PrefID PubType ShortName FullName Note LastUpdate ModifiedBy Publisher PlacePublished PubRegID Status StartYear EndYear BHL } pubs = @name_collection . ref_collection . collection . collect { | r | r . publication } . compact . uniq pubs . each_with_index do | p , i | cols = { PubID : i + 1 , PrefID : 0 , PubType : 1 , ShortName : "unknown_#{i}" , FullName : p , Note : @empty_quotes , LastUpdate : @time , ModifiedBy : @authorized_user_id , Publisher : @empty_quotes , PlacePublished : @empty_quotes , PubRegID : 0 , Status : 0 , StartYear : 0 , EndYear : 0 , BHL : 0 } @pub_collection . merge! ( p => i + 1 ) sql << sql_insert_statement ( 'tblPubs' , cols ) end sql . join ( "\n" ) end | Generate tblPubs SQL |
24,002 | def tblPeople @headers = %w{ PersonID FamilyName GivenNames GivenInitials Suffix Role LastUpdate ModifiedBy } sql = [ ] @name_collection . ref_collection . all_authors . each do | a | cols = { PersonID : a . id , FamilyName : ( a . last_name . length > 0 ? a . last_name : "Unknown" ) , GivenNames : a . first_name || @empty_quotes , GivenInitials : a . initials_string || @empty_quotes , Suffix : a . suffix || @empty_quotes , Role : 1 , LastUpdate : @time , ModifiedBy : @authorized_user_id } sql << sql_insert_statement ( 'tblPeople' , cols ) end sql . join ( "\n" ) end | Generate tblPeople string . |
24,003 | def tblRefAuthors @headers = %w{ RefID PersonID SeqNum AuthorCount LastUpdate ModifiedBy } sql = [ ] @name_collection . ref_collection . collection . each do | r | r . authors . each_with_index do | x , i | cols = { RefID : r . id , PersonID : x . id , SeqNum : i + 1 , AuthorCount : r . authors . size + 1 , LastUpdate : @time , ModifiedBy : @authorized_user_id } sql << sql_insert_statement ( 'tblRefAuthors' , cols ) end end sql . join ( "\n" ) end | Generate tblRefAuthors string . |
24,004 | def tblCites @headers = %w{ TaxonNameID SeqNum RefID NomenclatorID LastUpdate ModifiedBy NewNameStatus CitePages Note TypeClarification CurrentConcept ConceptChange InfoFlags InfoFlagStatus PolynomialStatus } sql = [ ] @name_collection . citations . keys . each do | name_id | seq_num = 1 @name_collection . citations [ name_id ] . each do | ref_id , nomenclator_index , properties | cols = { TaxonNameID : name_id , SeqNum : seq_num , RefID : ref_id , NomenclatorID : nomenclator_index , LastUpdate : @time , ModifiedBy : @authorized_user_id , CitePages : ( properties [ :cite_pages ] ? properties [ :cite_pages ] : @empty_quotes ) , NewNameStatus : 0 , Note : ( properties [ :note ] ? properties [ :note ] : @empty_quotes ) , TypeClarification : 0 , CurrentConcept : ( properties [ :current_concept ] == true ? 1 : 0 ) , ConceptChange : 0 , InfoFlags : 0 , InfoFlagStatus : 1 , PolynomialStatus : 0 } sql << sql_insert_statement ( 'tblCites' , cols ) seq_num += 1 end end sql . join ( "\n" ) end | Generate tblCites string . |
24,005 | def tblTypeSpecies @headers = %w{ GenusNameID SpeciesNameID Reason AuthorityRefID FirstFamGrpNameID LastUpdate ModifiedBy NewID } sql = [ ] names = @name_collection . names_at_rank ( 'genus' ) + @name_collection . names_at_rank ( 'subgenus' ) names . each do | n | if n . properties [ :type_species_id ] ref = get_ref ( n ) next if ref . nil? cols = { GenusNameID : n . id , SpeciesNameID : n . properties [ :type_species_id ] , Reason : 0 , AuthorityRefID : 0 , FirstFamGrpNameID : 0 , LastUpdate : @time , ModifiedBy : @authorized_user_id , NewID : 0 } sql << sql_insert_statement ( 'tblTypeSpecies' , cols ) end end sql . join ( "\n" ) end | Generate tblTypeSpecies string . |
24,006 | def tblNomenclator @headers = %w{ NomenclatorID GenusNameID SubgenusNameID SpeciesNameID SubspeciesNameID LastUpdate ModifiedBy SuitableForGenus SuitableForSpecies InfrasubspeciesNameID InfrasubKind } sql = [ ] i = 1 @name_collection . nomenclators . keys . each do | i | name = @name_collection . nomenclators [ i ] genus_id = @genus_names [ name [ 0 ] ] genus_id ||= 0 subgenus_id = @genus_names [ name [ 1 ] ] subgenus_id ||= 0 species_id = @species_names [ name [ 2 ] ] species_id ||= 0 subspecies_id = @species_names [ name [ 3 ] ] subspecies_id ||= 0 variety_id = @species_names [ name [ 4 ] ] variety_id ||= 0 cols = { NomenclatorID : i , GenusNameID : genus_id , SubgenusNameID : subgenus_id , SpeciesNameID : species_id , SubspeciesNameID : subspecies_id , InfrasubspeciesNameID : variety_id , InfrasubKind : ( variety_id == 0 ? 0 : 2 ) , LastUpdate : @time , ModifiedBy : @authorized_user_id , SuitableForGenus : 0 , SuitableForSpecies : 0 } i += 1 sql << sql_insert_statement ( 'tblNomenclator' , cols ) end sql . join ( "\n" ) end | Must be called post tblGenusNames and tblSpeciesNames . Some records are not used but can be cleaned by SF |
24,007 | def empty_row? ( row ) is_empty = true row . each do | item | is_empty = false if item && ! item . empty? end is_empty end | Return true if row contains no data |
24,008 | def truncate_decimal ( a_cell ) if ( a_cell . is_a? ( Numeric ) ) a_cell = truncate_decimal_to_string ( a_cell , 3 ) a_cell = BigDecimal . new ( a_cell ) . to_s ( "F" ) end a_cell end | Truncates a decimal to 3 decimal places if numeric and remove trailing zeros if more than one decimal place . returns a string |
24,009 | def clean_int_value ( a_cell ) if ( a_cell . match ( / \. / ) ) cary = a_cell . split ( "." ) a_cell = cary [ 0 ] end a_cell end | If the result is n . 000 ... Remove the unecessary zeros . |
24,010 | def parse ( raw_args ) cmd_args = cmd_args_extractor . call ( raw_args ) cmd = root . locate ( cmd_args , raw_args ) root . add_global_options ( cmd ) begin parser . call ( cmd , cmd_args , raw_args ) rescue => e shell . error e . message shell . failure_exit end end | Initializes with a root command object |
24,011 | def execute ( context ) cmd = context [ :cmd ] opts = context [ :opts ] || { } args = context [ :args ] || [ ] cmd_args = context [ :cmd_args ] cli_shell = context [ :shell ] || shell unless cmd . callable? return root [ 'help' ] . call ( opts , cmd_args , shell ) end cmd = handle_callable_option ( root , cmd ) cmd . call ( opts , args , cli_shell ) end | Executes the callable object in a command . All command callable object expect to be called the the options hash arg hash and shell object . |
24,012 | def get_access_token if :: File . exists? ( ACCESS_TOKEN ) @access_token = :: YAML . load_file ( ACCESS_TOKEN ) end if @access_token . nil? get_initial_token :: File . open ( ACCESS_TOKEN , 'w' ) do | out | YAML . dump ( @access_token , out ) end end end | get the access token |
24,013 | def get_initial_token @request_token = get_request_token puts "Place \"#{@request_token.authorize_url}\" in your browser" print "Enter the number they give you: " pin = STDIN . readline . chomp @access_token = @request_token . get_access_token ( :oauth_verifier => pin ) end | get the initial access token |
24,014 | def traverse ( sexp , visitor , context = Visitor :: Context . new ) element_name , attrs , children = decompose_sexp ( sexp ) non_ns_attrs , ns_bindings = Namespace :: non_ns_attrs_ns_bindings ( context . ns_stack , element_name , attrs ) context . ns_stack . push ( ns_bindings ) eelement_name = Namespace :: explode_qname ( context . ns_stack , element_name ) eattrs = Namespace :: explode_attr_qnames ( context . ns_stack , non_ns_attrs ) begin visitor . element ( context , eelement_name , eattrs , ns_bindings ) do children . each_with_index do | child , i | if child . is_a? ( Array ) traverse ( child , visitor , context ) else visitor . text ( context , child ) end end end ensure context . ns_stack . pop end visitor end | pre - order traversal of the sexp calling methods on the visitor with each node |
24,015 | def errship_standard ( errship_scope = false ) flash [ :error ] ||= I18n . t ( 'errship.standard' ) render :template => '/errship/standard.html.erb' , :layout => 'application' , :locals => { :status_code => 500 , :errship_scope => errship_scope } , :status => ( Errship . status_code_success ? 200 : 500 ) end | A blank page with just the layout and flash message which can be redirected to when all else fails . |
24,016 | def flashback ( error_message , exception = nil ) airbrake_class . send ( :notify , exception ) if airbrake_class flash [ :error ] = error_message begin redirect_to :back rescue ActionController :: RedirectBackError redirect_to error_path end end | Set the error flash and attempt to redirect back . If RedirectBackError is raised redirect to error_path instead . |
24,017 | def each Transaction . open ( ":#{method} operation" ) do | t | next_token = starting_token begin args = @args . dup args << next_token results = @sdb . send ( @method , * args ) yield ( results , self ) next_token = results [ :next_token ] end while next_token end end | Yields once for each result set until there is no next token . |
24,018 | def form_authenticity_token raise 'CSRF token secret must be defined' if CSRF_TOKEN_SECRET . nil? || CSRF_TOKEN_SECRET . empty? if request . session_options [ :id ] . nil? || request . session_options [ :id ] . empty? original_form_authenticity_token else Digest :: SHA1 . hexdigest ( "#{CSRF_TOKEN_SECRET}#{request.session_options[:id]}#{request.subdomain}" ) end end | Sets the token value for the current session . |
24,019 | def reset! Putio :: Configurable . keys . each do | key | public_send ( "#{key}=" . to_sym , Putio :: Defaults . options [ key ] ) end self end | Reset configuration options to default values |
24,020 | def add_machined_helpers machined . context_helpers . each do | helper | case helper when Proc instance_eval & helper when Module extend helper end end end | Loops through the helpers added to the Machined environment and adds them to the Context . Supports blocks and Modules . |
24,021 | def run runtime = Runtime . new buffer = '' while ( line = Readline . readline ( buffer . empty? ? ">> " : "?> " , true ) ) begin buffer << line ast = Parser . new . parse ( buffer ) puts "=> " + runtime . run ( ast ) . to_s buffer = '' rescue Crisp :: SyntaxError => e end end end | start the shell |
24,022 | def load ( needs = { } ) needs = needs . merge ( { "zergrush" => INCLUDE } ) Gem :: Specification . each { | gem | next if @gems . has_key? gem . name check = needs . dup gem . dependencies . each do | dep | if check . has_key? dep . name check [ dep . name ] = ! check [ dep . name ] end end if ( check . select { | name , test | ! test } ) . length == 0 if gem . metadata [ "zergrushplugin" ] != nil require File . join ( gem . gem_dir , "lib" , gem . name , "init.rb" ) @gems [ gem . name ] = gem . gem_dir end end } return nil end | Responsible for going through the list of available gems and loading any plugins requested . It keeps track of what it s loaded already and won t load them again . |
24,023 | def put ( doc , opts = { } ) opts = opts . inject ( { } ) { | h , ( k , v ) | h [ k . to_s ] = v ; h } doc = Rufus :: Json . dup ( doc ) unless opts [ 'update_rev' ] type , key = doc [ 'type' ] , doc [ '_id' ] raise ( ArgumentError . new ( "missing values for keys 'type' and/or '_id'" ) ) if type . nil? || key . nil? rev = ( doc [ '_rev' ] ||= - 1 ) raise ( ArgumentError . new ( "values for '_rev' must be positive integers" ) ) if rev . class != Fixnum && rev . class != Bignum r = lock ( rev == - 1 ? :create : :write , type , key ) do | file | cur = do_get ( file ) return cur if cur && cur [ '_rev' ] != doc [ '_rev' ] return true if cur . nil? && doc [ '_rev' ] != - 1 doc [ '_rev' ] += 1 File . open ( file . path , 'wb' ) { | io | io . write ( Rufus :: Json . encode ( doc ) ) } end r == false ? true : nil end | Creates a new cloche . |
24,024 | def get_many ( type , regex = nil , opts = { } ) opts = opts . inject ( { } ) { | h , ( k , v ) | h [ k . to_s ] = v ; h } d = dir_for ( type ) return ( opts [ 'count' ] ? 0 : [ ] ) unless File . exist? ( d ) regexes = regex ? Array ( regex ) : nil docs = [ ] skipped = 0 limit = opts [ 'limit' ] skip = opts [ 'skip' ] count = opts [ 'count' ] ? 0 : nil files = Dir [ File . join ( d , '**' , '*.json' ) ] . sort_by { | f | File . basename ( f ) } files = files . reverse if opts [ 'descending' ] files . each do | fn | key = File . basename ( fn , '.json' ) if regexes . nil? or match? ( key , regexes ) skipped = skipped + 1 next if skip and skipped <= skip doc = get ( type , key ) next unless doc if count count = count + 1 else docs << doc end break if limit and docs . size >= limit end end count ? count : docs end | Given a type this method will return an array of all the documents for that type . |
24,025 | def datepicker ( object_name , method , options = { } , timepicker = false ) input_tag = JqueryDatepick :: Tags . new ( object_name , method , self , options ) dp_options , tf_options = input_tag . split_options ( options ) tf_options [ :value ] = input_tag . format_date ( tf_options [ :value ] , String . new ( dp_options [ :dateFormat ] ) ) if tf_options [ :value ] && ! tf_options [ :value ] . empty? && dp_options . has_key? ( :dateFormat ) html = input_tag . render method = timepicker ? "datetimepicker" : "datepicker" html += javascript_tag ( "jQuery(document).ready(function(){jQuery('##{input_tag.get_name_and_id(tf_options.stringify_keys)["id"]}').#{method}(#{dp_options.to_json})});" ) html . html_safe end | Mehtod that generates datepicker input field inside a form |
24,026 | def default = ( value ) value = value . to_sym unless config . accounts . include? ( value ) raise NoSuchAccount end config [ :default ] = value config . save! end | This is deliberately not abstracted ( it could be easily accessed from withing the method_missing method but that will just lead to nastiness later when I implement colors for example . |
24,027 | def queue_push ( object ) queue_item = QueueItem . new ( :kind => "push" , :object_type => object . class . name , :object_local_id => object . id , :state => "new" ) queue_item . save end | Queues object for push |
24,028 | def queue_pull ( object_class , remote_id ) queue_item = QueueItem . new ( :kind => "pull" , :object_type => object_class . name , :object_remote_id => remote_id , :state => "new" ) queue_item . save end | Queues object for pull |
24,029 | def elements_by_source source_items . map . with_index do | source_item , index | Organismo :: Element . new ( source_item , index ) . create end end | initialize elements items |
24,030 | def to_s str = String . new ( '' ) str = add_comment ( str , ':' , @references . join ( ' ' ) ) if references? str = add_comment ( str , ',' , @flags . join ( "\n" ) ) if flags? str = add_string ( str , 'msgctxt' , @msgctxt ) if @msgctxt str = add_string ( str , 'msgid' , @msgid ) str = add_string ( str , 'msgid_plural' , @msgid_plural ) if plural? str = add_translations ( str ) str end | Create a new POEntry |
24,031 | def info @info ||= { link_snippet : @link_snippet , title : title , description : description , start_time : start_time , end_time : end_time , win_chance : win_chance , current_entries : current_entries , max_entries : max_entries , is_done : is_done } end | Gives information about the raffle . |
24,032 | def populate_raffle_info threads = [ ] threads << Thread . new do @api_info = API . raffle_info ( @link_snippet ) end threads << Thread . new do page = @scraper . fetch ( raffle_link ( @link_snippet ) ) @scraper_info = @scraper . scrape_raffle ( page ) end threads . each { | t | t . join } end | Asynchronously makes network connections to TF2R to query its API and scrape the raffle page . |
24,033 | def normalize_entries ( entries ) entries . map do | entry | entry [ :steam_id ] = extract_steam_id entry . delete ( 'link' ) entry [ :username ] = entry . delete ( 'name' ) entry [ :color ] = entry . delete ( 'color' ) . downcase . strip entry [ :avatar_link ] = entry . delete ( 'avatar' ) end entries end | Converts the representation of participants by TF2R s API into our own standard representation . |
24,034 | def post_to ( track , data , tags_in = { } ) tags_in = ( here . tags . identical_copy . update ( tags_in ) rescue tags_in ) if here plan . post_data self , track , data , tags_in self end | Post data with the associated tags_in to this s spot s plan s method spot with name name and hint that the caller requested the spot activation to be executed on track tack |
24,035 | def organization_create ( global_options , options ) result = Excon . post ( "#{global_options[:fenton_server_url]}/organizations.json" , body : organization_json ( options ) , headers : { 'Content-Type' => 'application/json' } ) [ result . status , JSON . parse ( result . body ) ] end | Sends a post request with json from the command line organization |
24,036 | def save_draft ( parent_draft = nil , parent_association_name = nil ) if valid? do_create_draft ( parent_draft , parent_association_name ) create_subdrafts end return self . draft . reload if self . draft end | Build and save the draft when told to do so . |
24,037 | def build_draft_uploads self . attributes . keys . each do | key | if ( self . respond_to? ( key ) && self . send ( key ) . is_a? ( CarrierWave :: Uploader :: Base ) && self . send ( key ) . file ) self . draft . draft_uploads << build_draft_upload ( key ) end end end | Loop through and create DraftUpload objects for any Carrierwave uploaders mounted on this draftable object . |
24,038 | def build_draft_upload ( key ) cw_uploader = self . send ( key ) file = File . new ( cw_uploader . file . path ) if cw_uploader . file existing_upload = self . draft . draft_uploads . where ( :draftable_mount_column => key ) . first draft_upload = existing_upload . nil? ? DraftUpload . new : existing_upload draft_upload . file_data = file draft_upload . draftable_mount_column = key draft_upload end | Get a reference to the CarrierWave uploader mounted on the current draftable object grab the file in it and shove that file into a new DraftUpload . |
24,039 | def root ( force_reload = nil ) @root = nil if force_reload @root ||= transaction do reload_boundaries base_class . roots . find ( :first , :conditions => [ "#{nested_set_column(:left)} <= ? AND #{nested_set_column(:right)} >= ?" , left , right ] ) end end | Finds the root node that this node descends from |
24,040 | def family_ids ( force_reload = false ) return @family_ids unless @family_ids . nil? or force_reload transaction do reload_boundaries query = "SELECT id FROM #{self.class.quote_db_property(base_class.table_name)} " + "WHERE #{nested_set_column(:left)} >= #{left} AND #{nested_set_column(:right)} <= #{right} " + "ORDER BY #{nested_set_column(:left)}" @family_ids = base_class . connection . select_values ( query ) . map ( & :to_i ) end end | Returns the ids of the node and all nodes that descend from it . |
24,041 | def recalculate_nested_set ( left ) child_left = left + 1 children . each do | child | child_left = child . recalculate_nested_set ( child_left ) end set_boundaries ( left , child_left ) save_without_validation! right + 1 end | Rebuild this node s childrens boundaries |
24,042 | def send_waplink number , url , message cmd_waplink number , url , message if wait wait_for last_label return false if @response_cmd . eql? 'NOOK' return "#{@response_args[0]}.#{@response_args[1]}" . to_f end end | number The telephone number url The URL to content . Usually a image tone or application message Information text before downloading content |
24,043 | def add_addressee addressees , wait = true @addressees_accepted = false @addressees_rejected = false if addressees . kind_of? ( Array ) addressees = addressees . join ' ' end cmd_dst addressees while wait && ! @addressees_accepted wait_for last_label return false if ! add_addressee_results end end | Add telephone numbers into the massive send list . It is recommended not to send more than 50 in each call |
24,044 | def msg message , wait = true cmd_msg message return false unless wait_for ( last_label ) if wait return @response_args end | Set the message for the massive send list |
24,045 | def new_post ( name , email , post , discussion ) @post = post @discussion = discussion @name = name mail :to => email , :subject => I18n . t ( 'cornerstone.cornerstone_mailer.new_post.subject' , :topic => @discussion . subject ) end | Email a single participant within a discussion - refer to post observer |
24,046 | def validate_record ( errors_count , row_hash , index ) record = new ( row_hash ) unless record . valid? errors_count += 1 [ nil , errors_count , log_and_return_validation_error ( record , row_hash , index ) ] else [ record , errors_count , nil ] end end | Validates each record and returns error count if record is invalid |
24,047 | def create_http_request ( http_method , path , * arguments ) http_method = http_method . to_sym if [ :post , :put ] . include? ( http_method ) data = arguments . shift end headers = arguments . first . is_a? ( Hash ) ? arguments . shift : { } case http_method when :post request = Net :: HTTP :: Post . new ( path , headers ) request [ "Content-Length" ] = 0 when :put request = Net :: HTTP :: Put . new ( path , headers ) request [ "Content-Length" ] = 0 when :get request = Net :: HTTP :: Get . new ( path , headers ) when :delete request = Net :: HTTP :: Delete . new ( path , headers ) else raise ArgumentError , "Don't know how to handle http_method: :#{http_method.to_s}" end request . basic_auth @config [ :username ] , @config [ :password ] if data . is_a? ( Hash ) request . set_form_data ( data ) elsif data request . body = data . to_s request [ "Content-Length" ] = request . body . length end request end | snippet based on oauth gem |
24,048 | def timeline_entries @timeline_entries ||= begin result = { } self . timelines . each do | ( timeline_kind , timeline_class ) | dir_name = Activr :: Utils . kind_for_class ( timeline_class ) dir_path = File . join ( Activr . timelines_path , dir_name ) if ! File . directory? ( dir_path ) dir_name = Activr :: Utils . kind_for_class ( timeline_class , 'timeline' ) dir_path = File . join ( Activr . timelines_path , dir_name ) end if File . directory? ( dir_path ) result [ timeline_kind ] = { } Dir [ "#{dir_path}/*.rb" ] . sort . inject ( result [ timeline_kind ] ) do | memo , file_path | base_name = File . basename ( file_path , '.rb' ) if ( base_name != "base_timeline_entry" ) klass = "#{timeline_class.name}::#{base_name.camelize}" . constantize route_kind = if ( match_data = base_name . match ( / / ) ) match_data [ 1 ] else base_name end route = timeline_class . routes . find do | timeline_route | timeline_route . kind == route_kind end raise "Timeline entry class found for an unspecified timeline route: #{file_path} / routes: #{timeline_class.routes.inspect}" unless route memo [ route_kind ] = klass end memo end end end result end end | Get all registered timeline entries |
24,049 | def class_for_timeline_entry ( timeline_kind , route_kind ) ( self . timeline_entries [ timeline_kind ] && self . timeline_entries [ timeline_kind ] [ route_kind ] ) || Activr :: Timeline :: Entry end | Get class for timeline entry corresponding to given route in given timeline |
24,050 | def add_entity ( entity_name , entity_options , activity_klass ) entity_name = entity_name . to_sym if @entity_classes [ entity_name ] && ( @entity_classes [ entity_name ] . name != entity_options [ :class ] . name ) raise "Entity name #{entity_name} already used with class #{@entity_classes[entity_name]}, can't redefine it with class #{entity_options[:class]}" end @entity_classes [ entity_name ] = entity_options [ :class ] @activity_entities [ activity_klass ] ||= [ ] @activity_entities [ activity_klass ] << entity_name @entities ||= { } @entities [ entity_name ] ||= { } if ! @entities [ entity_name ] [ activity_klass ] . blank? raise "Entity name #{entity_name} already used for activity: #{activity_klass}" end @entities [ entity_name ] [ activity_klass ] = entity_options end | Register an entity |
24,051 | def activity_entities_for_model ( model_class ) @activity_entities_for_model [ model_class ] ||= begin result = [ ] @entity_classes . each do | entity_name , entity_class | result << entity_name if ( entity_class == model_class ) end result end end | Get all entities names for given model class |
24,052 | def timeline_entities_for_model ( model_class ) @timeline_entities_for_model [ model_class ] ||= begin result = { } self . timelines . each do | timeline_kind , timeline_class | result [ timeline_class ] = [ ] timeline_class . routes . each do | route | entities_ary = @activity_entities [ route . activity_class ] ( entities_ary || [ ] ) . each do | entity_name | result [ timeline_class ] << entity_name if ( @entity_classes [ entity_name ] == model_class ) end end result [ timeline_class ] . uniq! end result end end | Get all entities names by timelines that can have a reference to given model class |
24,053 | def classes_from_path ( dir_path ) Dir [ "#{dir_path}/*.rb" ] . sort . inject ( { } ) do | memo , file_path | klass = File . basename ( file_path , '.rb' ) . camelize . constantize if ! memo [ klass . kind ] . nil? raise "Kind #{klass.kind} already used by class #{memo[klass.kind]} so can't use it for class #{klass}" end memo [ klass . kind ] = klass memo end end | Find all classes in given directory |
24,054 | def read files = Dir . glob ( File . join ( path , "**/*" ) ) regex = Regexp . new ( "(?<=#{path}).*" ) files . map do | file | unless ( ( File . directory? file ) || ( File . extname ( file ) . upcase != ".URL" ) ) url = File . read ( file ) . scan ( / \n / ) . flatten . first . chomp name = url_name ( File . basename ( file , ".*" ) ) description = "" tag = extract_tags ( File . dirname ( file ) . scan ( regex ) ) [ url , name , description , tag ] end end . compact end | Reads the links from the Internet Explorer s bookmarks directory |
24,055 | def multi_new ( rhs ) if ( rhs . kind_of? ( Vector3 ) ) ans = self . multi_inner ( rhs . to_column_vector ) return Vector3 . new ( ans [ 0 , 0 ] , ans [ 1 , 0 ] , ans [ 2 , 0 ] ) end multi_inner ( rhs ) end | hold original multiply processing |
24,056 | def check_meta_permalink candidate = ( self . meta_permalink ? self . meta_permalink : self . title . parameterize ) accepted = nil counter = 0 while accepted . nil? if LatoBlog :: Tag . find_by ( meta_permalink : candidate ) counter += 1 candidate = "#{candidate}-#{counter}" else accepted = candidate end end self . meta_permalink = accepted end | This function check if current permalink is valid . If it is not valid it generate a new from the post title . |
24,057 | def check_lato_blog_tag_parent tag_parent = LatoBlog :: TagParent . find_by ( id : lato_blog_tag_parent_id ) if ! tag_parent errors . add ( 'Tag parent' , 'not exist for the tag' ) throw :abort return end same_language_tag = tag_parent . tags . find_by ( meta_language : meta_language ) if same_language_tag && same_language_tag . id != id errors . add ( 'Tag parent' , 'has another tag for the same language' ) throw :abort return end end | This function check that the category parent exist and has not others tags for the same language . |
24,058 | def prepare_params p results = { } p . each { | k , v | results [ k . to_s ] = v } results . sort . to_h end | Sort the params consistently |
24,059 | def enum_constants constants . select { | constant | value = const_get constant value . is_a? ProgneTapera :: EnumItem } end | Destroy or Update the Enum Items def clear_optional_items |
24,060 | def load_yaml_configuration yaml_config = YAML . load_file ( "#{@rails_root_dir}/config/chronuscop.yml" ) @redis_db_number = yaml_config [ @rails_environment ] [ 'redis_db_number' ] @redis_server_port = yaml_config [ @rails_environment ] [ 'redis_server_port' ] @project_number = yaml_config [ @rails_environment ] [ 'project_number' ] @api_token = yaml_config [ @rails_environment ] [ 'api_token' ] @chronuscop_server_address = yaml_config [ @rails_environment ] [ 'chronuscop_server_address' ] @sync_time_interval = yaml_config [ @rails_environment ] [ 'sync_time_interval' ] end | rails root directory must be set before calling this . |
24,061 | def whois connected do fiber = Fiber . current callbacks = { } callbacks [ 311 ] = @thaum . on ( 311 ) do | event_data | nick = event_data [ :params ] . split ( ' ' ) [ 1 ] if nick . downcase == @nick . downcase @online = true end end callbacks [ 401 ] = @thaum . on ( 401 ) do | event_data | nick = event_data [ :params ] . split ( ' ' ) [ 1 ] if nick . downcase == @nick . downcase @online = false fiber . resume end end callbacks [ 318 ] = @thaum . on ( 318 ) do | event_data | nick = event_data [ :params ] . split ( ' ' ) [ 1 ] if nick . downcase == @nick . downcase fiber . resume end end raw "WHOIS #{@nick}" Fiber . yield callbacks . each do | type , callback | @thaum . callbacks [ type ] . delete ( callback ) end end self end | Updates the properties of an user . |
24,062 | def attributes _attributes . inject ( HashWithIndifferentAccess . new ) do | hash , attribute | hash . update attribute => send ( attribute ) end end | don t override this method without calling super! |
24,063 | def permission_attributes = ( permissions ) self . permissions = [ ] permissions . each do | key , value | key , value = key . dup , value . dup if key . ends_with? "_permissions" grant_permissions ( value ) elsif key . chomp! "_permission" grant_permissions ( key ) if value . to_i != 0 end end end | Used by advanced permission forms which group permissions by their associated component or using a single check box per permission . |
24,064 | def has_permission? ( * levels ) if levels . all? { | level | permissions . include? level . to_sym } return true else return false end end | Returns true if the object has all the permissions specified by + levels + |
24,065 | def method_missing ( method_name , * args , & block ) case method_name . to_s when / / return component_permissions_reader ( method_name ) if respond_to? ( :joinable_type ) && joinable_type . present? when / / return single_permission_reader ( method_name ) if respond_to? ( :joinable_type ) && joinable_type . present? end super end | Adds readers for component permission groups and single permissions |
24,066 | def verify_and_sort_permissions self . permissions += [ :find , :view ] unless is_a? ( DefaultPermissionSet ) raise "Invalid permissions: #{(permissions - allowed_permissions).inspect}. Must be one of #{allowed_permissions.inspect}" unless permissions . all? { | permission | allowed_permissions . include? permission } self . permissions = permissions . uniq . sort_by { | permission | allowed_permissions . index ( permission ) } end | Verifies that all the access levels are valid for the attached permissible Makes sure no permissions are duplicated Enforces the order of access levels in the access attribute using the order of the permissions array |
24,067 | def verify ( options = { } , & block ) approval = Git :: Approvals :: Approval . new ( approval_path , options ) approval . diff ( block . call ) do | err | :: RSpec :: Expectations . fail_with err end rescue Errno :: ENOENT => e :: RSpec :: Expectations . fail_with e . message EOS end | Verifies that the result of the block is the same as the approved version . |
24,068 | def approval_filename parts = [ example , * example . example_group . parent_groups ] . map do | ex | Git :: Approvals :: Utils . filenamify ex . description end File . join parts . to_a . reverse end | The approval filename |
24,069 | def aggregate_and_create ( oftype , ts = Time . now . floor ) Octo :: Enterprise . each do | enterprise | calculate ( enterprise . id , oftype , ts ) end end | Aggregates and creates trends for all the enterprises for a specific trend type at a specific timestamp |
24,070 | def aggregate! ( ts = Time . now . floor ) aggregate_and_create ( Octo :: Counter :: TYPE_MINUTE , ts ) end | Override the aggregate! defined in counter class as the calculations for trending are a little different |
24,071 | def calculate ( enterprise_id , trend_type , ts = Time . now . floor ) args = { enterprise_id : enterprise_id , ts : ts , type : trend_type } klass = @trend_for . constantize hitsResult = klass . public_send ( :where , args ) trends = hitsResult . map { | h | counter2trend ( h ) } grouped_trends = trends . group_by { | x | x . ts } grouped_trends . each do | _ts , trendlist | sorted_trendlist = trendlist . sort_by { | x | x . score } sorted_trendlist . each_with_index do | trend , index | trend . rank = index trend . type = trend_type trend . save! end end end | Performs the actual trend calculation |
24,072 | def get_trending ( enterprise_id , type , opts = { } ) ts = opts . fetch ( :ts , Time . now . floor ) args = { enterprise_id : enterprise_id , ts : opts . fetch ( :ts , Time . now . floor ) , type : type } res = where ( args ) . limit ( opts . fetch ( :limit , DEFAULT_COUNT ) ) enterprise = Octo :: Enterprise . find_by_id ( enterprise_id ) if res . count == 0 and enterprise . fakedata? Octo . logger . info 'Beginning to fake data' res = [ ] if ts . class == Range ts_begin = ts . begin ts_end = ts . end ts_begin . to ( ts_end , 1 . day ) . each do | _ts | 3 . times do | rank | items = @trend_class . constantize . send ( :where , { enterprise_id : enterprise_id } ) . first ( 10 ) if items . count > 0 uid = items . shuffle . pop . unique_id _args = args . merge ( ts : _ts , rank : rank , score : rank + 1 , uid : uid ) res << self . new ( _args ) . save! end end end elsif ts . class == Time 3 . times do | rank | uid = 0 items = @trend_class . constantize . send ( :where , { enterprise_id : enterprise_id } ) . first ( 10 ) if items . count > 0 uid = items . shuffle . pop . unique_id _args = args . merge ( rank : rank , score : rank + 1 , uid : uid ) res << self . new ( _args ) . save! end end end end res . map do | r | clazz = @trend_class . constantize clazz . public_send ( :recreate_from , r ) end end | Gets the trend of a type at a time |
24,073 | def counter2trend ( counter ) self . new ( { enterprise : counter . enterprise , score : score ( counter . divergence ) , uid : counter . uid , ts : counter . ts } ) end | Converts a couunter into a trend |
24,074 | def example_pending ( example ) if example_group . metadata [ :feature ] && example . metadata [ :skipped ] @skipped_examples << pending_examples . delete ( example ) @skipped_count += 1 output . puts cyan ( "#{current_indentation}#{example.description}" ) else super end end | Builds a new formatter for outputting Uninhibited features . |
24,075 | def summary_line ( example_count , failure_count , pending_count ) pending_count -= skipped_count summary = pluralize ( example_count , "example" ) summary << " (" summary << red ( pluralize ( failure_count , "failure" ) ) summary << ", " << yellow ( "#{pending_count} pending" ) if pending_count > 0 summary << ", " << cyan ( "#{skipped_count} skipped" ) if skipped_count > 0 summary << ")" summary end | Generates a colorized summary line based on the supplied arguments . |
24,076 | def run PayuLatam :: SubscriptionService . new ( context . params , context . current_user ) . call rescue => exception fail! ( exception . message ) end | metodo principal de esta clase al estar en un rescue evitamos que el proyecto saque error 500 cuando algo sale mal INTERCEPTAMOS el error y lo enviamos al controller para que trabaje con el |
24,077 | def coalesce ( other ) @sum += other . sum @sumsq += other . sumsq if other . num > 0 @min = other . min if @min > other . min @max = other . max if @max < other . max @last = other . last end @num += other . num end | Coalesce the statistics from the _other_ sampler into this one . The _other_ sampler is not modified by this method . |
24,078 | def sample ( s ) @sum += s @sumsq += s * s if @num == 0 @min = @max = s else @min = s if @min > s @max = s if @max < s end @num += 1 @last = s end | Adds a sampling to the calculations . |
24,079 | def sd return 0.0 if num < 2 begin return Math . sqrt ( ( sumsq - ( sum * sum / num ) ) / ( num - 1 ) ) rescue Errno :: EDOM return 0.0 end end | Calculates the standard deviation of the data so far . |
24,080 | def coalesce ( other ) sync { other . stats . each do | name , sampler | stats [ name ] . coalesce ( sampler ) end } end | Create a new Tracker instance . An optional boolean can be passed in to change the threadsafe value of the tracker . By default all trackers are created to be threadsafe . |
24,081 | def time ( event ) sync { stats [ event ] . mark } yield ensure sync { stats [ event ] . tick } end | Time the execution of the given block and store the results in the named _event_ sampler . The sampler will be created if it does not exist . |
24,082 | def periodically_run ( period , & block ) raise ArgumentError , 'a runner already exists' unless @runner . nil? @runner = Thread . new do start = stop = Time . now . to_f loop do seconds = period - ( stop - start ) seconds = period if seconds <= 0 sleep seconds start = Time . now . to_f break if Thread . current [ :stop ] == true if @mutex then @mutex . synchronize ( & block ) else block . call end stop = Time . now . to_f end end end | Periodically execute the given _block_ at the given _period_ . The tracker will be locked while the block is executing . |
24,083 | def write ( target , gzip : options [ :gzip ] , hash : options [ :hash ] ) asset = assets [ target ] return if asset . nil? name = hash ? asset . digest_path : asset . logical_path . to_s name = File . join ( options [ :output ] , name ) unless options [ :output ] . nil? path = name path = File . join ( directory , path ) unless directory . nil? write ( target , gzip : gzip , hash : false ) if hash == :also_unhashed asset . write_to "#{path}.gz" , compress : true if gzip asset . write_to path name end | Write a target asset to file with a hashed name . |
24,084 | def computed_path ( context ) @_path ||= case @path when String , Hash @path when Symbol context . public_send ( @path ) when Proc context . instance_exec ( & @path ) else raise ArgumentError , "Expected one of String, Symbol, or Proc, " "got #{@path.class}" end end | Computes the path of the breadcrumb under the given context . |
24,085 | def computed_name ( context ) @_name ||= case @name when String @name when Symbol I18n . translate ( @name ) when Proc context . instance_exec ( & @name ) when nil computed_path ( context ) else raise ArgumentError , "Expected one of String, Symbol, or Proc, " "got #{@name.class}" end end | Computes the name of the breadcrumb under the given context . |
24,086 | def read bookmark_file = Dir . glob ( File . expand_path ( path ) ) . shift raise "Did not find file #{path}" unless bookmark_file db = SQLite3 :: Database . new ( path ) import = db . execute ( QUERY_STRING ) end | Reads the links from the Firefox database places . sqlite |
24,087 | def rows read . map do | row | a = row [ 0 ] ; b = row [ 1 ] ; c = row [ 2 ] ; d = row [ 3 ] ; e = row [ 4 ] ; f = row [ 5 ] [ a , b || c , ( d || '' ) . gsub ( "\n" , ' ' ) , [ e , f ] . join ( ',' ) . gsub ( / / , '' ) ] end end | Returns row values in Arrays |
24,088 | def to_png return @png_data if ! @png_data . nil? image = minimagick_image image . resize '16x16!' image . format 'png' image . strip @png_data = image . to_blob raise FaviconParty :: InvalidData . new ( "Empty png" ) if @png_data . empty? @png_data end | Export source_data as a 16x16 png |
24,089 | def extract_repo ( path , destination , reference ) fail 'Git not installed' unless Utils . command? 'git' Dir . chdir path do system "git archive #{reference} | tar -x -C #{destination}" end end | Extract repository files at a particular reference to directory . |
24,090 | def call buffer = ActiveSupport :: SafeBuffer . new @breadcrumbs . each do | breadcrumb | buffer << @block . call ( breadcrumb . computed ( @context ) ) end buffer end | Creates a buffer and iterates over every breadcrumb yielding the breadcrumb to the block given on initialization . |
24,091 | def call outer_tag = @options . fetch ( :outer , "ol" ) inner_tag = @options . fetch ( :inner , "li" ) outer = tag ( outer_tag , @options . fetch ( :outer_options , nil ) , true ) if outer_tag inner = tag ( inner_tag , @options . fetch ( :inner_options , nil ) , true ) if inner_tag buffer = ActiveSupport :: SafeBuffer . new buffer . safe_concat ( outer ) if outer_tag @breadcrumbs . each do | breadcrumb | buffer . safe_concat ( inner ) if inner_tag buffer << link_to ( breadcrumb . computed_name ( @context ) , breadcrumb . computed_path ( @context ) , breadcrumb . options ) buffer . safe_concat ( "</#{inner_tag}>" ) if inner_tag end buffer . safe_concat ( "</#{outer_tag}>" ) if outer_tag buffer end | Renders the breadcrumbs in HTML tags . If no options were provided on initialization it uses defaults . |
24,092 | def acquire id , fiber if conn = @available . pop @reserved [ id ] = conn else Fiber . yield @pending . push ( fiber ) acquire ( id , fiber ) end end | Acquire a lock on a connection and assign it to executing fiber - if connection is available pass it back to the calling block - if pool is full yield the current fiber until connection is available |
24,093 | def method_missing method , * args , & blk __reserve__ do | conn | if @trace conn . trace ( @trace ) { conn . __send__ ( method , * args , & blk ) } else conn . __send__ ( method , * args , & blk ) end end end | Allow the pool to behave as the underlying connection |
24,094 | def transmit! bits bytes_sent = @handle . bulk_transfer dataOut : bits , endpoint : USB_ENDPOINT_OUT bytes_sent == bits . length end | Creates a connection to the NXT brick . |
24,095 | def transceive bits raise :: LegoNXT :: BadOpCodeError unless bytestring ( DirectOps :: REQUIRE_RESPONSE , SystemOps :: REQUIRE_RESPONSE ) . include? bits [ 0 ] raise :: LegoNXT :: TransmitError unless transmit! bits bytes_received = @handle . bulk_transfer dataIn : 64 , endpoint : USB_ENDPOINT_IN return bytes_received end | Sends a packet string of bits and then receives a result . |
24,096 | def open context = LIBUSB :: Context . new device = context . devices ( :idVendor => LEGO_VENDOR_ID , :idProduct => NXT_PRODUCT_ID ) . first raise :: LegoNXT :: NoDeviceError . new ( "Please make sure the device is plugged in and powered on" ) if device . nil? @handle = device . open @handle . claim_interface ( 0 ) end | Opens the connection |
24,097 | def handle_special_fields if [ 'referer_host' , 'referer_path' , 'referer_params' , 'search_engine' , 'search_query' ] . include? ( params [ :field ] ) @items = @items . only_first_in_session end if [ 'search_engine' , 'search_query' ] . include? ( params [ :field ] ) @items = @items . without_nil_in params [ :field ] end if params [ :field ] == 'entry_path' params [ :field ] = 'path' @items = @items . only_first_in_session end super end | Handle special fields |
24,098 | def referenced_element ref = @xml . attributes [ 'ref' ] . value @referenced_element ||= if ref =~ / / prefix , element = ref . split ( ':' ) schema . find_element ( element ) || schema . find_attribute ( "@#{element}" ) if schema = Schema . find ( prefix ) else self . schema . find_element ( ref ) || self . schema . find_attribute ( "@#{ref}" ) end end | Only valid if this is a reference . Also works for attributes this was a crappy name |
24,099 | def item ( price , item_name ) @current_nesting_level [ item_name . to_s ] = price . respond_to? ( :to_hash ) ? price . to_hash : price . to_i end | Creates PriceBuilder on a target object . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.