idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
21,100 | def generate_swagger_file delete_file_before File . open ( @swagger_file , 'a+' ) do | file | file . write ( if SwaggerDocsGenerator . configure . compress write_in_swagger_file . to_json else JSON . pretty_generate write_in_swagger_file end ) end end | Open or create a swagger . json file |
21,101 | def mod_for_phrases ( raw_cell , method_name_or_ability_class , card_to_setup ) return unless raw_cell raw_cell . split ( / / ) . each do | raw_cell_part | p = make_parsed_phrase_obj ( raw_cell_part , method_name_or_ability_class ) p . mod_card ( card_to_setup ) if p end end | Raw Cell is the text from the csv file for this column |
21,102 | def method_missing ( meth , * args , & block ) if @categories . include? ( meth ) if block_given? args [ 0 ] = yield block end self :: msg ( meth , args [ 0 ] ) else super end end | This is what responds to Zog . info Zog . error etc |
21,103 | def associate ( model , options = { } ) options [ :only ] = Array ( options [ :only ] ) options [ :except ] = Array ( options [ :except ] ) options [ :depends_on ] = Array ( options [ :depends_on ] ) options = { delegate : true } . merge ( options ) associate = build_associate ( model , options ) self . associates << associate define_associate_delegation ( associate ) if options [ :delegate ] define_associate_instance_setter_method ( associate ) define_associate_instance_getter_method ( associate ) end | Defines an associated model |
21,104 | def build_associate ( model , options = { } ) model_name = model . to_s . underscore model_klass = ( options [ :class_name ] || model ) . to_s . classify . constantize dependent_associate_names = options [ :depends_on ] . map ( & :to_s ) attribute_names = extract_attribute_names ( model_klass , options ) ensure_name_uniqueness ( associates . map ( & :name ) , model_name ) ensure_attribute_uniqueness ( associates . map ( & :attribute_names ) , attribute_names ) if options [ :delegate ] ensure_dependent_names_existence ( associates . map ( & :name ) , dependent_associate_names ) Item . new ( model_name , model_klass , attribute_names , dependent_associate_names , options ) end | Builds an associate |
21,105 | def ensure_attribute_uniqueness ( associates_attribute_names , attribute_names ) attribute_names . each do | attribute_name | if associates_attribute_names . include? ( attribute_name ) raise NameError , "already defined attribute name '#{attribute_name}' for #{name}(#{object_id})" end end end | Ensure associate attribute names don t clash with already declared ones |
21,106 | def ensure_dependent_names_existence ( associates_names , dependent_associate_names ) dependent_associate_names . each do | dependent_name | unless associates_names . include? ( dependent_name ) raise NameError , "undefined associated model '#{dependent_name}' for #{name}(#{object_id})" end end end | Ensure associate dependent names exists |
21,107 | def define_associate_delegation ( associate ) methods = [ associate . attribute_names , associate . attribute_names . map { | attr | "#{attr}=" } ] . flatten send ( :delegate , * methods , to : associate . name ) end | Define associated model attribute methods delegation |
21,108 | def define_associate_instance_setter_method ( associate ) define_method "#{associate.name}=" do | object | unless object . is_a? ( associate . klass ) raise ArgumentError , "#{associate.klass}(##{associate.klass.object_id}) expected, got #{object.class}(##{object.class.object_id})" end instance = instance_variable_set ( "@#{associate.name}" , object ) depending = associates . select { | _associate | _associate . dependent_names . include? ( associate . name ) } depending . each do | _associate | send ( _associate . name ) . send ( "#{associate.name}=" , instance ) end instance end end | Define associated model instance setter method |
21,109 | def define_associate_instance_getter_method ( associate ) define_method associate . name do instance = instance_variable_get ( "@#{associate.name}" ) || instance_variable_set ( "@#{associate.name}" , associate . klass . new ) depending = associates . select { | _associate | _associate . dependent_names . include? ( associate . name ) } depending . each do | _associate | existing = send ( _associate . name ) . send ( associate . name ) send ( _associate . name ) . send ( "#{associate.name}=" , instance ) unless existing end instance end end | Define associated model instance getter method |
21,110 | def account_activation ( data = { } ) @data = { user : nil , client_ip : '0.0.0.0' } . merge ( data || { } ) raise unless data [ :user ] mail to : data [ :user ] . email , subject : 'Account activation' end | Sends the activation email to a new user . |
21,111 | def invalid_password_reset ( data = { } ) @data = { email : nil , message : 'This email address is not associated with an existing account.' , client_ip : '0.0.0.0' } . merge ( data || { } ) raise unless data [ :email ] mail to : data [ :email ] , subject : 'Password reset request' end | Sends an invalid password reset attempt message to a user whether they exist or not . |
21,112 | def configuration_module ( base = self ) Module . new . tap do | cm | delegators = get_configuration_methods base = send ( base ) if base . is_a? ( Symbol ) cm . extend Module . new { delegators . each do | method | module_eval do define_method ( method ) do | * args | base . send ( method , * args ) end end end } end end | Creates and returns anonymous module containing delegators that point to methods from a class this module is included in or the given + base + . |
21,113 | def get_configuration_methods ( local_only = false ) all_delegators = singleton_class . send ( :cf_block_delegators ) + cf_block_delegators return all_delegators if local_only ancestors . each_with_object ( all_delegators ) do | ancestor , all | all . merge ( ancestor . send ( __method__ , true ) ) if ancestor . respond_to? ( __method__ ) end end | Gets all method names known to configuration engine . |
21,114 | def configuration_block_delegate ( * methods ) methods . flatten . each { | m | cf_block_delegators . add ( m . to_sym ) } @cb_conf_module = nil if @cb_conf_module nil end | This DSL method is intended to be used in a class or module to indicate which methods should be delegated . |
21,115 | def configuration_block_core ( conf_module , & block ) return conf_module unless block_given? return conf_module . tap ( & block ) unless block . arity == 0 conf_module . module_eval ( & block ) conf_module end | Evaluates configuration block within a context of the given module . |
21,116 | def show_system_status ( options = { } ) options = { url_on_completion : nil , completion_button : 'Continue' , main_status : 'System is busy' } . merge ( options || { } ) if block_given? clear_system_status Spawnling . new do status = BarkestCore :: GlobalStatus . new if status . acquire_lock status . set_message options [ :main_status ] begin yield status ensure status . release_lock end else yield false end end end session [ :status_comp_url ] = options [ :url_on_completion ] session [ :status_comp_lbl ] = options [ :completion_button ] redirect_to status_current_url end | Shows the system status while optionally performing a long running code block . |
21,117 | def clear_system_status unless BarkestCore :: GlobalStatus . locked? File . open ( BarkestCore :: WorkPath . system_status_file , 'w' ) . close end end | Clears the system status log file . |
21,118 | def to_delimited_s ( delim = ',' ) split = self . to_s . split ( '.' ) split [ 0 ] = split . first . reverse . gsub ( / \d / , "\\1#{delim}" ) . reverse split . join ( '.' ) . uncapsulate ( ',' ) end | Convert this integer into a string with every three digits separated by a delimiter on the left side of the decimal |
21,119 | def call ( sev , time , _ , msg ) level = ( { Logger :: DEBUG => 'DEBUG' , Logger :: INFO => 'INFO' , Logger :: WARN => 'WARN' , Logger :: ERROR => 'ERROR' , Logger :: FATAL => 'FATAL' , } [ sev ] || sev . to_s ) . upcase if msg . present? && AUTO_DEBUG_PATTERNS . find { | pattern | msg =~ pattern } return '' if debug_skip? level = 'DEBUG' end if msg . present? if msg . is_a? ( :: Exception ) msg = "#{msg.message} (#{msg.class})\n#{(msg.backtrace || []).join("\n")}" elsif ! msg . is_a? ( :: String ) msg = msg . inspect end msg = rm_fmt msg { level : level , time : time . strftime ( '%Y-%m-%d %H:%M:%S' ) , message : msg , app_name : app_name , app_version : app_version , process_id : Process . pid , } . to_json + "\r\n" else '' end end | Overrides the default formatter behavior to log a JSON line . |
21,120 | def estimate_pdf_business_card_report xml = Builder :: XmlMarkup . new xml . instruct! xml . Request ( :xmlns => "urn:sbx:apis:SbxBaseComponents" ) do | xml | connection . requester_credentials_block ( xml ) xml . EstimatePdfBusinessCardReport end response = connection . post_xml ( xml ) document = REXML :: Document . new ( response ) number_of_cards = document . elements [ "EstimatePdfBusinessCardReportCallResponse" ] . elements [ "NumberOfBusinessCards" ] . text . to_i rescue 0 number_of_pages = document . elements [ "EstimatePdfBusinessCardReportCallResponse" ] . elements [ "NumberOfPages" ] . text . to_i rescue 0 return number_of_cards , number_of_pages end | Returns the estimated number of cards and number of pages for exporting Business Cards as PDF |
21,121 | def generate_pdf_business_card_report xml = Builder :: XmlMarkup . new xml . instruct! xml . Request ( :xmlns => "urn:sbx:apis:SbxBaseComponents" ) do | xml | connection . requester_credentials_block ( xml ) xml . GeneratePdfBusinessCardReport end response = connection . post_xml ( xml ) document = REXML :: Document . new ( response ) document . elements [ "GeneratePdfBusinessCardReportCallResponse" ] . elements [ "URL" ] . text end | Returns a URL for one - time download of Business Cards as PDF |
21,122 | def notify_preference xml = Builder :: XmlMarkup . new xml . instruct! xml . Request ( :xmlns => "urn:sbx:apis:SbxBaseComponents" ) do | xml | connection . requester_credentials_block ( xml ) xml . GetBusinessCardNotifyPreferenceCall end response = connection . post_xml ( xml ) document = REXML :: Document . new ( response ) document . elements [ "GetBusinessCardNotifyPreferenceCallResponse" ] . elements [ "BusinessCardNotifyPreference" ] . text == "1" end | Does the user have business card auto - share mode turned on? |
21,123 | def notify_preference = ( value ) if value translated_value = "1" else translated_value = "0" end xml = Builder :: XmlMarkup . new xml . instruct! xml . Request ( :xmlns => "urn:sbx:apis:SbxBaseComponents" ) do | xml | connection . requester_credentials_block ( xml ) xml . SetBusinessCardNotifyPreferenceCall do | xml | xml . BusinessCardNotifyPreference ( translated_value ) end end response = connection . post_xml ( xml ) value end | Turn auto - share mode on or off |
21,124 | def auto_share_contact_details xml = Builder :: XmlMarkup . new xml . instruct! xml . Request ( :xmlns => "urn:sbx:apis:SbxBaseComponents" ) do | xml | connection . requester_credentials_block ( xml ) xml . GetAutoShareContactDetailsCall end response = connection . post_xml ( xml ) details = Hash . new document = REXML :: Document . new ( response ) details_element = document . elements [ "GetAutoShareContactDetailsCallResponse" ] details [ :first_name ] = details_element . elements [ "FirstName" ] . text details [ :last_name ] = details_element . elements [ "LastName" ] . text details [ :email ] = details_element . elements [ "Email" ] . text details [ :additional_contact_info ] = details_element . elements [ "AdditionalContactInfo" ] . text details end | Get user s contact information that is sent out with business cards |
21,125 | def color_for ( arg ) arg = Yummi :: Context :: new ( arg ) unless arg . is_a? Context call ( arg ) end | Returns the color for the given value |
21,126 | def parse ( data ) result_df = nil Array ( data ) . each_with_index do | filename , idx | filename = filename . to_s logger . info "Converting #{filename} to a dataframe" processed_filename = preprocess ( filename ) csv_df = Daru :: DataFrame . from_csv processed_filename , @csv_options if csv_df . vectors . size == 0 headers_df = Daru :: DataFrame . from_csv processed_filename , @csv_options . merge ( return_headers : true ) csv_df = Daru :: DataFrame . new ( [ ] , order : headers_df . vectors . to_a ) end csv_df [ @filename_field ] = Daru :: Vector . new ( [ filename ] * csv_df . size , index : csv_df . index ) if @filename_field if idx == 0 result_df = csv_df else result_df = result_df . concat csv_df end end Remi :: DataFrame . create ( :daru , result_df ) end | Converts a list of filenames into a dataframe after parsing them according ot the csv options that were set |
21,127 | def encode ( dataframe ) logger . info "Writing CSV file to temporary location #{@working_file}" label_columns = self . fields . reduce ( { } ) { | h , ( k , v ) | if v [ :label ] h [ k ] = v [ :label ] . to_sym end h } dataframe . rename_vectors label_columns dataframe . write_csv @working_file , @csv_options @working_file end | Converts the dataframe to a CSV file stored in the local work directory . If labels are present write the CSV file with those headers but maintain the structure of the original dataframe |
21,128 | def post ( * args , & task ) raise ArgumentError , 'no block given' unless block_given? return false unless running? task . call ( * args ) true end | Creates a new executor |
21,129 | def target_extension return @target_extension if @target_extension if type = MIME :: Types [ self . target_mime_type ] . first if type . sub_type == "html" @target_extension = "html" else @target_extension = type . extensions . first end else @target_extension = File . extname ( self . source_path . to_s ) . sub ( / \. / , "" ) end end | Try to infer the final extension of the output file . |
21,130 | def update_metadata ( uid ) return false unless store_meta path = full_path ( uid ) meta = storage ( :get_blob , container_name , path ) [ 0 ] . metadata return false if meta . present? meta = meta_from_file ( path ) return false if meta . blank? storage ( :set_blob_metadata , container_name , path , meta ) storage ( :delete_blob , container_name , meta_path ( path ) ) true rescue Azure :: Core :: Http :: HTTPError nil end | Updates metadata of file and deletes old meta file from legacy mode . |
21,131 | def map ref , route , options = { } context = Context . collection [ get_context ] context . routes [ ref ] = Route . new ( route , context , options ) end | map a route |
21,132 | def root_to reference Router . set_root_to reference context = Context . collection [ reference ] context . routes [ :root ] = Route . new ( '/' , context , { context : reference } ) end | set the root context this is the initial context that will be renered by the router |
21,133 | def fakeUser @roles = [ 'administrator' , 'normal user' , 'Linux Test Environment' ] @role = @roles [ rand ( 0 .. 2 ) ] @fake_user = { "user" : { "firstname" : Faker :: Name . first_name , "lastname" : Faker :: Name . last_name , "email" : Faker :: Internet . email , "role" : @role } } end | Generate a unique fake user for testing |
21,134 | def populate ( line , msg ) @line = line @sequence = msg [ 'sequence' ] @depth = msg [ 'depth' ] @cmd = msg [ 'cmd' ] @kind = msg [ 'kind' ] @msg = msg [ 'msg' ] @key = msg [ 'key' ] end | Create a new log message |
21,135 | def next ( msg ) next_line do | input , line | if input . key? ( 'sequence' ) msg . populate ( line , input ) unless @sequence && @sequence != input [ 'sequence' ] return true end end return false end | Populates a message from the next line in the |
21,136 | def generate_ruby_version ruby_version = ( RUBY_PATCHLEVEL == 0 ) ? RUBY_VERSION : "#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}" File . open ( "#{self.path}/.ruby-version" , 'w' ) do | f | f . write ruby_version end end | Create rbenv local |
21,137 | def generate_steps_templates Bebox :: PROVISION_STEPS . each do | step | ssh_key = '' step_dir = Bebox :: Provision . step_name ( step ) templates_path = Bebox :: Project :: templates_path generate_file_from_template ( "#{templates_path}/puppet/#{step}/manifests/site.pp.erb" , "#{self.path}/puppet/steps/#{step_dir}/manifests/site.pp" , { nodes : [ ] } ) generate_file_from_template ( "#{templates_path}/puppet/#{step}/hiera/hiera.yaml.erb" , "#{self.path}/puppet/steps/#{step_dir}/hiera/hiera.yaml" , { step_dir : step_dir } ) generate_file_from_template ( "#{templates_path}/puppet/#{step}/hiera/data/common.yaml.erb" , "#{self.path}/puppet/steps/#{step_dir}/hiera/data/common.yaml" , { step_dir : step_dir , ssh_key : ssh_key , project_name : self . shortname } ) end end | Generate steps templates for hiera and manifests files |
21,138 | def apply_step ( project_root , environment , step ) ( return warn _ ( 'wizard.provision.ssh_key_advice' ) % { environment : environment } ) unless Bebox :: Environment . check_environment_access ( project_root , environment ) nodes_to_step = Bebox :: Node . nodes_in_environment ( project_root , environment , previous_checkpoint ( step ) ) ( return warn _ ( 'wizard.provision.no_provision_nodes' ) % { step : step } ) unless nodes_to_step . count > 0 nodes_for_provisioning ( nodes_to_step , step ) in_step_nodes = Bebox :: Node . list ( project_root , environment , "steps/#{step}" ) outputs = [ ] nodes_to_step . each do | node | next unless check_node_to_step ( node , in_step_nodes , step ) outputs << provision_step_in_node ( project_root , environment , step , in_step_nodes , node ) end return outputs end | Apply a step for the nodes in a environment |
21,139 | def estimate ( unspents , payees , network : , tx_size : nil , fee_per_kb : nil ) payees = payees . dup unspent_total = unspents . inject ( 0 ) { | sum , output | sum += output . value } payee_total = payees . inject ( 0 ) { | sum , payee | sum += payee . value } nominal_change = unspent_total - payee_total payees << Output . new ( value : nominal_change , network : network ) if nominal_change > 0 tx_size ||= estimate_tx_size ( unspents , payees ) small = tx_size < 1000 min_payee = payees . min_by { | payee | payee . value } big_outputs = min_payee . value > 1_000_000 high_priority = priority ( size : tx_size , unspents : unspents . map { | output | { value : output . value , age : output . confirmations } } ) > PRIORITY_THRESHOLD return 0 if small && big_outputs && high_priority fee_for_bytes ( tx_size , network : network , fee_per_kb : fee_per_kb ) end | Given an array of unspent Outputs and an array of Outputs for a Transaction estimate the fee required for the transaction to be included in a block . |
21,140 | def post ( data = { } ) request = Request . new ( @uri , headers : @headers , data : data , ) request . post end | POST s a resource from the URI and returns the result based on its content type . JSON content will be parsed and returned as equivalent Ruby objects . All other content types will be returned as text . |
21,141 | def put ( data = { } ) request = Request . new ( @uri , headers : @headers , data : data , ) request . put end | PUT s a resource to the URI and returns the result based on its content type . JSON content will be parsed and returned as equivalent Ruby objects . All other content types will be returned as text . |
21,142 | def consumer ( cons , * init_args , & block ) if cons . instance_of? Class cons = cons . new ( * init_args ) end ch = ConsumerHelper . new ( cons , credential ) ch . instance_eval & block provider . add_consumer ( ch . consumer ) end | Adds a consumer . |
21,143 | def attribute ( attr ) return super unless self . class . metadata_column_fields . include? ( attr . to_sym ) options = self . class . metadata_column_fields [ attr . to_sym ] || { } default = options . include? ( :default ) ? options [ :default ] : nil _metadata_hash . include? ( attr ) ? HasMetadataColumn . metadata_typecast ( _metadata_hash [ attr ] , options [ :type ] ) : default end | ATTRIBUTE MATCHER METHODS |
21,144 | def build_ansi_methods ( hash ) hash . each do | key , value | define_method ( key ) do | string = nil , & block | result = Array . new result << %(\e[#{value}m) if block_given? result << block . call elsif string . respond_to? ( :to_str ) result << string . to_str elsif respond_to? ( :to_str ) result << to_str else return result end result << %(\e[0m) result . join end end true end | Dynamicly constructs ANSI methods for the color methods based on the ANSI code hash passed in . |
21,145 | def uncolor ( string = nil , & block ) if block_given? block . call . to_str . gsub ( ANSI_REGEX , '' ) elsif string . respond_to? ( :to_str ) string . to_str . gsub ( ANSI_REGEX , '' ) elsif respond_to? ( :to_str ) to_str . gsub ( ANSI_REGEX , '' ) else '' end end | Removes ANSI code sequences from a string . |
21,146 | def validate_each ( record , attribute , value ) return if value . blank? return if value == :verified return if Incline :: Recaptcha :: paused? remote_ip , _ , response = value . partition ( '|' ) if remote_ip . blank? || response . blank? record . errors [ :base ] << ( options [ :message ] || 'Requires reCAPTCHA challenge to be completed' ) else if Incline :: Recaptcha :: verify ( response : response , remote_ip : remote_ip ) record . send "#{attribute}=" , :verified else record . errors [ :base ] << ( options [ :message ] || 'Invalid response from reCAPTCHA challenge' ) end end end | Validates a reCAPTCHA attribute . |
21,147 | def included ( klass ) klass . extend AliasingClassMethods klass . extend UniversalClassMethods klass . send ( :class_variable_set , :@@classy_aliases , self . send ( :class_variable_get , :@@classy_aliases ) ) super end | Handle a class including a module that has included Aliasable . Since the contolling module has extended this module this method ends up being called when the controlling module is included . |
21,148 | def symbolize_keys keys , hash new_hash = { } keys . each do | key | if hash [ key ] . kind_of? Hash new_hash [ key . to_sym ] = symbolize_keys ( hash [ key ] . keys , hash [ key ] ) elsif hash [ key ] . kind_of? Array new_hash [ key . to_sym ] = [ ] hash [ key ] . each do | item | if item . kind_of? Hash new_hash [ key . to_sym ] << symbolize_keys ( item . keys , item ) else new_hash [ key . to_sym ] << item end end else new_hash [ key . to_sym ] = hash [ key ] end end return new_hash end | Creates a new hash with all keys as symbols can be any level of depth |
21,149 | def constructor_shortcut ( target ) define_method target . to_s . downcase do | * args | new target , * args end end | Meta - programming method for creating constructor shortcut methods |
21,150 | def collect_information ( identifier , group_id ) group = :: BetterRailsDebugger :: AnalysisGroup . find group_id if not group . present? Rails . logger . error "[BetterRailsDebugger] Group '#{recorded[:group_id]}' not found. Skiping..." return end if not Mongoid :: Config . configured? Mongoid . load! ( BetterRailsDebugger :: Configuration . instance . mongoid_config_file , Rails . env . to_sym ) Mongoid . logger . level = Logger :: FATAL end instance = :: BetterRailsDebugger :: GroupInstance . create identifier : identifier , analysis_group_id : group_id , caller_file : caller [ 3 ] [ / / ] , status : 'pending' collect_memory_information ( instance ) collect_trace_point_history ( instance ) :: BetterRailsDebugger :: AnalysisRecorderJob . perform_later ( { instance_id : instance . id . to_s } ) end | Record into db information about object creation |
21,151 | def masterfile? ( element_key ) if Tools . class_type ( element_key ) == 'DO' file_list = load ( element_key ) unless file_list . nil? file_list . each do | file | return true if file . fileStorageType . casecmp ( 'master' ) . zero? end end end false end | Returns true or false if a masterfile exist |
21,152 | def masterfile_name ( element_key ) file_list = load ( element_key ) unless file_list . nil? file_list . each do | file | return file . fileName if file . fileStorageType . downcase! == 'master' end end '' end | Returns the name of a masterfile if present |
21,153 | def load ( element_key ) parameter = { basic_auth : @auth } response = self . class . get ( "/elements/#{element_key}/files" , parameter ) parse_files ( response [ 'FileInfos' ] ) if response . success? end | Loads the filelist Returns a full list of file data |
21,154 | def load_masterfile ( element_key ) parameter = { basic_auth : @auth } response = self . class . get ( "/elements/#{element_key}/files/masterfile" , parameter ) return response if response . success? end | Loads the masterfile directly |
21,155 | def upload_masterfile ( element_key , file , original_filename ) content_length = file . size content_type = 'application/octet-stream; charset=utf-8' parameter = { basic_auth : @auth , headers : { 'Content-Type' => content_type , 'Content-Length' => content_length . to_s , 'storageType' => 'MASTER' , 'filename' => original_filename . to_s } , body : file . read } upload_file element_key , parameter end | Masterfile is the main file attached to a document |
21,156 | def change_quit ( quit_command ) raise Shells :: NotRunning unless running? self . options = options . dup . merge ( quit : quit_command ) . freeze self end | Initializes the shell with the supplied options . |
21,157 | def url_get_html ( url_str ) url = URI . parse ( URI . encode ( url_str ) ) req = Net :: HTTP :: Get . new ( url . to_s ) res = Net :: HTTP . start ( url . host , url . port ) { | http | http . request ( req ) } res . body end | Send url to get response |
21,158 | def extract_comments ( content , user_id ) data_arr = [ ] if content content . each do | cmtItem | data_hash_sub = Hash . new { } data_hash_sub [ 'title' ] = cmtItem [ 'titleMain' ] data_hash_sub [ 'comment' ] = cmtItem [ 'content' ] data_hash_sub [ 'book_url' ] = BOOK_URL + cmtItem [ 'orgProdId' ] url = MAIN_URL + 'co=' + cmtItem [ 'pkNo' ] + '&ci=' + user_id + '&cp=3' data_hash_sub [ 'comment_url' ] = url data_hash_sub [ 'crt_time' ] = cmtItem [ 'crt_time' ] data_arr . push ( data_hash_sub ) end else data_arr = [ ] end @comments_found ||= data_arr end | Return the comments in the format specified in spec . |
21,159 | def find! ( * args ) raise_not_found_error_was = Mongoid . raise_not_found_error begin Mongoid . raise_not_found_error = true self . find ( * args ) ensure Mongoid . raise_not_found_error = raise_not_found_error_was end end | Finds document by id . Raises error if document is not found . |
21,160 | def breadcrumbs return unless show_breadcrumbs? content_for ( :breadcrumbs , content_tag ( :ol , class : "breadcrumb" ) do concat ( content_tag ( :li , link_to ( "Home" , root_path ) ) ) if can_view_resource_index? concat ( content_tag ( :li , controller_link ) ) end end ) end | Render navigational information in the form of breadcrumbs |
21,161 | def put_bucket_policy ( bucket_policy ) if bucket_policy && bucket_policy . is_a? ( String ) && bucket_policy . strip != '' bucket_request ( :put , :body => bucket_policy , :subresource => "policy" ) true else false end end | Set bucket policy for the given bucket |
21,162 | def create_new_profile ( project_root , profile_name , profile_base_path ) profile_base_path = Bebox :: Profile . cleanpath ( profile_base_path ) return unless name_valid? ( profile_name , profile_base_path ) profile_path = profile_base_path . empty? ? profile_name : profile_complete_path ( profile_base_path , profile_name ) return error ( _ ( 'wizard.profile.name_exist' ) % { profile : profile_path } ) if profile_exists? ( project_root , profile_path ) profile = Bebox :: Profile . new ( profile_name , project_root , profile_base_path ) output = profile . create ok _ ( 'wizard.profile.creation_success' ) % { profile : profile_path } return output end | Create a new profile |
21,163 | def name_valid? ( profile_name , profile_base_path ) unless valid_puppet_class_name? ( profile_name ) error _ ( 'wizard.profile.invalid_name' ) % { words : Bebox :: RESERVED_WORDS . join ( ', ' ) } return false end return true if profile_base_path . empty? unless Bebox :: Profile . valid_pathname? ( profile_base_path ) error _ ( 'wizard.profile.invalid_path' ) % { words : Bebox :: RESERVED_WORDS . join ( ', ' ) } return false end true end | Check if the profile name is valid |
21,164 | def remove_profile ( project_root ) profiles = Bebox :: Profile . list ( project_root ) if profiles . count > 0 profile = choose_option ( profiles , _ ( 'wizard.choose_remove_profile' ) ) else return error _ ( 'wizard.profile.no_deletion_profiles' ) end return warn ( _ ( 'wizard.no_changes' ) ) unless confirm_action? ( _ ( 'wizard.profile.confirm_deletion' ) ) profile_name = profile . split ( '/' ) . last profile_base_path = profile . split ( '/' ) [ 0 ... - 1 ] . join ( '/' ) profile = Bebox :: Profile . new ( profile_name , project_root , profile_base_path ) output = profile . remove ok _ ( 'wizard.profile.deletion_success' ) return output end | Removes an existing profile |
21,165 | def field_symbolizer ( arg = nil ) return @field_symbolizer unless arg @field_symbolizer = if arg . is_a? Symbol Remi :: FieldSymbolizers [ arg ] else arg end end | Field symbolizer used to convert field names into symbols . This method sets the symbolizer for the data subject and also sets the symbolizers for any associated parser and encoders . |
21,166 | def df = ( new_dataframe ) dsl_eval if new_dataframe . respond_to? :df_type @dataframe = new_dataframe else @dataframe = Remi :: DataFrame . create ( df_type , new_dataframe ) end end | Reassigns the dataframe associated with this DataSubject . |
21,167 | def method_missing ( symbol , * args ) self . class . new ( @components . map { | enum | enum . send ( symbol , * args ) } ) end | Returns the union of the results of calling the given method symbol on each component . |
21,168 | def generate_user_data ( lxd_params , options ) logger . info ( "Calling <#{__method__.to_s}>" ) lxd_params [ :config ] = { } if options [ :' ' ] lxd_params [ :config ] [ :" " ] = { } else sshkeys = maas . get_sshkeys pkg_repos = maas . get_package_repos lxd_params [ :config ] [ :' ' ] = { 'ssh_authorized_keys' => [ ] } sshkeys . each do | key | lxd_params [ :config ] [ :' ' ] [ 'ssh_authorized_keys' ] . push ( key [ 'key' ] ) end pkg_repos . each do | repo | if repo [ 'name' ] == 'main_archive' lxd_params [ :config ] [ :' ' ] [ 'apt_mirror' ] = repo [ 'url' ] end end lxd_params [ :config ] [ :" " ] [ 'source_image_alias' ] = lxd_params [ :alias ] lxd_params [ :config ] [ :" " ] [ 'maas' ] = true end if options [ :' ' ] lxd_params [ :config ] [ :" " ] = "true" end if options [ :' ' ] lxd_params [ :config ] [ :" " ] = "true" lxd_params [ :config ] [ :" " ] = "true" end if options [ :' ' ] lxd_params [ :config ] [ :" " ] = "true" lxd_params [ :config ] [ :" " ] = "iptable_nat, ip6table_nat, ebtables, openvswitch, kvm, kvm_intel, tap, vhost, vhost_net, vhost_scsi, vhost_vsock" end lxd_params [ :config ] [ :" " ] [ 'gogetit' ] = true lxd_params [ :config ] [ :' ' ] [ 'package_update' ] = false lxd_params [ :config ] [ :' ' ] [ 'package_upgrade' ] = false lxd_params [ :config ] [ :' ' ] = generate_cloud_init_config ( options , config , lxd_params [ :config ] [ :' ' ] ) lxd_params [ :config ] [ :" " ] = "#cloud-config\n" + YAML . dump ( lxd_params [ :config ] [ :" " ] ) [ 4 .. - 1 ] return lxd_params end | to generate user . user - data |
21,169 | def fill_in ( element , value ) if element . match / / select_date ( element , value ) else browser . type ( "jquery=#{element}" , value ) end end | Fill in a form field |
21,170 | def select_date ( element , value ) suffixes = { :year => '1i' , :month => '2i' , :day => '3i' , :hour => '4i' , :minute => '5i' } date = value . respond_to? ( :year ) ? value : Date . parse ( value ) browser . select "jquery=#{element}_#{suffixes[:year]}" , date . year browser . select "jquery=#{element}_#{suffixes[:month]}" , date . strftime ( '%B' ) browser . select "jquery=#{element}_#{suffixes[:day]}" , date . day end | Fill in a Rails - ish set of date_select fields |
21,171 | def wait_for ( element ) case element when :page_load browser . wait_for ( :wait_for => :page ) when :ajax browser . wait_for ( :wait_for => :ajax , :javascript_framework => Pyrite . js_framework ) else browser . wait_for ( :element => "jquery=#{element}" ) end end | Wait for a specific element the page to load or an AJAX request to return |
21,172 | def create_database_files username = builder . options [ 'database-username' ] password = builder . options [ 'database-password' ] builder . remove_file "config/database.yml" create_database_yml_file ( "config/database.sample.yml" , "username" , "pass" ) create_database_yml_file ( "config/database.yml" , username , password ) end | create a new database . yml that works with PG . |
21,173 | def add_observer ( observer_class , func = :handle_event ) func = func . to_sym unless observer_class . instance_methods . include? ( func ) m = "#<#{observer_class}> does not respond to `#{func}'" raise NoMethodError , m end observer_peers [ observer_class ] = func self end | Add observer . |
21,174 | def ssl_required? return ENV [ 'SSL' ] == 'on' ? true : false if defined? ENV [ 'SSL' ] return false if local_request? return false if RAILS_ENV == 'test' ( ( self . class . read_inheritable_attribute ( :ssl_required_actions ) || [ ] ) . include? ( action_name . to_sym ) ) && ( :: Rails . env == 'production' || :: Rails . env == 'staging' ) end | Only require ssl if we are in production |
21,175 | def ancestors return to_enum ( __callee__ ) unless block_given? node = self loop do node = node . parent yield node end end | Iterates over the nodes above this in the tree hierarchy and yields them to a block . If no block is given an enumerator is returned . |
21,176 | def child ( index = nil ) unless index raise ArgumentError , 'No index for node with degree != 1' if degree != 1 return first end rtl , index = wrap_index index raise RangeError , 'Child index out of range' if index >= degree children ( rtl : rtl ) . each do | c | break c if index . zero? index -= 1 end end | Accessor method for any of the n children under this node . If called without an argument and the node has anything but exactly one child an exception will be raised . |
21,177 | def edges ( & block ) return to_enum ( __callee__ ) unless block_given? children do | v | yield self , v v . edges ( & block ) end end | Iterates over each edge in the tree . |
21,178 | def + ( other ) unless root? && other . root? raise StructureException , 'Only roots can be added' end a = frozen? ? dup : self b = other . frozen? ? other . dup : other ab = self . class . new ab << a << b end | Add two roots together to create a larger tree . A new common root will be created and returned . Note that if the any of the root nodes are not frozen they will be modified and as a result seize to be roots . |
21,179 | def swagger_doc ( action , & block ) parse = ParserAction . new ( action , & block ) parse . adding_path end | Complete json file with datas to method and controller . Each action to controller is writing in temporary file . |
21,180 | def swagger_definition ( name , & block ) parse = ParserDefinition . new ( name , & block ) parse . adding_definition end | Complete definitions objects for each controller . |
21,181 | def Promise ( obj ) return obj . to_promise if obj . respond_to? ( :to_promise ) Deferred . new . fulfill ( obj ) end | Convert any object to a promise . When the object in question responds to to_promise the result of that method will be returned . If not a new deferred object is created and immediately fulfilled with the given object . |
21,182 | def normalize_path ( test , path ) Pathname . new ( path ) . relative_path_from ( test . project . path . realpath ) . to_s end | Will make path relative to project dir |
21,183 | def assert_valid_keys ( options , valid_options ) unknown_keys = options . keys - valid_options . keys raise ( ArgumentError , "Unknown options(s): #{unknown_keys.join(", ")}" ) unless unknown_keys . empty? end | Tests if + options + includes only valid keys . Raises an error if any key is not included within + valid_options + . + valid_options + is a Hash that must include all accepted keys . values aren t taken into account . |
21,184 | def describe_file_diff ( diff , max_width = 80 ) description = [ ] description << "File comparison error `#{diff.relative_path}` for #{spec.spec_folder}:" description << "--- DIFF " . ljust ( max_width , '-' ) description += diff . map do | line | case line when / \+ / then line . green when / / then line . red else line end . gsub ( "\n" , '' ) . gsub ( "\r" , '\r' ) end description << "--- END " . ljust ( max_width , '-' ) description << '' description * "\n" end | Return a description text for an expectation that two files were expected to be the same but are not . |
21,185 | def sign_in_success g_user = signed_in? if g_user user = { :email => g_user . email , :user_id => g_user . user_id , :name => g_user . name , :photo_url => g_user . photo_url , :provider_id => g_user . provider_id } @user = User . find_by ( user_id : user [ :user_id ] ) if @user . nil? @user = User . create user else @user . update user end session [ :user ] = @user . id if session [ :previous_url ] previous_url = session [ :previous_url ] session . delete :previous_url redirect_to previous_url else redirect_to main_app . root_url end else @user = false session . delete :user flash . alert = "Sign in failed. Please try again." redirect_to gitkit_sign_in_url end end | This will be called after successfull signin |
21,186 | def render_erb_template ( template_path , options ) require 'tilt' Tilt :: ERBTemplate . new ( template_path ) . render ( nil , options ) end | Render a template for file content |
21,187 | def write_content_to_file ( file_path , content ) File . open ( file_path , 'w' ) do | f | f . write content end end | Write content to a file |
21,188 | def create_resource ( resource , opts = { } ) data , _status_code , _headers = create_resource_with_http_info ( resource , opts ) return data end | Creates a new resource |
21,189 | def get_resource ( id_or_uri , opts = { } ) data , _status_code , _headers = get_resource_with_http_info ( id_or_uri , opts ) return data end | Returns a single resource |
21,190 | def list_aggregated_resources ( uri_prefix , opts = { } ) data , _status_code , _headers = list_aggregated_resources_with_http_info ( uri_prefix , opts ) return data end | Returns aggregated resources to be monitored |
21,191 | def update_resource ( id_or_uri , resource , opts = { } ) data , _status_code , _headers = update_resource_with_http_info ( id_or_uri , resource , opts ) return data end | Updates a single resource |
21,192 | def add_list_data ( data ) raise symbol . to_s if data . nil? self . exchange_rate = data [ 'price_usd' ] . to_f self . perchant_change_week = data [ 'percent_change_7d' ] . to_f self . perchant_change_day = data [ 'percent_change_24h' ] . to_f end | Builds a UserPair given the related CMC data |
21,193 | def new_topic board : 92 , subj : 'test' , msg : 'msg' , icon : "exclamation" board = board . instance_of? ( Symbol ) ? @opts [ :boards ] [ board ] : board get "/index.php?action=post;board=#{board}.0" raise "Not logged, cannot post!" unless logged? p msg seqnum , sc = find_fields 'seqnum' , 'sc' subj = xml_encode ( subj_encode ( subj ) ) msg = xml_encode ( msg ) post "/index.php?action=post2;start=0;board=#{board}" , content_type : 'multipart/form-data; charset=ISO-8859-1' , body : { topic : 0 , subject : subj , icon : icon , message : msg , notify : 0 , do_watch : 0 , selfmod : 0 , lock : 0 , goback : 1 , ns : "NS" , post : "Post" , additional_options : 0 , sc : sc , seqnum : seqnum } , options : { timeout : 5 } new_topic = @response . headers [ 'location' ] raise "No redirect to posted topic!" unless new_topic && @response . status == 302 get new_topic end | Post new topic |
21,194 | def each_vertex_breadth_first ( start_vertex , walk_method ) remaining = [ start_vertex ] remaining . each_with_object ( [ ] ) do | vertex , history | history << vertex yield vertex send ( walk_method , vertex ) . each do | other | remaining << other unless history . include? ( other ) end end end | Yield each reachable vertex to a block breadth first |
21,195 | def create_versions_class versions_table_name = self . versions_table_name self . const_set self . versions_class_name , Class . new ( ActiveRecord :: Base ) self . versions_class . class_eval do self . table_name = versions_table_name public_attributes = self . column_names . reject { | attr | self . protected_attributes . deny? ( attr ) } self . attr_accessible ( * public_attributes ) end end | create a class |
21,196 | def make_bonds ( bond_length = 3.0 ) @bonds = Array . new atoms_extended = atoms . dup if periodic? v1 = lattice_vectors [ 0 ] v2 = lattice_vectors [ 1 ] atoms . each { | a | [ - 1 , 0 , 1 ] . each { | n1 | [ - 1 , 0 , 1 ] . each { | n2 | atoms_extended << a . displace ( n1 * v1 [ 0 ] + n2 * v2 [ 0 ] , n1 * v1 [ 1 ] + n2 * v2 [ 1 ] , n1 * v1 [ 2 ] + n2 * v2 [ 2 ] ) } } } end tree = KDTree . new ( atoms_extended , 3 ) atoms . each { | a | r = 4 neighbors = tree . find ( [ a . x - r , a . x + r ] , [ a . y - r , a . y + r ] , [ a . z - r , a . z + r ] ) neighbors . each { | n | b = Bond . new ( a , n ) @bonds << b if b . length < bond_length } } end | Generate and cache bonds for this geometry . A bond will be generated for every pair of atoms closer than + bond_length + |
21,197 | def recache_visible_atoms ( makeBonds = false ) plane_count = ( @clip_planes ? @clip_planes . length : 0 ) return if plane_count == 0 if @visibleAtoms @visibleAtoms . clear else @visibleAtoms = [ ] end @atoms . each { | a | i = plane_count @clip_planes . each { | p | i = i - 1 if 0 >= p . distance_to_point ( a . x , a . y , a . z ) } @visibleAtoms << a if i == 0 } if @visibleBonds @visibleBonds . clear else @visibleBonds = [ ] end make_bonds if ( makeBonds or @bonds . nil? ) @bonds . each { | b | a0 = b [ 0 ] a1 = b [ 1 ] i0 = plane_count i1 = plane_count @clip_planes . each { | p | i0 = i0 - 1 if 0 >= p . distance_to_point ( a0 . x , a0 . y , a0 . z ) i1 = i1 - 1 if 0 >= p . distance_to_point ( a1 . x , a1 . y , a1 . z ) } @visibleBonds << b if ( i0 + i1 ) < 2 } end | Recompute the atoms that are behind all the clip planes Atoms that are in front of any clip - plane are considered invisible . |
21,198 | def center ( visible_only = true ) if atoms . empty? return Atom . new ( 0 , 0 , 0 ) else bounds = bounding_box ( visible_only ) x = ( bounds [ 0 ] . x + bounds [ 1 ] . x ) / 2.0 y = ( bounds [ 0 ] . y + bounds [ 1 ] . y ) / 2.0 z = ( bounds [ 0 ] . z + bounds [ 1 ] . z ) / 2.0 return Atom . new ( x , y , z ) end end | Return an Atom whose coordinates are the center of the unit - cell . |
21,199 | def displace ( x , y , z ) Geometry . new ( atoms ( :all ) . collect { | a | a . displace ( x , y , z ) } , self . lattice_vectors ) end | Return a new unit cell with all the atoms displaced by the amount x y z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.