idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
19,300
def get_email_template url = ApiRequest . base_path ( "questionpro.survey.getEmailTemplate" ) result = self . class . get ( url , body : self . options ) self . full_response = result self . status = result [ 'status' ] email_template = EmailTemplate . new ( result [ 'response' ] [ 'emailTemplate' ] ) return email_temp...
Get Specific Template . Template ID must be set inside the api request object .
19,301
def get_all_accounts url = ApiRequest . base_path ( "questionpro.survey.getAllAccounts" ) result = self . class . get ( url , body : self . options ) self . full_response = result self . status = result [ 'status' ] accounts = [ ] result_accounts = result [ 'response' ] [ 'accounts' ] result_accounts . each do | accoun...
Get all the accounts that belongs to the api key s owner .
19,302
def get_account url = ApiRequest . base_path ( "questionpro.survey.getAccount" ) result = self . class . get ( url , body : self . options ) self . full_response = result self . status = result [ 'status' ] account = Account . new ( result [ 'response' ] [ 'account' ] ) return account end
Get Specific Account . User ID must be set inside the api request object .
19,303
def get_unsubscribers url = ApiRequest . base_path ( "questionpro.survey.getUnsubscribedEmailAddresses" ) result = self . class . get ( url , body : self . options ) self . full_response = result self . status = result [ 'status' ] unsubscribers = [ ] result_unsubscribers = result [ 'response' ] [ 'response' ] result_u...
Get Unsubscribed Emails related to the api key .
19,304
def get_survey_meta url = ApiRequest . base_path ( "questionpro.survey.sendSurveyMetaData" ) result = self . class . get ( url , body : self . options ) self . full_response = result self . status = result [ 'status' ] survey_meta = SurveyMeta . new ( result [ 'response' ] ) return survey_meta end
Survey ID must be set inside the api request object .
19,305
def send_survey ( mode = 1 , emails = nil , template_id = nil ) url = ApiRequest . base_path ( "questionpro.survey.sendSurvey" ) result = self . class . get ( url , body : { surveyID : self . survey_id , mode : mode , emailGroupID : self . email_group_id , emails : emails , templateID : self . template_id , template : ...
Send Specific Survey . Survey ID must be set inside the api request object .
19,306
def get_send_history url = ApiRequest . base_path ( "questionpro.survey.emailBatchStatistics" ) result = self . class . get ( url , body : self . options ) self . full_response = result self . status = result [ 'status' ] email_batches = [ ] result_email_batches = result [ 'response' ] [ 'emailBatches' ] result_email_b...
Get Send History related to a specific survey . Survey ID must be set inside the api request object .
19,307
def send_reminders url = ApiRequest . base_path ( "questionpro.survey.sendReminder" ) result = self . class . get ( url , body : self . options ) self . full_response = result self . status = result [ 'status' ] self . message = result [ 'response' ] [ 'result' ] end
Send Reminders . Survey ID must be set inside the api request object . Email Group ID must be set inside the api request object . Template ID must be set inside the api request object .
19,308
def create_email_list ( emails = [ ] , email_group_name = nil ) url = ApiRequest . base_path ( "questionpro.survey.createEmailGroup" ) result = self . class . get ( url , body : { id : self . survey_id , emails : emails , emailGroupName : email_group_name } . compact . to_json ) self . full_response = result self . sta...
Create Email List . Survey ID must be set inside the api request object .
19,309
def questions extracted_questions = [ ] unless self . qp_questions . nil? self . qp_questions . each do | question | extracted_questions . push ( Question . new ( question ) ) end end return extracted_questions end
Extract the Questions from the hashes stored inside qp_questions attribute .
19,310
def ldiff ( license ) xml = Nokogiri :: XML ( File . open ( @path ) , & :noblanks ) comment = xml . xpath ( '/comment()' ) [ 0 ] now = comment . nil? ? '' : comment . text . to_s . strip ideal = license . strip differ ( ideal , now ) end
Return the difference for the license .
19,311
def fix ( license = '' ) xml = Nokogiri :: XML ( File . open ( @path ) , & :noblanks ) unless license . empty? xml . xpath ( '/comment()' ) . remove xml . children . before ( Nokogiri :: XML :: Comment . new ( xml , "\n#{license.strip}\n" ) ) end ideal = xml . to_xml ( indent : 2 ) File . write ( @path , ideal ) end
Fixes the document .
19,312
def start ( turn ) game_context . check_turn ( turn ) game_context . set_turn_and_clear_grid ( turn ) engine . transition_to_state_and_send_event ( Playing , :game_started ) end
Starts a new game .
19,313
def sections extracted_sections = [ ] unless self . qp_sections . nil? self . qp_sections . each do | section | extracted_sections . push ( Section . new ( section ) ) end end return extracted_sections end
Extract the Sections from the hashes stored inside qp_sections attribute .
19,314
def stats ( cmd_options = { } ) raw = hg ( [ "log -r ? --stat --template '{node}\n'" , hash_id ] , cmd_options ) result = raw . scan ( / \d \d \( \+ \) \d \( \- \) / ) . flatten . map { | r | r . to_i } return { } if result . empty? { 'files' => result [ 0 ] , 'additions' => result [ 1 ] , 'deletions' => result [ 2 ] ,...
Returns a Hash of diffstat - style summary of changes for the commit .
19,315
def build ( row ) build_row! ( row ) rescue ArgumentError => e raise unless e . message == 'struct size differs' raise_invalid_row_length! ( e , row ) end
Returns a new instance of RowBuilder .
19,316
def find_header ( header ) { } . tap do | returning | contents . scan ( header_with_content_regexp ( header ) ) . flatten . first . split ( "\n" ) . each do | setting | name , value = * setting . split ( '=' ) . map ( & :strip ) returning [ name ] = value end end end
Returns content of the specified section of hgrc .
19,317
def find_setting ( header , setting ) return nil if contents . nil? contents . scan ( setting_regexp ( header , setting ) ) . flatten . first end
Returns content of the specified setting from a section .
19,318
def add ( name , value ) build ( name , value ) . tap do | hook | hook . save end end
Adds a new hook to the repository .
19,319
def create_without_callbacks ( bulk = false ) raise ArgumentError , "a document requires a database to be created to (The document or the #{self.class} default database were not set)" unless database set_unique_id if new? && self . respond_to? ( :set_unique_id ) result = database . save_doc ( self , bulk ) ( result [ "...
unlike save create returns the newly created document
19,320
def save ( ** options ) if use_refresh_token? options [ :ttl ] = self . created_at + 6 . months else options [ :ttl ] = self . created_at + self . expires_in + 30 end super ( ** options ) end
Lets make sure these keys are not clogging up the database forever
19,321
def to_csv ( columns : nil ) attributes = members attributes = columns & attributes if columns row = attributes . map! { | column | to_csv_value ( column ) } :: CSV . generate_line ( row ) end
Represent row as CSV
19,322
def inspect attributes = members . map do | field | value = self [ field ] value = "\"#{value}\"" if value . is_a? ( String ) [ field , value ] . join ( '=' ) end . join ( ', ' ) "#<Row #{attributes}>" end
Describe the contents of this row in a string .
19,323
def to_csv_value ( column ) value = public_send ( column ) return if value . nil? return value . to_csv if value . respond_to? ( :to_csv ) value . to_s end
Returns the column in CSV format
19,324
def update ( oldrev = nil , newrev = nil ) if index_file_exists? && oldrev != "0" * 40 hg ( [ "log --debug -r ?:? --style ? >> ?" , oldrev , newrev , Style . file_index , path ] ) else hg ( [ "log --debug -r : --style ? > ?" , Style . file_index , path ] ) end end
updates file index
19,325
def commits_from ( commit_sha ) raise UnsupportedRef if commit_sha . is_a? Array read_if_needed already = { } final = [ ] left_to_do = [ commit_sha ] while commit_sha = left_to_do . shift next if already [ commit_sha ] final << commit_sha already [ commit_sha ] = true commit = @commit_index [ commit_sha ] commit [ :par...
builds a list of all commits reachable from a single commit
19,326
def update_attributes_without_saving ( hash ) hash . each do | k , v | raise NoMethodError , "#{k}= method not available, use property :#{k}" unless self . respond_to? ( "#{k}=" ) end hash . each do | k , v | self . send ( "#{k}=" , v ) end end
Sets the attributes from a hash
19,327
def term_hash @terms . inject ( { } ) { | sum , t | sum . update ( t . name . value => t . id . value ) } end
Warning! This assumes terms are unique they are NOT required to be so in an OBO file . Ignores hash colisions!!
19,328
def answers extracted_answers = [ ] unless self . qp_values . nil? self . qp_values . each do | answer | extracted_answers . push ( ResponseAnswer . new ( answer ) ) end end return extracted_answers end
Extract the Answers from the hashes stored inside qp_values attribute .
19,329
def acts_as_approvable ( options = { } ) extend ClassMethods include InstanceMethods cattr_accessor :approvable_on self . approvable_on = Array . wrap ( options . delete ( :on ) { [ :create , :update , :destroy ] } ) cattr_accessor :approvable_field self . approvable_field = options . delete ( :state_field ) cattr_acce...
Declare this in your model to require approval on new records or changes to fields .
19,330
def require_jars! require 'jruby' MARC :: MARC4J . new ( :jardir => settings [ 'marc4j_reader.jar_dir' ] ) java_import "org.marc4j.converter.impl.AnselToUnicode" unless defined? Java :: net . sourceforge . jtds . jdbc . Driver jtds_jar_dir = settings [ "jtds.jar_path" ] || File . expand_path ( "../../vendor/jtds" , Fil...
We ignore the iostream even though we get one we re gonna read from a Horizon DB! Requires marc4j and jtds and java_import s some classes .
19,331
def convert_text! ( text , error_handler ) text = AnselToUnicode . new ( error_handler , true ) . convert ( text ) if convert_marc8_to_utf8? if settings [ "horizon.destination_encoding" ] == "UTF8" && ( settings [ "horizon.codepoint_translate" ] . to_s == "true" || settings [ "horizon.character_reference_translate" ] ....
Converts from Marc8 to UTF8 if neccesary .
19,332
def fix_leader! ( leader ) if leader . length < 24 leader . replace ( leader . ljust ( 24 , ' ' ) ) elsif leader . length > 24 leader . replace ( leader . byteslice ( 0 , 24 ) ) end leader [ 10 .. 11 ] = '22' leader [ 20 .. 23 ] = '4500' if settings [ 'horizon.destination_encoding' ] == "UTF8" leader [ 9 ] = 'a' end le...
Mutate string passed in to fix leader bytes for marc21
19,333
def softmax ( w ) e = Numo :: NMath . exp ( w - ( w . max ) ) dist = e / ( e . sum ) return dist end
using softmax as output layer is recommended for classification where outputs are mutually exclusive
19,334
def normalize_name ( context , constant = nil ) case context when constant context . name when Symbol context . to_s else context end end
Normalizes the various different input objects to Strings
19,335
def << ( cbor ) @buffer . write ( cbor ) @decoding_fiber . resume rescue FiberError => e msg = e . message if msg . include? ( "dead" ) raise Cborb :: InvalidByteSequenceError elsif msg . include? ( "threads" ) raise Cborb :: DecodingError , "Can't decode across threads" else raise end end
Buffering new CBOR data
19,336
def consume ( size ) data = @buffer . read ( size ) . to_s if data . size < size @buffer . reset! while data . size != size Fiber . yield data += @buffer . read ( size - data . size ) end end data end
Consume CBOR data . This method will be called only in fiber .
19,337
def email_groups extracted_groups = [ ] unless self . email_groups_list . nil? self . email_groups_list . each do | email_group | extracted_groups . push ( EmailGroup . new ( email_group ) ) end end return extracted_groups end
Extract the Email Groups from the hashes stored inside email_groups_list attribute .
19,338
def templates extracted_templates = [ ] unless self . templates_list . nil? self . templates_list . each do | template | extracted_templates . push ( Template . new ( template ) ) end end return extracted_templates end
Extract the Templates from the hashes stored inside templates_list attribute .
19,339
def matching ( staging_record , table_name = nil ) table_name , id = Stagehand :: Key . generate ( staging_record , :table_name => table_name ) prepare_to_modify ( table_name ) return Record . where ( :id => id ) end
Returns a scope that limits results any occurrences of the specified record . Record can be specified by passing a staging record or an id and table_name .
19,340
def subscribe ( caller = nil , & block ) if block_given? notify_when = block . call ( state ) @listeners << { obj : block . binding . receiver , notify_when : notify_when } else @listeners << { obj : caller } end end
Allow subscribing either by passing a reference to self or by passing a block which defines the state keys that this listener cares about
19,341
def strap_reducers ( reducers ) reducers . each { | k , reducer | set_state * [ k , reducer . map_state ( type : nil ) ] } reducers end
Initialize state with the key - value pair associated with each reducer
19,342
def add ( path , prefix = nil ) path = File . expand_path path prefix ||= '/' in_work_tree File . dirname ( path ) do index = @git . index index . read_tree 'HEAD' add = lambda do | f , p | file = File . basename f pre = ( p == '/' ) ? file : File . join ( p , file ) dir = File . stat ( f ) . directory? if dir ( Dir . ...
Creates a new repository instance on the given path
19,343
def add_remote ( name , url ) @remotes [ name ] = Remote :: Git . new ( self , name , url ) @remotes [ name ] . add end
Adds a new remote to this Repository
19,344
def contents ( path = nil ) contents = [ ] object = find_object ( path || '/' ) contents << path unless path . nil? || object . nil? if object . is_a? Grit :: Tree ( object . blobs + object . trees ) . each do | obj | contents += contents ( path . nil? ? obj . basename : File . join ( path , obj . basename ) ) end end ...
Gets a list of files and directories in the specified path inside the repository
19,345
def git_remotes remotes = { } @git . git . remote . split . each do | remote | url = @git . git . config ( { } , '--get' , "remote.#{remote}.url" ) . strip remotes [ remote ] = Remote :: Git . new ( self , remote , url ) end remotes end
Loads remotes from the backing Git repository s configuration
19,346
def history ( path = nil ) params = [ '--format=raw' ] params += [ '--' , path ] unless path . nil? output = @git . git . log ( { } , * params ) Grit :: Commit . list_from_string @git , output end
Generate a history of Git commits for either the complete repository or a specified file or directory
19,347
def info ( path ) info = { } object = object! path info [ :history ] = history path info [ :mode ] = object . mode info [ :name ] = object . name info [ :path ] = path info [ :sha ] = object . id info [ :created ] = info [ :history ] . last . committed_date info [ :modified ] = info [ :history ] . first . committed_dat...
Get information about a file or directory in the repository
19,348
def prepare raise AlreadyPreparedError . new ( @path ) if prepared? in_work_tree :tmp do FileUtils . touch '.silo' @git . add '.silo' @git . commit_index 'Enabled Silo for this repository' end end
Prepares the Git repository backing this Silo repository for use with Silo
19,349
def purge ( path , prune = true ) object = object! path if object . is_a? Grit :: Tree ( object . blobs + object . trees ) . each do | blob | purge File . join ( path , blob . basename ) , prune end else params = [ '-f' , '--index-filter' , "git rm --cached --ignore-unmatch #{path}" ] params << '--prune-empty' if prune...
Purges a single file or the complete structure of a directory with the given path from the repository
19,350
def remove ( path ) object = object! path path += '/' if object . is_a? ( Grit :: Tree ) && path [ - 1 ] . chr != '/' index = @git . index index . read_tree 'HEAD' index . delete path type = object . is_a? ( Grit :: Tree ) ? 'directory' : 'file' commit_msg = "Removed #{type} #{path}" index . commit commit_msg , [ @git ...
Removes a single file or the complete structure of a directory with the given path from the HEAD revision of the repository
19,351
def remove_remote ( name ) remote = @remotes [ name ] raise UndefinedRemoteError . new ( name ) if remote . nil? remote . remove @remotes [ name ] = nil end
Removes the remote with the given name from this repository
19,352
def restore ( path , prefix = '.' ) object = object! path prefix = File . expand_path prefix FileUtils . mkdir_p prefix unless File . exists? prefix file_path = File . join prefix , File . basename ( path ) if object . is_a? Grit :: Tree FileUtils . mkdir file_path unless File . directory? file_path ( object . blobs + ...
Restores a single file or the complete structure of a directory with the given path from the repository
19,353
def inject_solr_document_behavior file_path = 'app/models/solr_document.rb' if File . exist? ( file_path ) inject_into_file file_path , after : / / do "\n # Adds GeoWorks behaviors to the SolrDocument.\n" " include GeoWorks::SolrDocumentBehavior\n" end else Rails . logger . info " \e[31mFailure\e[0m GeoWorks req...
Add behaviors to the SolrDocument model
19,354
def response_set extracted_sets = [ ] unless self . qp_response_set . nil? self . qp_response_set . each do | set | extracted_sets . push ( ResponseSet . new ( set ) ) end end return extracted_sets end
Extract the Response Set from the hash stored inside qp_response_set attribute .
19,355
def url_for_page ( page ) view . url_for ( view . default_url_options . merge ( { page_param . to_sym => page } ) . merge ( options [ :params ] || { } ) ) end
setup rails_paginate collection build url
19,356
def link_to_page ( page , key , link_options = { } ) css_class = "#{link_options[:class]} #{page == current_page ? 'current' : ''}" if key . nil? content_tag :span , ".." , :class => "spacer" elsif page . nil? content_tag :span , t ( key ) , :class => "#{css_class} unavailable" else link_to t ( key , :page => page ) , ...
link to page with i18n support
19,357
def stop server = Communist . servers . delete ( app . object_id ) { | s | NullServer . new } if Communist . server . respond_to? ( :shutdown ) server . shutdown elsif Communist . server . respond_to? ( :stop! ) server . stop! else server . stop end @server_thread . join end
Stops the server after handling the connection . Attempts to stop the server gracefully otherwise shuts current connection right away .
19,358
def displayed_pages ( limit = 10 , left_offset = - 5 , right_offset = 4 ) lower , upper = nil , nil if page + left_offset < 1 || page + right_offset > pages . last lower = [ page , [ pages . last - limit , 0 ] . max + 1 ] . min upper = [ page + limit - 1 , pages . last ] . min else lower = page + left_offset upper = pa...
Provides dirt - simple logic for spitting out page numbers based on the current page .
19,359
def ping res = transport . get ( '' ) { | r | r . headers [ 'Accept' ] = 'text/plain' } res . status == 200 && res . body == "Nebula.Api v2" rescue StandardError => _e return false end
Below actual methods from api
19,360
def wait ( i , & block ) @order [ i ] = block return unless i == @current while order [ @current ] order . delete ( @current ) . call @current += 1 end end
Executes block if it s its turn queues the block in the other case .
19,361
def call_api_with_retry ( options = { } ) config = self . class . retriable_configuration config . merge! ( Take2 . local_defaults ( options ) ) unless options . empty? tries ||= config [ :retries ] begin yield rescue => e if config [ :retriable ] . map { | klass | e . class <= klass } . any? unless tries . zero? || co...
Yields a block and retries on retriable errors n times . The raised error could be the defined retriable or it child .
19,362
def number_of_retries ( num ) raise ArgumentError , 'Must be positive Integer' unless num . is_a? ( Integer ) && num . positive? self . retries = num end
Sets number of retries .
19,363
def retriable_errors ( * errors ) message = 'All retriable errors must be StandardError decendants' raise ArgumentError , message unless errors . all? { | e | e <= StandardError } self . retriable = errors end
Sets list of errors on which the block will retry .
19,364
def backoff_strategy ( options ) available_types = [ :constant , :linear , :fibonacci , :exponential ] raise ArgumentError , 'Incorrect backoff type' unless available_types . include? ( options [ :type ] ) self . backoff_intervals = Backoff . new ( options [ :type ] , options [ :start ] ) . intervals end
Sets the backoff strategy
19,365
def retriable_configuration Take2 :: Configuration :: CONFIG_ATTRS . each_with_object ( { } ) do | key , hash | hash [ key ] = send ( key ) end end
Exposes current class configuration
19,366
def install fetch parse_package_json determine_name_and_version if ! name || name . to_s =~ / \s / raise ( Jim :: InstallError , "Could not determine name for #{@fetched_path}" ) end logger . info "Installing #{name} #{version}" logger . debug "fetched_path #{@fetched_path}" if options [ :shallow ] shallow_filename = [...
Fetch and install the files determining their name and version if not provided . If the fetch_path contains a directory of files it iterates over the directory installing each file that isn t in IGNORE_DIRS and a name and version can be determined for . It also installs a package . json file along side the JS file that...
19,367
def validate_casted_arrays result = true array_casted_properties = self . class . properties . select { | property | property . casted && property . type . instance_of? ( Array ) } array_casted_properties . each do | property | casted_values = self . send ( property . name ) next unless casted_values . is_a? ( Array ) ...
checking on casted objects
19,368
def recursive_valid? ( target , context , state ) valid = state target . each do | key , prop | if prop . is_a? ( Array ) prop . each do | item | if item . validatable? valid = recursive_valid? ( item , context , valid ) && valid end end elsif prop . validatable? valid = recursive_valid? ( prop , context , valid ) && v...
Do recursive validity checking
19,369
def call ( value , type ) return type . call ( value ) if type . respond_to? ( :call ) self [ type ] . call ( value ) end
Call value type
19,370
def []= ( type , caller ) type = to_key ( type ) if type? ( type ) raise ( Errors :: TypeExistsError , "type '#{type}' already exists" ) end @callers [ type ] = caller end
Register a caller
19,371
def write message = '' response = self . class . write message , @params message = response [ 'message' ] response . keep_if { | key , value | DEFAULT_PARAMS . keys . include? key } @params . merge! response @params . delete_if { | key , value | DEFAULT_PARAMS [ key ] == value } message end
Initializes a Client with given parameters .
19,372
def pass! ( interops = { } , options = { } , & block ) options [ :unsafe ] = @unsafe env = options . delete ( :env ) || { } backend . call ( * contents ( interops ) , env , options , & block ) rescue Errno :: ENOENT raise NoCommandError , @command end
Initialize the messenger .
19,373
def each ( 1 .. ROWS ) . each do | r | ( 1 .. COLS ) . each do | c | yield ( r , c , self [ r , c ] ) end end end
Iterates over all the positions of this grid from left to right and top to bottom .
19,374
def each_open self . each { | r , c , _ | yield ( r , c ) if open? ( r , c ) } end
Iterates over all the open positions of this grid from left to right and top to bottom .
19,375
def connected? ( klass ) return false if Process . pid != @process_pid . get conn = self . retrieve_connection_pool ( klass ) conn && conn . connected? end
Returns true if a connection that s accessible to this class has already been opened .
19,376
def all_children ( flag = nil ) also_foreign = ( flag == :also_foreign ) arr = [ ] ecore = self . class . ecore already_used_references = [ ] ecore . eAllReferences . sort_by { | r | r . name } . select { | r | r . containment } . each do | ref | unless already_used_references . include? ( ref . name ) res = self . sen...
All direct children
19,377
def all_children_deep ( flag = nil ) arr = [ ] all_children ( flag ) . each do | c | arr << c c . all_children_deep ( flag ) . each do | cc | arr << cc end end arr end
All direct and indirect children
19,378
def traverse ( flag = nil , & op ) op . call ( self ) all_children_deep ( flag ) . each do | c | op . call ( c ) end end
Execute an operation on the node itself and all children direct and indirect .
19,379
def handle_response stdout , stderr , thread unless thread . value . success? dump = "#{thread.value} \n Stderr: #{stderr.read} \n Stdout: #{stdout.read} \n" raise dump end end
Default error handling called in every popen3 call . Only executes if thread had a failing exit code
19,380
def header_deduplicator = ( strategy ) if header_deduplicator_registry . type? ( strategy ) @header_deduplicator = header_deduplicator_registry [ strategy ] elsif strategy . respond_to? ( :call ) @header_deduplicator = strategy else message = "unknown deduplication strategy: '#{strategy}'" raise ( Errors :: UnknownDedu...
Set the deduplication header strategy
19,381
def default_header_deduplicators @default_header_deduplicators ||= { deduplicate : proc do | columns | Helpers . key_count_to_deduplicated_array ( columns ) end , raise : proc do | columns | duplicates = Helpers . duplicated_items ( columns ) if duplicates . any? message = "all columns must be unique, duplicates are: #...
Default header deduplicate strategies
19,382
def default_converters @default_converters ||= { decimal! : StrictConvertDecimal , integer! : StrictConvertInteger , date! : StrictConvertDate , datetime! : StrictConvertDatetime , symbol! : StrictConvertSymbol , downcase! : StrictConvertDowncase , upcase! : StrictConvertUpcase , boolean! : StrictConvertBoolean , decim...
Default converter registry
19,383
def host host = options [ :host ] || @configuration [ 'host' ] host = 'http://api.unipept.ugent.be' if host . nil? || host . empty? if host . start_with? ( 'http://' , 'https://' ) host else "http://#{host}" end end
Returns the host . If a value is defined by both an option and the config file the value of the option is used .
19,384
def input_iterator return arguments . each unless arguments . empty? return IO . foreach ( options [ :input ] ) if options [ :input ] $stdin . each_line end
Returns an input iterator to use for the request . - if arguments are given uses arguments - if the input file option is given uses file input - if none of the previous are given uses stdin
19,385
def selected_fields return @selected_fields unless @selected_fields . nil? fields = [ * options [ :select ] ] . map { | f | f . split ( ',' ) } . flatten fields . concat ( required_fields ) if @fasta && ! fields . empty? @selected_fields = fields . map { | f | glob_to_regex ( f ) } end
Returns an array of regular expressions containing all the selected fields
19,386
def run ServerMessage . new ( @host ) . print unless options [ :quiet ] hydra = Typhoeus :: Hydra . new ( max_concurrency : concurrent_requests ) batch_order = Unipept :: BatchOrder . new last_id = 0 batch_iterator . iterate ( input_iterator ) do | input_slice , batch_id , fasta_mapper | last_id = batch_id @fasta = ! f...
Runs the command
19,387
def save_error ( message ) path = error_file_path FileUtils . mkdir_p File . dirname ( path ) File . open ( path , 'w' ) { | f | f . write message } warn "API request failed! log can be found in #{path}" end
Saves an error to a new file in the . unipept directory in the users home directory .
19,388
def handle_response ( response , batch_id , fasta_mapper ) if response . success? handle_success_response ( response , batch_id , fasta_mapper ) else handle_failed_response ( response ) end end
Handles the response of an API request . Returns a block to execute .
19,389
def filter_result ( json_response ) result = JSON [ json_response ] rescue [ ] result = [ result ] unless result . is_a? Array result . map! { | r | r . select! { | k , _v | selected_fields . any? { | f | f . match k } } } unless selected_fields . empty? result end
Parses the json_response wraps it in an array if needed and filters the fields based on the selected_fields
19,390
def save Dir . chdir ( @gl_admin . working_dir ) do if @config new_conf = @config . to_file ( @confdir ) @gl_admin . add ( new_conf ) end if @ssh_keys files = list_keys ( @keydir ) . map { | f | File . basename f } keys = @ssh_keys . values . map { | f | f . map { | t | t . filename } } . flatten to_remove = ( files - ...
Writes all changed aspects out to the file system will also stage all changes
19,391
def reset! Dir . chdir ( @gl_admin . working_dir ) do @gl_admin . git . reset ( { :hard => true } , 'HEAD' ) @gl_admin . git . clean ( { :d => true , :q => true , :f => true } ) end reload! end
This method will destroy all local tracked changes resetting the local gitolite git repo to HEAD and reloading the entire repository Note that this will also delete all untracked files
19,392
def update ( options = { } ) options = { :reset => true , :rebase => false } . merge ( options ) reset! if options [ :reset ] Dir . chdir ( @gl_admin . working_dir ) do @gl_admin . git . pull ( { :rebase => options [ :rebase ] } , "origin" , "master" ) end reload! end
Updates the repo with changes from remote master
19,393
def load_keys ( path = nil ) path ||= File . join ( @path , @keydir ) keys = Hash . new { | k , v | k [ v ] = DirtyProxy . new ( [ ] ) } list_keys ( path ) . each do | key | new_key = SSHKey . from_file ( File . join ( path , key ) ) owner = new_key . owner keys [ owner ] << new_key end keys . values . each { | set | s...
Loads all . pub files in the gitolite - admin keydir directory
19,394
def event ( user_id , key , val = "" ) opts = { :key => key , :valuestring => val , :user_id => user_id } post "/admin/api/customevent.json" , opts end
Initializes a dailycred object
19,395
def prepare_translations! stash . each do | locale , attrs | if attrs . any? translation = record . translations . find_by_locale ( locale ) translation ||= record . translations . build ( :locale => locale ) attrs . each { | name , value | translation [ name ] = value } end end reset end
Prepares data from stash for persisting in embeded Translation documents . Also clears stash for further operations .
19,396
def fetch_attribute ( locale , name ) translation = record . translation_for ( locale ) return translation && translation . send ( name ) end
Returns persisted value of attribute for given locale or nil .
19,397
def url = ( url ) uri = URI . parse url case uri . scheme when / / default_port = 3306 @engine = :mysql when / / default_port = 5432 @engine = :postgres end raise 'Invalid database url' unless uri . user && uri . host && uri . path @username = uri . user @password = uri . password @hostname = uri . host @port = uri . p...
Handle url - > fields conversion
19,398
def bundle_dir = ( new_dir ) if new_dir new_dir = Pathname . new ( new_dir ) new_dir . mkpath end @bundle_dir = new_dir end
Set the bundle_dir where bundles will be written . If bundle_dir is set to nil all bundles will be written to STDOUT
19,399
def jimfile_to_json h = { "bundle_dir" => bundle_dir } . merge ( options ) h [ 'bundles' ] = { } self . bundles . each do | bundle_name , requirements | h [ 'bundles' ] [ bundle_name ] = [ ] requirements . each do | name , version | h [ 'bundles' ] [ bundle_name ] << if version . nil? || version . strip == '' name else...
Output the parse Jimfile requirements and options as a Jimfile - ready JSON - encoded string