idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
9,200 | def execute_hooks_for ( type , name ) model . hooks [ name ] [ type ] . each { | hook | hook . call ( self ) } end | Execute all the queued up hooks for a given type and name |
9,201 | def run_once ( default ) caller_method = Kernel . caller ( 1 ) . first [ / / , 1 ] sentinel = "@_#{caller_method}_sentinel" return instance_variable_get ( sentinel ) if instance_variable_defined? ( sentinel ) begin instance_variable_set ( sentinel , default ) yield ensure remove_instance_variable ( sentinel ) end end | Prevent a method from being in the stack more than once |
9,202 | def pluralize ( word ) result = word . to_s . dup if word . empty? || inflections . uncountables . include? ( result . downcase ) result else inflections . plurals . each { | ( rule , replacement ) | break if result . gsub! ( rule , replacement ) } result end end | Returns the plural form of the word in the string . |
9,203 | def exception_message ( e ) msg = [ "Exception #{e.class} -> #{e.message}" ] base = File . expand_path ( Dir . pwd ) + '/' e . backtrace . each do | t | msg << " #{File.expand_path(t).gsub(/#{base}/, '')}" end if e . backtrace msg . join ( "\n" ) end | Prints out exception_message based on specified e |
9,204 | def classify ( dashed_word ) dashed_word . to_s . split ( '-' ) . each { | part | part [ 0 ] = part [ 0 ] . chr . upcase } . join end | Given a word with dashes returns a camel cased version of it . |
9,205 | def dasherize ( word ) classify ( word ) . to_s . gsub ( / / , '/' ) . gsub ( / / , '\1_\2' ) . gsub ( / \d / , '\1_\2' ) . tr ( "_" , "-" ) . downcase end | Given a class dasherizes the name used for getting tube names |
9,206 | def resolve_priority ( pri ) if pri . respond_to? ( :queue_priority ) resolve_priority ( pri . queue_priority ) elsif pri . is_a? ( String ) || pri . is_a? ( Symbol ) resolve_priority ( Backburner . configuration . priority_labels [ pri . to_sym ] ) elsif pri . is_a? ( Integer ) pri else Backburner . configuration . de... | Resolves job priority based on the value given . Can be integer a class or nothing |
9,207 | def resolve_respond_timeout ( ttr ) if ttr . respond_to? ( :queue_respond_timeout ) resolve_respond_timeout ( ttr . queue_respond_timeout ) elsif ttr . is_a? ( Integer ) ttr else Backburner . configuration . respond_timeout end end | Resolves job respond timeout based on the value given . Can be integer a class or nothing |
9,208 | def work_one_job ( conn = connection ) begin job = reserve_job ( conn ) rescue Beaneater :: TimedOutError => e return end self . log_job_begin ( job . name , job . args ) job . process self . log_job_end ( job . name ) rescue Backburner :: Job :: JobFormatInvalid => e self . log_error self . exception_message ( e ) res... | Performs a job by reserving a job from beanstalk and processing it |
9,209 | def new_connection Connection . new ( Backburner . configuration . beanstalk_url ) { | conn | Backburner :: Hooks . invoke_hook_events ( self , :on_reconnect , conn ) } end | Return a new connection instance |
9,210 | def reserve_job ( conn , reserve_timeout = Backburner . configuration . reserve_timeout ) Backburner :: Job . new ( conn . tubes . reserve ( reserve_timeout ) ) end | Reserve a job from the watched queues |
9,211 | def handle_error ( e , name , args , job ) if error_handler = Backburner . configuration . on_error if error_handler . arity == 1 error_handler . call ( e ) elsif error_handler . arity == 3 error_handler . call ( e , name , args ) else error_handler . call ( e , name , args , job ) end end end | Handles an error according to custom definition Used when processing a job that errors out |
9,212 | def compact_tube_names ( tube_names ) tube_names = tube_names . first if tube_names && tube_names . size == 1 && tube_names . first . is_a? ( Array ) tube_names = Array ( tube_names ) . compact if tube_names && Array ( tube_names ) . compact . size > 0 tube_names = nil if tube_names && tube_names . compact . empty? tub... | Normalizes tube names given array of tube_names Compacts nil items flattens arrays sets tubes to nil if no valid names Loads default tubes when no tubes given . |
9,213 | def log_job_end ( name , message = nil ) ellapsed = Time . now - job_started_at ms = ( ellapsed . to_f * 1000 ) . to_i action_word = message ? 'Finished' : 'Completed' log_info ( "#{action_word} #{name} in #{ms}ms #{message}" ) end | Print out when a job completed If message is nil job is considered complete |
9,214 | def process res = @hooks . invoke_hook_events ( job_name , :before_perform , * args ) return false unless res @hooks . around_hook_events ( job_name , :around_perform , * args ) do timeout_job_after ( task . ttr > 1 ? task . ttr - 1 : task . ttr ) { job_class . perform ( * args ) } end task . delete @hooks . invoke_hoo... | Processes a job and handles any failure deleting the job once complete |
9,215 | def timeout_job_after ( secs , & block ) begin Timeout :: timeout ( secs ) { yield } rescue Timeout :: Error => e raise JobTimeout , "#{name}(#{(@args||[]).join(', ')}) hit #{secs}s timeout.\nbacktrace: #{e.backtrace}" end end | Timeout job within specified block after given time . |
9,216 | def retryable ( options = { } , & block ) options = { :max_retries => 4 , :on_retry => nil , :retry_delay => 1.0 } . merge! ( options ) retry_count = options [ :max_retries ] begin yield rescue Beaneater :: NotConnected if retry_count > 0 reconnect! retry_count -= 1 sleep options [ :retry_delay ] options [ :on_retry ] ... | Yield to a block that will be retried several times if the connection to beanstalk goes down and is able to be re - established . |
9,217 | def ensure_connected! ( max_retries = 4 , retry_delay = 1.0 ) return self if connected? begin reconnect! return self rescue Beaneater :: NotConnected => e if max_retries > 0 max_retries -= 1 sleep retry_delay retry else raise e end end end | Attempts to ensure a connection to beanstalk is established but only if we re not connected already |
9,218 | def beanstalk_addresses uri = self . url . is_a? ( Array ) ? self . url . first : self . url beanstalk_host_and_port ( uri ) end | Returns the beanstalk queue addresses |
9,219 | def beanstalk_host_and_port ( uri_string ) uri = URI . parse ( uri_string ) raise ( BadURL , uri_string ) if uri . scheme != 'beanstalk' . freeze "#{uri.host}:#{uri.port || 11300}" end | Returns a host and port based on the uri_string given |
9,220 | def find_cities cities = CS . cities ( params [ :state_id ] . to_sym , params [ :country_id ] . to_sym ) respond_to do | format | format . json { render :json => cities . to_a } end end | Sent it to state_id and country id it will return cities of that states |
9,221 | def file_field ( method , options = { } ) bootstrap = form_bootstrap . scoped ( options . delete ( :bootstrap ) ) return super if bootstrap . disabled draw_form_group ( bootstrap , method , options ) do if bootstrap . custom_control content_tag ( :div , class : "custom-file" ) do add_css_class! ( options , "custom-file... | Wrapper for file_field helper . It can accept custom_control option . |
9,222 | def plaintext ( method , options = { } ) bootstrap = form_bootstrap . scoped ( options . delete ( :bootstrap ) ) draw_form_group ( bootstrap , method , options ) do remove_css_class! ( options , "form-control" ) add_css_class! ( options , "form-control-plaintext" ) options [ :readonly ] = true ActionView :: Helpers :: ... | Bootstrap wrapper for readonly text field that is shown as plain text . |
9,223 | def primary ( value = nil , options = { } , & block ) add_css_class! ( options , "btn-primary" ) submit ( value , options , & block ) end | Same as submit button only with btn - primary class added |
9,224 | def draw_form_group ( bootstrap , method , options ) label = draw_label ( bootstrap , method , for_attr : options [ :id ] ) errors = draw_errors ( method ) control = draw_control ( bootstrap , errors , method , options ) do yield end form_group_class = "form-group" form_group_class += " row" if bootstrap . horizontal? ... | form group wrapper for input fields |
9,225 | def draw_control ( bootstrap , errors , _method , options ) add_css_class! ( options , "form-control" ) add_css_class! ( options , "is-invalid" ) if errors . present? draw_control_column ( bootstrap , offset : bootstrap . label [ :hide ] ) do draw_input_group ( bootstrap , errors ) do yield end end end | Renders control for a given field |
9,226 | def draw_control_column ( bootstrap , offset : ) return yield unless bootstrap . horizontal? css_class = bootstrap . control_col_class . to_s css_class += " #{bootstrap.offset_col_class}" if offset content_tag ( :div , class : css_class ) do yield end end | Wrapping in control in column wrapper |
9,227 | def draw_form_group_fieldset ( bootstrap , method ) options = { } unless bootstrap . label [ :hide ] label_text = bootstrap . label [ :text ] label_text ||= ActionView :: Helpers :: Tags :: Label :: LabelBuilder . new ( @template , @object_name . to_s , method , @object , nil ) . translation add_css_class! ( options , ... | Wrapper for collections of radio buttons and checkboxes |
9,228 | def bootstrap_form_with ( ** options , & block ) bootstrap_options = options [ :bootstrap ] || { } css_classes = options . delete ( :class ) if bootstrap_options [ :layout ] . to_s == "inline" css_classes = [ css_classes , "form-inline" ] . compact . join ( " " ) end form_options = options . reverse_merge ( builder : C... | Wrapper for form_with . Passing in Bootstrap form builder . |
9,229 | def supress_form_field_errors original_proc = ActionView :: Base . field_error_proc ActionView :: Base . field_error_proc = proc { | input , _instance | input } yield ensure ActionView :: Base . field_error_proc = original_proc end | By default Rails will wrap form fields with extra html to indicate inputs with errors . We need to handle this in the builder to render Bootstrap specific markup . So we need to bypass this . |
9,230 | def request ( uri , method = :get , body = nil , query = nil , content_type = nil ) headers = { } { 'Content-Type' => content_type || 'application/json' , 'User-Agent' => "Parse for Ruby, #{VERSION}" , Protocol :: HEADER_MASTER_KEY => @master_key , Protocol :: HEADER_APP_ID => @application_id , Protocol :: HEADER_API_K... | Perform an HTTP request for the given uri and method with common basic response handling . Will raise a ParseProtocolError if the response has an error status code and will return the parsed JSON body on success if there is one . |
9,231 | def save if @parse_object_id method = :put merge! ( @op_fields ) else method = :post end body = safe_hash . to_json data = @client . request ( uri , method , body ) if data object = Parse . parse_json ( class_name , data ) object = Parse . copy_client ( @client , object ) parse object end if @class_name == Parse :: Pro... | Write the current state of the local object to the API . If the object has never been saved before this will create a new object otherwise it will update the existing stored object . |
9,232 | def safe_hash Hash [ map do | key , value | if Protocol :: RESERVED_KEYS . include? ( key ) nil elsif value . is_a? ( Hash ) && value [ Protocol :: KEY_TYPE ] == Protocol :: TYPE_RELATION nil elsif value . nil? [ key , Protocol :: DELETE_OP ] else [ key , Parse . pointerize_value ( value ) ] end end . compact ] end | representation of object to send on saves |
9,233 | def increment ( field , amount = 1 ) body = { field => Parse :: Increment . new ( amount ) } . to_json data = @client . request ( uri , :put , body ) parse data self end | Increment the given field by an amount which defaults to 1 . Saves immediately to reflect incremented |
9,234 | def parse ( data ) return unless data @parse_object_id ||= data [ Protocol :: KEY_OBJECT_ID ] if data . key? Protocol :: KEY_CREATED_AT @created_at = DateTime . parse data [ Protocol :: KEY_CREATED_AT ] end if data . key? Protocol :: KEY_UPDATED_AT @updated_at = DateTime . parse data [ Protocol :: KEY_UPDATED_AT ] end ... | Merge a hash parsed from the JSON representation into this instance . This will extract the reserved fields merge the hash keys and then ensure that the reserved fields do not occur in the underlying hash storage . |
9,235 | def draw_children first = true @children . each do | child | child . draw ( 1 , first ) first = false end puts '└──' end | Draw all children at the same level for having multiple top - level peer leaves . |
9,236 | def upload_to_s3 ( file , key ) attempts = 0 begin super unless ( checksum = checksum_file ( file ) ) . nil? verify_s3_checksum ( key , checksum , attempt : attempts ) end rescue RuntimeError => e unless ( attempts += 1 ) > 3 sleep 10 retry end raise e end end | Uploads the file to s3 and verifies the checksum . |
9,237 | def download_from_github ( version ) file_pattern = "*#{version}*.tar.gz" attempts = 0 Retriable . retriable on : RuntimeError do FileUtils . rm ( Dir . glob ( '*' ) ) sh_out ( "hub release download #{version}" ) raise "File '#{file_pattern}' not found." if Dir . glob ( file_pattern ) . empty? file = Dir . glob ( file_... | Downloads the release build from github and verifies the checksum . |
9,238 | def verify_download_checksum ( build_file , checksum_file , attempt : 0 ) expected = File . read ( checksum_file ) actual = Digest :: MD5 . file ( build_file ) . hexdigest if actual != expected log . error ( "GitHub fie #{build_file} checksum should be #{expected} " "but was #{actual}." ) backup_failed_github_file ( bu... | Verifies the checksum for a file downloaded from github . |
9,239 | def backup_failed_github_file ( build_file , attempt ) basename = File . basename ( build_file , '.tar.gz' ) destination = File . join ( Dir . tmpdir , basename , ".gh.failure.#{attempt}.tar.gz" ) FileUtils . cp ( build_file , destination ) log . info ( "Copied #{build_file} to #{destination}" ) end | Backs up the failed file from a github verification . |
9,240 | def verify_s3_checksum ( s3_name , checksum_file , attempt : 0 ) headers = s3_client . head_object ( key : s3_name , bucket : @bucket_name ) expected = File . read ( checksum_file ) actual = headers . etag . tr ( '"' , '' ) if actual != expected log . error ( "S3 file #{s3_name} checksum should be #{expected} but " "wa... | Verifies the checksum for a file uploaded to s3 . |
9,241 | def backup_failed_s3_file ( s3_name , attempt ) basename = File . basename ( s3_name , '.tar.gz' ) destination = "#{Dir.tmpdir}/#{basename}.s3.failure.#{attempt}.tar.gz" s3_client . get_object ( response_target : destination , key : s3_name , bucket : @bucket_name ) log . info ( "Copied #{s3_name} to #{destination}" ) ... | Backs up the failed file from an s3 verification . |
9,242 | def get_addl_info ( instance_ids ) resp = ec2_client . describe_instances ( instance_ids : instance_ids ) data = { } resp . reservations . map ( & :instances ) . flatten . each do | instance | data [ instance . instance_id ] = instance end data end | Get additional information about instances not returned by the ASG API . |
9,243 | def wait_for_build ( version ) retry_opts = { tries : MAX_BUILD_FIND_ATTEMPTS , base_interval : 10 } job_number = nil sh_retry ( "bundle exec travis show #{@cli_args} #{version}" , opts : retry_opts ) do | build_out | raise CommandError , "Build for #{version} not found.\n#{build_out}" unless ( job_number = build_out .... | Looks for the travis build and attempts to retry if the build does not exist yet . |
9,244 | def wait_for_job ( job_number ) authenticate start = Time . new job = repo . job ( job_number ) ilog . start_threaded ( "Waiting for job #{job_number} to complete." ) do | s | while ! job . finished? && Time . new - start < @timeout s . continue ( "Job status: #{job.state}" ) sleep 10 job . reload end if job . finished... | Waits for a job to complete within the defined timeout . |
9,245 | def default_values h = { } template . parameters . each do | p | h [ p . name ] = h . default end h end | Return a Hash of the default values defined in the stack template . |
9,246 | def git_tag_exists ( tag , sha ) exists = false sh_step ( "git tag -l #{tag}" ) do | _ , output | exists = ( output . strip == tag ) end if exists sh_step ( "git rev-list -n 1 #{tag}" ) do | _ , output | raise "#{tag} already exists at a different SHA" if output . strip != sha end log . info ( "tag #{tag} already exist... | Determines if a valid git tag already exists . |
9,247 | def hub_release_exists ( semver ) exists = false sh_step ( "hub release show #{semver}" , fail : false ) do | _ , output | first_line = output . split ( "\n" ) . first exists = ! first_line . nil? && first_line . strip == semver . to_s end log . info ( "release #{semver} already exists" ) if exists exists end | Determines if a github release already exists . |
9,248 | def check_ci_status ( sha ) out = nil retry_opts = { max_elapsed_time : @ci_status_timeout , base_interval : 10 } ilog . start_threaded ( "Check CI status for #{sha}." ) do | step | out = sh_retry ( "hub ci-status --verbose #{sha}" , opts : retry_opts ) step . success end out end | Checks for the commit s CI job status . If its not finished yet wait till timeout . |
9,249 | def prob_h_to_ao h rmin , rmax = h . keys . minmax o = rmin s = 1 + rmax - rmin raise ArgumentError , "Range of possible results too large" if s > 1000000 a = Array . new ( s , 0.0 ) h . each { | k , v | a [ k - rmin ] = Float ( v ) } [ a , o ] end | Convert hash to array offset notation |
9,250 | def prob_ao_to_h a , o h = Hash . new a . each_with_index { | v , i | h [ i + o ] = v if v > 0.0 } h end | Convert array offset notation to hash |
9,251 | def basic_options Hash [ BASIC_OPTION_KEYS . map { | k | [ k , send ( k ) ] } ] . reject { | _ , v | v . nil? } end | return a hash of basic options to merge |
9,252 | def results ( profile = nil , options = { } ) query = loaded? ? Query . from_query ( self ) : self options , profile = profile , self . profile if profile . is_a? ( Hash ) query . profile = profile query . apply_options ( self . basic_options . merge ( options ) ) query end | if no filters we use results to add profile |
9,253 | def requeue ( queue , opts = { } ) queue_name = case queue when String , Symbol then queue else queue . name end note_state_change :requeue do @client . call ( 'requeue' , @client . worker_name , queue_name , @jid , @klass_name , JSON . dump ( opts . fetch ( :data , @data ) ) , opts . fetch ( :delay , 0 ) , 'priority' ... | Move this from it s current queue into another |
9,254 | def fail ( group , message ) note_state_change :fail do @client . call ( 'fail' , @jid , @worker_name , group , message , JSON . dump ( @data ) ) || false end rescue Qless :: LuaScriptError => err raise CantFailError . new ( err . message ) end | Fail a job |
9,255 | def start queue = :: Queue . new @thread = Thread . start do @listener_redis . subscribe ( @channel , @my_channel ) do | on | on . subscribe do | channel | queue . push ( :subscribed ) if channel == @channel end on . message do | channel , message | handle_message ( channel , message ) end end end queue . pop end | Start a thread listening |
9,256 | def pop ( count = nil ) jids = JSON . parse ( @client . call ( 'pop' , @name , worker_name , ( count || 1 ) ) ) jobs = jids . map { | j | Job . new ( @client , j ) } count . nil? ? jobs [ 0 ] : jobs end | Pop a work item off the queue |
9,257 | def peek ( count = nil ) jids = JSON . parse ( @client . call ( 'peek' , @name , ( count || 1 ) ) ) jobs = jids . map { | j | Job . new ( @client , j ) } count . nil? ? jobs [ 0 ] : jobs end | Peek at a work item |
9,258 | def length ( @client . redis . multi do %w[ locks work scheduled depends ] . each do | suffix | @client . redis . zcard ( "ql:q:#{@name}-#{suffix}" ) end end ) . inject ( 0 , :+ ) end | How many items in the queue? |
9,259 | def scope_for_slug_generator relation = super return relation if new_record? relation = relation . merge ( Slug . where ( 'sluggable_id <> ?' , id ) ) if friendly_id_config . uses? ( :scoped ) relation = relation . where ( Slug . arel_table [ :scope ] . eq ( serialized_scope ) ) end relation end | If we re updating don t consider historic slugs for the same record to be conflicts . This will allow a record to revert to a previously used slug . |
9,260 | def connect! return unless @backend . nil? @backend = train_connection . connection @backend . wait_until_ready mix_in_target_platform! unless @mocked_connection rescue Train :: UserError => e raise ConnectionFailure . new ( e , config ) rescue Train :: Error => e raise ConnectionFailure . new ( e . cause || e , config... | Establish connection to configured target . |
9,261 | def fetch_file_contents ( remote_path ) result = backend . file ( remote_path ) if result . exist? && result . file? result . content else nil end end | Retrieve the contents of a remote file . Returns nil if the file didn t exist or couldn t be read . |
9,262 | def targets return @targets unless @targets . nil? expanded_urls = [ ] @split_targets . each do | target | expanded_urls = ( expanded_urls | expand_targets ( target ) ) end @targets = expanded_urls . map do | url | config = @conn_options . merge ( config_for_target ( url ) ) TargetHost . new ( config . delete ( :url ) ... | Returns the list of targets as an array of TargetHost instances them to account for ranges embedded in the target name . |
9,263 | def load_cookbook ( path_or_name ) require "chef/exceptions" if File . directory? ( path_or_name ) cookbook_path = path_or_name require "chef/cookbook/cookbook_version_loader" begin v = Chef :: Cookbook :: CookbookVersionLoader . new ( cookbook_path ) v . load! cookbook = v . cookbook_version rescue Chef :: Exceptions ... | Given a cookbook path or name try to load that cookbook . Either return a cookbook object or raise an error . |
9,264 | def find_recipe ( cookbook , recipe_name = nil ) recipes = cookbook . recipe_filenames_by_name if recipe_name . nil? default_recipe = recipes [ "default" ] raise NoDefaultRecipe . new ( cookbook . root_dir , cookbook . name ) if default_recipe . nil? default_recipe else recipe = recipes [ recipe_name ] raise RecipeNotF... | Find the specified recipe or default recipe if none is specified . Raise an error if recipe cannot be found . |
9,265 | def connect_target ( target_host , reporter ) connect_message = T . status . connecting ( target_host . user ) reporter . update ( connect_message ) do_connect ( target_host , reporter ) end | Accepts a target_host and establishes the connection to that host while providing visual feedback via the Terminal API . |
9,266 | def generate_local_policy ( reporter ) action = Action :: GenerateLocalPolicy . new ( cookbook : temp_cookbook ) action . run do | event , data | case event when :generating reporter . update ( TS . generate_local_policy . generating ) when :exporting reporter . update ( TS . generate_local_policy . exporting ) when :s... | Runs the GenerateLocalPolicy action and renders UI updates as the action reports back |
9,267 | def converge ( reporter , local_policy_path , target_host ) reporter . update ( TS . converge . converging ( temp_cookbook . descriptor ) ) converge_args = { local_policy_path : local_policy_path , target_host : target_host } converger = Action :: ConvergeTarget . new ( converge_args ) converger . run do | event , data... | Runs the Converge action and renders UI updates as the action reports back |
9,268 | def handle_message ( message , data , reporter ) if message == :error reporter . error ( ChefApply :: UI :: ErrorPrinter . error_summary ( data [ 0 ] ) ) end end | A handler for common action messages |
9,269 | def map ( opts ) if opts . is_a? Hash opts . each do | channel , controller | if channel . is_a? String if FayeRails :: Matcher . match? '/**' , channel routing_extension . map ( channel , controller ) else raise ArgumentError , "Invalid channel: #{channel}" end elsif channel == :default if controller == :block routing... | Rudimentary routing support for channels to controllers . |
9,270 | def image ( link , title , alt_text ) if @image_parameters . present? prefix = link . include? ( '?' ) ? '&' : '?' link += "#{prefix}#{@image_parameters.to_query}" end content_tag ( :img , nil , src : link . to_s , alt : alt_text , title : title ) end | Image tag wrapper for forwarding Image API options |
9,271 | def get_child_entity_from_path_by ( field , children ) child_value = children . shift child = send ( :children ) . find { | c | c . send ( field ) == child_value } return child . get_child_entity_from_path_by ( field , children ) if child && ! children . empty? child end | Given a field and an array of child fields we need to recurse through them to get the last one |
9,272 | def parse_markdown ( markdown_string , renderer_options : { } , markdown_options : { } , image_options : { } ) markdown_string ||= '' markdown_opts = { no_intr_emphasis : true , tables : true , fenced_code_blocks : true , autolink : true , disable_indented_code_blocks : true , strikethrough : true , lax_spacing : true ... | Return HTML which is passed through the Redcarpet markdown processor using a custom renderer so that we can manipulate images using contentful s URL - based API . NOTE that this is super - permissive out of the box . Set options to suit when you call the method . |
9,273 | def create request . format = :json update_type = request . headers [ 'HTTP_X_CONTENTFUL_TOPIC' ] ActiveSupport :: Notifications . instrument ( "Contentful.#{update_type}" , params ) render body : nil end | this is where we receive a webhook via a POST |
9,274 | def references_for_title references = [ ] references << "ISBN: #{attachment[:isbn]}" if attachment [ :isbn ] . present? references << "Unique reference: #{attachment[:unique_reference]}" if attachment [ :unique_reference ] . present? references << "Command paper number: #{attachment[:command_paper_number]}" if attachme... | FIXME this has english in it so will cause problems if the locale is not en |
9,275 | def open_tcp_connection ( ipaddr , port , opts = { } ) @ipaddr , @port = ipaddr , port timeout = opts [ :connect_timeout ] ||= 1 io = nil begin io = Socket . tcp ( @ipaddr , @port , nil , nil , connect_timeout : timeout ) rescue Errno :: ECONNREFUSED , Errno :: ETIMEDOUT raise ModBusTimeout . new , 'Timed out attemptin... | Open TCP socket |
9,276 | def logging_bytes ( msg ) result = "" msg . each_byte do | c | byte = if c < 16 '0' + c . to_s ( 16 ) else c . to_s ( 16 ) end result << "[#{byte}]" end result end | Convert string of byte to string for log |
9,277 | def write_single_coil ( addr , val ) if val == 0 query ( "\x5" + addr . to_word + 0 . to_word ) else query ( "\x5" + addr . to_word + 0xff00 . to_word ) end self end | Write a single coil |
9,278 | def write_multiple_coils ( addr , vals ) nbyte = ( ( vals . size - 1 ) >> 3 ) + 1 sum = 0 ( vals . size - 1 ) . downto ( 0 ) do | i | sum = sum << 1 sum |= 1 if vals [ i ] > 0 end s_val = "" nbyte . times do s_val << ( sum & 0xff ) . chr sum >>= 8 end query ( "\xf" + addr . to_word + vals . size . to_word + nbyte . chr... | Write multiple coils |
9,279 | def read_discrete_inputs ( addr , ninputs ) query ( "\x2" + addr . to_word + ninputs . to_word ) . unpack_bits [ 0 .. ninputs - 1 ] end | Read discrete inputs |
9,280 | def write_multiple_registers ( addr , vals ) s_val = "" vals . each do | reg | s_val << reg . to_word end query ( "\x10" + addr . to_word + vals . size . to_word + ( vals . size * 2 ) . chr + s_val ) self end | Write multiple holding registers |
9,281 | def mask_write_register ( addr , and_mask , or_mask ) query ( "\x16" + addr . to_word + and_mask . to_word + or_mask . to_word ) self end | Mask a holding register |
9,282 | def query ( request ) tried = 0 response = "" begin :: Timeout . timeout ( @read_retry_timeout , ModBusTimeout ) do send_pdu ( request ) response = read_pdu end rescue ModBusTimeout => err log "Timeout of read operation: (#{@read_retries - tried})" tried += 1 retry unless tried >= @read_retries raise ModBusTimeout . ne... | Request pdu to slave device |
9,283 | def [] ( key ) if key . instance_of? ( 0 . class ) @slave . send ( "read_#{@type}" , key , 1 ) elsif key . instance_of? ( Range ) @slave . send ( "read_#{@type}s" , key . first , key . count ) else raise ModBus :: Errors :: ProxyException , "Invalid argument, must be integer or range. Was #{key.class}" end end | Initialize a proxy for a slave and a type of operation Read single or multiple values from a modbus slave depending on whether a Fixnum or a Range was given . Note that in the case of multiples a pluralized version of the method is sent to the slave |
9,284 | def []= ( key , val ) if key . instance_of? ( 0 . class ) @slave . send ( "write_#{@type}" , key , val ) elsif key . instance_of? ( Range ) if key . count != val . size raise ModBus :: Errors :: ProxyException , "The size of the range must match the size of the values (#{key.count} != #{val.size})" end @slave . send ( ... | Write single or multiple values to a modbus slave depending on whether a Fixnum or a Range was given . Note that in the case of multiples a pluralized version of the method is sent to the slave . Also when writing multiple values the number of elements must match the number of registers in the range or an exception is ... |
9,285 | def read_rtu_response ( io ) msg = nil while msg . nil? msg = io . read ( 2 ) end function_code = msg . getbyte ( 1 ) case function_code when 1 , 2 , 3 , 4 then msg += io . read ( 1 ) msg += io . read ( msg . getbyte ( 2 ) + 2 ) when 5 , 6 , 15 , 16 then msg += io . read ( 6 ) when 22 then msg += io . read ( 8 ) when 0... | We have to read specific amounts of numbers of bytes from the network depending on the function code and content |
9,286 | def crc16 ( msg ) crc_lo = 0xff crc_hi = 0xff msg . unpack ( 'c*' ) . each do | byte | i = crc_hi ^ byte crc_hi = crc_lo ^ CrcHiTable [ i ] crc_lo = CrcLoTable [ i ] end return ( ( crc_hi << 8 ) + crc_lo ) end | Calc CRC16 for massage |
9,287 | def each_expression ( include_self = false , & block ) traverse ( include_self ) do | event , exp , index | yield ( exp , index ) unless event == :exit end end | Iterates over the expressions of this expression as an array passing the expression and its index within its parent to the given block . |
9,288 | def flat_map ( include_self = false , & block ) result = [ ] each_expression ( include_self ) do | exp , index | if block_given? result << yield ( exp , index ) else result << [ exp , index ] end end result end | Returns a new array with the results of calling the given block once for every expression . If a block is not given returns an array with each expression and its level index as an array . |
9,289 | def run ( executable , * args ) executable_full = executable_path ( executable ) self . command = args | default_args self . command = command . sort . unshift ( executable_full ) system ( * self . command , system_options ) end | Run the given commands via a system call . The executable must be one of the permitted ClamAV executables . The arguments will be combined with default arguments if needed . The arguments are sorted alphabetically before being passed to the system . |
9,290 | def view_on db , view_name , query = { } , & block raise ArgumentError , "View query options must be set as symbols!" if query . keys . find { | k | k . is_a? ( String ) } view_name = view_name . to_s view_slug = "#{name}/#{view_name}" query = view_defaults ( view_name ) . merge ( query ) query [ :reduce ] ||= false if... | Dispatches to any named view in a specific database |
9,291 | def put_attachment ( name , file , options = { } ) raise ArgumentError , "doc must be saved" unless self . rev raise ArgumentError , "doc.database required to put_attachment" unless database result = database . put_attachment ( self , name , file , options ) self [ '_rev' ] = result [ 'rev' ] result [ 'ok' ] end | saves an attachment directly to couchdb |
9,292 | def fetch_attachment ( name ) raise ArgumentError , "doc must be saved" unless self . rev raise ArgumentError , "doc.database required to put_attachment" unless database database . fetch_attachment ( self , name ) end | returns an attachment s data |
9,293 | def delete_attachment ( name , force = false ) raise ArgumentError , "doc.database required to delete_attachment" unless database result = database . delete_attachment ( self , name , force ) self [ '_rev' ] = result [ 'rev' ] result [ 'ok' ] end | deletes an attachment directly from couchdb |
9,294 | def uri ( append_rev = false ) return nil if new? couch_uri = "#{database.root}/#{CGI.escape(id)}" if append_rev == true couch_uri << "?rev=#{rev}" elsif append_rev . kind_of? ( Integer ) couch_uri << "?rev=#{append_rev}" end couch_uri end | Returns the CouchDB uri for the document |
9,295 | def clean_uri ( uri ) uri = uri . dup uri . path = "" uri . query = nil uri . fragment = nil uri end | Duplicate and remove excess baggage from the provided URI |
9,296 | def prepare_http_connection conn = HTTPClient . new ( options [ :proxy ] || self . class . proxy ) set_http_connection_options ( conn , options ) conn end | Take a look at the options povided and try to apply them to the HTTP conneciton . |
9,297 | def set_http_connection_options ( conn , opts ) unless uri . user . to_s . empty? conn . force_basic_auth = true conn . set_auth ( uri . to_s , uri . user , uri . password ) end if opts . include? ( :verify_ssl ) conn . ssl_config . verify_mode = opts [ :verify_ssl ] ? OpenSSL :: SSL :: VERIFY_PEER : OpenSSL :: SSL :: ... | Prepare the http connection options for HTTPClient . We try to maintain RestClient compatability in option names as this is what we used before . |
9,298 | def send_request ( req , & block ) @last_response = @http . request ( req . delete ( :method ) , req . delete ( :uri ) , req , & block ) end | Send request and leave a reference to the response for debugging purposes |
9,299 | def payload_from_doc ( req , doc , opts = { } ) if doc . is_a? ( IO ) || doc . is_a? ( StringIO ) || doc . is_a? ( Tempfile ) req [ :header ] [ 'Content-Type' ] = mime_for ( req [ :uri ] . path ) doc elsif opts [ :raw ] || doc . nil? doc else MultiJson . encode ( doc . respond_to? ( :as_couch_json ) ? doc . as_couch_js... | Check if the provided doc is nil or special IO device or temp file . If not encode it into a string . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.