idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
12,900 | def stub_paperclip_s3 ( model , attachment , extension ) definition = model . gsub ( " " , "_" ) . classify . constantize . attachment_definitions [ attachment . to_sym ] path = "http://s3.amazonaws.com/:id/#{definition[:path]}" path . gsub! ( / \/ \. / ) do | match | "([^\/\.]+)" end begin FakeWeb . register_uri ( :pu... | Stubs the HTTP PUT for an attachment using S3 storage . |
12,901 | def check ( key : nil , url : nil , emoji : ":link:" , search_title : true , search_commits : false , fail_on_warning : false , report_missing : true , skippable : true ) throw Error ( "'key' missing - must supply JIRA issue key" ) if key . nil? throw Error ( "'url' missing - must supply JIRA installation URL" ) if url... | Checks PR for JIRA keys and links them |
12,902 | def make src = @file dst = Tempfile . new ( [ @basename , @format ? ".#{@format}" : '' ] ) dst . binmode begin parameters = [ ] parameters << source_file_options parameters << ":source" parameters << transformation_command parameters << convert_options parameters << ":dest" parameters = parameters . flatten . compact .... | Performs the conversion of the + file + into a thumbnail . Returns the Tempfile that contains the new image . |
12,903 | def transformation_command scale , crop = @current_geometry . transformation_to ( @target_geometry , crop? ) trans = [ ] trans << "-resize" << %["#{scale}"] unless scale . nil? || scale . empty? trans << "-crop" << %["#{crop}"] << "+repage" if crop trans end | Returns the command ImageMagick s + convert + needs to transform the image into the thumbnail . |
12,904 | def add_options ( options = { } , raw_options = nil ) @options . merge! ( options . stringify_keys ) unless options . blank? @raw_options << raw_options unless raw_options . blank? end | Merge additional options and raw_options |
12,905 | def reverse_add_options ( options = { } , raw_options = nil ) @options . reverse_merge! ( options . stringify_keys ) unless options . blank? @raw_options << raw_options unless raw_options . blank? end | Merge additional options and raw_options but don t overwrite existing |
12,906 | def content_type type = ( self . path . match ( / \. \w / ) [ 1 ] rescue "octet-stream" ) . downcase case type when %r" " then "image/jpeg" when %r" " then "image/tiff" when %r" " , "gif" , "bmp" then "image/#{type}" when "txt" then "text/plain" when %r" " then "text/html" when "js" then "application/js" when "csv" , "... | Infer the MIME - type of the file from the extension . |
12,907 | def packet ( * args ) code = args . pick ( String , :code ) base_namespace = args . pick ( :base_namespace ) do nil end no_base_namespace = args . pick ( :no_base_namespace ) do @no_base_namespace end privileges_ = args . pick ( Privileges , :privileges ) do Privileges . new end encoding = get_source_encoding ( code ) ... | Creates a packet of code with the given privileges to execute later as many times as neccessary |
12,908 | def verify params = to_hash . downcase_keys if TaxCloud . configuration . usps_username params = params . merge ( 'uspsUserID' => TaxCloud . configuration . usps_username ) end response = TaxCloud . client . request ( :verify_address , params ) TaxCloud :: Responses :: VerifyAddress . parse ( response ) end | Verify this address . |
12,909 | def zip return nil unless zip5 && ! zip5 . empty? [ zip5 , zip4 ] . select { | z | z && ! z . empty? } . join ( '-' ) end | Complete zip code . Returns a 9 - digit Zip Code when available . |
12,910 | def processor_options args = { } @other_args . each do | k , v | args [ k ] = v . respond_to? ( :call ) ? v . call ( attachment ) : v end [ :processors , :geometry , :format , :whiny , :convert_options ] . each do | k | ( arg = send ( k ) ) && args [ k ] = arg end args end | Supplies the hash of options that processors expect to receive as their second argument Arguments other than the standard geometry format etc are just passed through from initialization and any procs are called here just before post - processing . |
12,911 | def styles unless @normalized_styles @normalized_styles = { } ( @styles . respond_to? ( :call ) ? @styles . call ( self ) : @styles ) . each do | name , args | @normalized_styles [ name ] = Paperclip :: Style . new ( name , args . dup , self ) end end @normalized_styles end | Creates an Attachment object . + name + is the name of the attachment + instance + is the ActiveRecord object instance it s attached to and + options + is the same as the hash passed to + has_attached_file + . |
12,912 | def url ( style_name = default_style , use_timestamp = @use_timestamp ) url = original_filename . nil? ? interpolate ( @default_url , style_name ) : interpolate ( @url , style_name ) use_timestamp && updated_at ? [ url , updated_at ] . compact . join ( url . include? ( "?" ) ? "&" : "?" ) : url end | Returns the public URL of the attachment with a given style . Note that this does not necessarily need to point to a file that your web server can access and can point to an action in your app if you need fine grained security . This is not recommended if you don t need the security however for performance reasons . Se... |
12,913 | def add_tags ( jobflow_id , tags ) params = { :operation => 'AddTags' , :resource_id => jobflow_id , :tags => tags } aws_result = @aws_request . submit ( params ) yield aws_result if block_given? end | Sets the specified tags on all instances in the specified jobflow |
12,914 | def describe_cluster ( jobflow_id ) params = { :operation => 'DescribeCluster' , :cluster_id => jobflow_id , } aws_result = @aws_request . submit ( params ) yield aws_result if block_given? JSON . parse ( aws_result ) end | Provides details about the specified jobflow |
12,915 | def describe_step ( jobflow_id , step_id ) params = { :operation => 'DescribeStep' , :cluster_id => jobflow_id , :step_id => step_id } aws_result = @aws_request . submit ( params ) yield aws_result if block_given? JSON . parse ( aws_result ) end | Provides details about the specified step within an existing jobflow |
12,916 | def list_clusters ( options = { } ) params = { :operation => 'ListClusters' } params . merge! ( :cluster_states => options [ :states ] ) if options [ :states ] params . merge! ( :created_before => options [ :created_before ] . to_i ) if options [ :created_before ] params . merge! ( :created_after => options [ :created_... | List the clusters given specified filtering |
12,917 | def list_instance_groups ( jobflow_id ) params = { :operation => 'ListInstanceGroups' , :cluster_id => jobflow_id , } aws_result = @aws_request . submit ( params ) yield aws_result if block_given? JSON . parse ( aws_result ) end | List the instance groups in the specified jobflow |
12,918 | def list_bootstrap_actions ( jobflow_id ) params = { :operation => 'ListBootstrapActions' , :cluster_id => jobflow_id , } aws_result = @aws_request . submit ( params ) yield aws_result if block_given? JSON . parse ( aws_result ) end | List the bootstrap actions in the specified jobflow |
12,919 | def list_steps ( jobflow_id , options = { } ) params = { :operation => 'ListSteps' , :cluster_id => jobflow_id , } params . merge! ( :step_ids => options [ :step_ids ] ) if options [ :step_ids ] params . merge! ( :step_states => options [ :step_states ] ) if options [ :step_states ] params . merge! ( :marker => options... | List the steps in a job flow given specified filtering |
12,920 | def remove_tags ( jobflow_id , keys ) params = { :operation => 'RemoveTags' , :resource_id => jobflow_id , :tag_keys => keys } aws_result = @aws_request . submit ( params ) yield aws_result if block_given? end | Remove the specified tags on all instances in the specified jobflow |
12,921 | def set_termination_protection ( jobflow_ids , protection_enabled = true ) params = { :operation => 'SetTerminationProtection' , :termination_protected => protection_enabled , :job_flow_ids => jobflow_ids } aws_result = @aws_request . submit ( params ) yield aws_result if block_given? end | Enabled or disable termination protection on the specified job flows . Termination protection prevents a job flow from being terminated by a user initiated action although the job flow will still terminate naturally . |
12,922 | def set_visible_to_all_users ( jobflow_ids , visible = true ) params = { :operation => 'SetVisibleToAllUsers' , :visible_to_all_users => visible , :job_flow_ids => jobflow_ids } aws_result = @aws_request . submit ( params ) yield aws_result if block_given? end | Whether or not all IAM users in this account can access the job flows . |
12,923 | def assets Dir [ "#{directory}/**/*" ] . sort . select { | path | ! File . directory? ( path ) && ! File . basename ( path ) . include? ( "yml" ) } . map do | file | file_to_hash ( file ) end end | This method is used for the exporter to copy assets |
12,924 | def to_hash hash = { :slug => slug , :permalink => permalink , :name => name , :children => children , :siblings => siblings , :parent => parent , :ancestors => ancestors , :navigation => Bonsai :: Navigation . tree , :updated_at => mtime , :created_at => ctime } . merge ( formatted_content ) . merge ( disk_assets ) . ... | This hash is available to all templates it will map common properties content file results as well as any magic hashes for file system contents |
12,925 | def formatted_content formatted_content = content formatted_content . each do | k , v | if v . is_a? ( String ) and v =~ / \n / formatted_content [ k ] = to_markdown ( v ) end end formatted_content end | This method ensures that multiline strings are run through markdown and smartypants |
12,926 | def digest ( type = :sha1 ) case type when :sha1 Digest :: SHA1 . hexdigest ( @bindata ) when :sha256 Digest :: SHA256 . hexdigest ( @bindata ) when :md5 Digest :: MD5 . hexdigest ( @bindata ) else raise ArgumentError end end | return hex digest string of apk file |
12,927 | def entry ( name ) entry = @zip . find_entry ( name ) raise NotFoundError , "'#{name}'" if entry . nil? return entry end | find and return zip entry with name |
12,928 | def find ( & block ) found = [ ] self . each_file do | name , data | ret = block . call ( name , data ) found << name if ret end found end | find files which is matched with block condition |
12,929 | def icon icon_id = @manifest . doc . elements [ '/manifest/application' ] . attributes [ 'icon' ] if / \w \/ \w / =~ icon_id drawables = @resource . find ( icon_id ) Hash [ drawables . map { | name | [ name , file ( name ) ] } ] else { icon_id => file ( icon_id ) } end end | extract icon data from AndroidManifest and resource . |
12,930 | def signs signs = { } self . each_file do | path , data | next unless path =~ / \/ / && data . unpack ( "CC" ) == [ 0x30 , 0x82 ] signs [ path ] = OpenSSL :: PKCS7 . new ( data ) end signs end | apk s signature information |
12,931 | def certificates return Hash [ self . signs . map { | path , sign | [ path , sign . certificates . first ] } ] end | certificate info which is used for signing |
12,932 | def version_name ( lang = nil ) vername = @doc . root . attributes [ 'versionName' ] unless @rsc . nil? if / \w \/ \w / =~ vername opts = { } opts [ :lang ] = lang unless lang . nil? vername = @rsc . find ( vername , opts ) end end vername end | application version name |
12,933 | def to_xml ( indent = 4 ) xml = '' formatter = REXML :: Formatters :: Pretty . new ( indent ) formatter . write ( @doc . root , xml ) xml end | return xml as string format |
12,934 | def parse_attribute ns_id , name_id , val_str_id , flags , val = @io . read ( 4 * 5 ) . unpack ( "V*" ) key = @strings [ name_id ] unless ns_id == 0xFFFFFFFF ns = @strings [ ns_id ] prefix = ns . sub ( / \/ / , '' ) unless @ns . include? ns @ns << ns @doc . root . add_namespace ( prefix , ns ) end key = "#{prefix}:#{ke... | parse attribute of a element |
12,935 | def each_exception Dir . chdir ( @data_folder ) Dir . glob ( "*.exceptions.txt" ) . each do | file | if File . open ( File . join ( @data_folder , file ) , 'r' ) . read != '' yield HTMLValidationResult . load_from_files ( file . gsub ( '.exceptions.txt' , '' ) ) end end end | For each stored exception yield an HTMLValidationResult object to allow the user to call . accept! on the exception if it is OK . |
12,936 | def map_with_monad ( lam = nil , & blk ) bind { | v | self . class . unit ( ( lam || blk ) . call ( v ) ) } end | Returns a monad whose elements are the results of applying the given function to each element in this monad |
12,937 | def select ( lam = nil , & blk ) bind { | x | ( lam || blk ) . call ( x ) ? self . class . unit ( x ) : self . class . empty } end | Returns a monad whose elements are all those elements of this monad for which the given predicate returned true |
12,938 | def generate_signature ( params ) secret = params . delete ( :secret ) if '' == secret . to_s nil else OpenSSL :: HMAC . hexdigest ( algorithm , secret , canonical_representation ( params ) ) end end | create a new HMAC instance |
12,939 | def validate_url_signature ( url , secret , opts = { } ) opts = default_opts . merge ( opts ) opts [ :query_based ] = true uri = parse_url ( url ) query_values = Rack :: Utils . parse_nested_query ( uri . query ) return false unless query_values auth_params = query_values . delete ( opts [ :auth_param ] ) return false ... | convienience method to check the signature of a url with query - based authentication |
12,940 | def canonical_representation ( params ) rep = "" rep << "#{params[:method].upcase}\n" rep << "date:#{params[:date]}\n" rep << "nonce:#{params[:nonce]}\n" ( params [ :headers ] || { } ) . sort . each do | pair | name , value = * pair rep << "#{name.downcase}:#{value}\n" end rep << params [ :path ] p = ( params [ :query ... | generates the canonical representation for a given request |
12,941 | def sign_request ( url , secret , opts = { } ) opts = default_opts . merge ( opts ) uri = parse_url ( url ) headers = opts [ :headers ] || { } date = opts [ :date ] || Time . now . gmtime date = date . gmtime . strftime ( '%a, %d %b %Y %T GMT' ) if date . respond_to? :strftime method = opts [ :method ] ? opts [ :method... | sign the given request |
12,942 | def sign_url ( url , secret , opts = { } ) opts = default_opts . merge ( opts ) opts [ :query_based ] = true headers , url = * sign_request ( url , secret , opts ) url end | convienience method to sign a url for use with query - based authentication |
12,943 | def start EM . synchrony do web_server = Thin :: Server . start ( '0.0.0.0' , 3000 ) do use Rack :: CommonLogger use Rack :: ShowExceptions map '/presentation' do use Rack :: Lint run Rack :: Lobster . new end end end end | Multicasts discovery messages to advertise its root device any embedded devices and any services . |
12,944 | def stacktrace stacktrace = @struct [ :stacktrace ] return nil if stacktrace . null? dup = case @struct [ :type ] when :core Satyr :: FFI . sr_core_stacktrace_dup ( stacktrace ) when :python Satyr :: FFI . sr_python_stacktrace_dup ( stacktrace ) when :kerneloops Satyr :: FFI . sr_koops_stacktrace_dup ( stacktrace ) whe... | Parses given JSON string to create new Report Returns Stacktrace of the report |
12,945 | def find_crash_thread pointer = Satyr :: FFI . sr_stacktrace_find_crash_thread @struct . to_ptr raise SatyrError , "Could not find crash thread" if pointer . null? dup = Satyr :: FFI . sr_thread_dup ( pointer ) raise SatyrError , "Failed to duplicate thread" if dup . null? Thread . send ( :new , dup ) end | Returns Thread that likely caused the crash that produced this stack trace |
12,946 | def get_or_else ( val_or_lam = nil , & blk ) v_or_f = val_or_lam || blk if ! empty? then value else ( v_or_f . respond_to? ( :call ) ? v_or_f . call : v_or_f ) end end | Returns contents if Some or given value or result of given block or lambda if None |
12,947 | def inherit_errors ( error_object ) error_object = error_object . errors if error_object . respond_to? ( :errors ) error_object . each do | k , v | next if _error_ignores [ k . to_sym ] if respond_to? ( k ) errors . add ( k , v ) elsif _error_map [ k . to_sym ] errors . add ( _error_map [ k . to_sym ] , v ) else errors... | applies the errors in error_object to self returns false so failure cases can end with this invocation |
12,948 | def sanitize_params ( inputs ) out = { } . with_indifferent_access _fields . each_pair do | field , config | next unless inputs . key? ( field ) out [ field ] = :: Subroutine :: TypeCaster . cast ( inputs [ field ] , config ) end out end | if you want to use strong parameters or something in your form object you can do so here . by default we just slice the inputs to the defined fields |
12,949 | def or_else ( other ) PartialFunction . new ( lambda { | x | self . defined_at? ( x ) || other . defined_at? ( x ) } , lambda { | x | if self . defined_at? ( x ) then self . call ( x ) else other . call ( x ) end } ) end | Composes this partial function with a fallback partial function which gets applied where this partial function is not defined . |
12,950 | def and_then ( func ) PartialFunction . new ( @defined_at_proc , lambda { | x | func . call ( self . call ( x ) ) } ) end | Composes this partial function with a transformation function that gets applied to results of this partial function . |
12,951 | def request ( method = :get , path = '/files/' , params = { } ) response = @api_connection . send method , path , params response . body end | basic request method |
12,952 | def upload ( object , options = { } ) if file? ( object ) then upload_file ( object , options ) elsif object . is_a? ( Array ) then upload_files ( object , options ) elsif object . is_a? ( String ) then upload_url ( object , options ) else raise ArgumentError , "Expected input to be a file/Array/URL, given: `#{object}`... | intelegent guess for file or URL uploading |
12,953 | def upload_files ( files , options = { } ) data = upload_params ( options ) . for_file_upload ( files ) response = @upload_connection . post ( '/base/' , data ) response . body . values . map! { | f | Uploadcare :: Api :: File . new ( self , f ) } end | Upload multiple files |
12,954 | def upload_url ( url , options = { } ) params = upload_params ( options ) . for_url_upload ( url ) token = request_file_upload ( params ) upload_status = poll_upload_result ( token ) if upload_status [ 'status' ] == 'error' raise ArgumentError . new ( upload_status [ 'error' ] ) end Uploadcare :: Api :: File . new ( se... | Upload from an URL |
12,955 | def restore_original_new_method ( klass ) klass . define_singleton_method :new do | * args , & block | Throttling . original_new_method ( klass ) . bind ( klass ) . call * args , & block end end | Restores the original . new method of the including class |
12,956 | def throttle_connection_rate now = Time . now delta = now - ( last_new_connection_at || now ) _throttle ( delta , now ) if delta < OandaAPI . configuration . min_new_connection_interval && OandaAPI . configuration . use_request_throttling? self . last_new_connection_at = Time . now end | Throttles the connection rate by sleeping for a duration if the interval bewteen consecutive connections is less than the allowed minimum . Only throttles when the API is configured to use_request_throttling . |
12,957 | def append_class ( cls ) return unless cls if c = html_options [ "class" ] html_options [ "class" ] << " " + cls . to_s else if c = has_option? ( "class" ) c << " " + cls . to_s cls = c end html_options [ "class" ] = cls . to_s end end | Appends the given class to the class HTMl attribute . |
12,958 | def countersign_token ( token : , context : nil , options : 0x00 ) begin account_provider = RecoveryToken . account_provider_issuer ( token ) rescue RecoveryTokenSerializationError , UnknownProviderError raise TokenFormatError , "Could not determine provider" end counter_recovery_token = RecoveryToken . build ( issuer ... | Takes a binary representation of a token and signs if for a given account provider . Do not pass in a RecoveryToken object . The wrapping data structure is identical to the structure it s wrapping in format . |
12,959 | def validate_recovery_token! ( token , context = { } ) errors = [ ] begin account_provider = RecoveryToken . account_provider_issuer ( token ) rescue RecoveryTokenSerializationError , UnknownProviderError , TokenFormatError => e raise RecoveryTokenError , "Could not determine provider: #{e.message}" end begin recovery_... | Validate the token according to the processing instructions for the save - token endpoint . |
12,960 | def generate_recovery_token ( data : , audience : , context : nil , options : 0x00 ) token = RecoveryToken . build ( issuer : self , audience : audience , type : RECOVERY_TOKEN_TYPE , options : options ) token . data = self . encryptor . encrypt ( data , self , context ) [ token , seal ( token , context ) ] end | Generates a binary token with an encrypted arbitrary data payload . |
12,961 | def dangerous_unverified_recovery_token ( countersigned_token ) parsed_countersigned_token = RecoveryToken . parse ( Base64 . strict_decode64 ( countersigned_token ) ) RecoveryToken . parse ( parsed_countersigned_token . data ) end | Parses a countersigned_token and returns the nested recovery token WITHOUT verifying any signatures . This should only be used if no user context can be identified or if we re extracting issuer information . |
12,962 | def validate_countersigned_recovery_token! ( countersigned_token , context = { } ) begin recovery_provider = RecoveryToken . recovery_provider_issuer ( Base64 . strict_decode64 ( countersigned_token ) ) rescue RecoveryTokenSerializationError => e raise CountersignedTokenError . new ( "Countersigned token is invalid: " ... | Validates the countersigned recovery token by verifying the signature of the countersigned token parsing out the origin recovery token verifying the signature on the recovery token and finally decrypting the data in the origin recovery token . |
12,963 | def seal ( token , context = nil ) raise RuntimeError , "signing private key must be set" unless self . instance_variable_get ( :@signing_private_key ) binary_token = token . to_binary_s signature = self . encryptor . sign ( binary_token , self . instance_variable_get ( :@signing_private_key ) , self , context ) Base64... | Signs the provided token and joins the data with the signature . |
12,964 | def unseal ( token_and_signature , context = nil ) token = RecoveryToken . parse ( token_and_signature ) unless token . version . to_i == PROTOCOL_VERSION raise TokenFormatError , "Version field must be #{PROTOCOL_VERSION}" end token_data , signature = partition_signed_token ( token_and_signature , token ) self . unsea... | Splits the payload by the token size treats the remaining portion as the signature of the payload and verifies the signature is valid for the given payload . |
12,965 | def repeat ( ex , count , options = { } ) Repeater . new ( count , options ) . run ( ex , self ) end | Retries an example . |
12,966 | def method_missing ( name , * args , & block ) return type . send ( name ) if type if name . to_s . end_with? ( '?' ) @settings . send ( name , * args , & block ) end | Delegate unknown messages to the settings object |
12,967 | def add_stderr ( * args ) args = args . flatten . compact args = args . first . split ( $/ ) if args . size == 1 @stderr ||= [ ] @stderr << args @stderr . flatten! self end | Add STDERR output from the command executed via SSH . |
12,968 | def parse ( options ) store = record_store ( options . delete ( :store ) ) Dispatcher . strategy_classes . map { | klass | klass . parse ( @base , store , options ) } . flatten . compact . each do | strategy | raise "Multiple record cache definitions found for '#{strategy.attribute}' on #{@base.name}" if @strategy_by_a... | Parse the options provided to the cache_records method and create the appropriate cache strategies . |
12,969 | def invalidate ( strategy , value = nil ) ( value = strategy ; strategy = :id ) unless strategy . is_a? ( Symbol ) @strategy_by_attribute [ strategy ] . invalidate ( value ) if @strategy_by_attribute [ strategy ] end | Explicitly invalidate one or more records |
12,970 | def run_command ( meth , * args , & block ) runner = @parallel ? :run_command_parallel : :run_command_serial self . send ( runner , meth , * args , & block ) end | Determines whether to call the serial or parallel method then calls it . |
12,971 | def run_command_parallel ( meth , * args , & block ) debug "P: #{meth} on #{@boxes.size} boxes (#{@boxes.collect {|b| b.host }.join(', ')})" threads = [ ] raps = Rye :: Rap . new ( self ) ( @boxes || [ ] ) . each do | box | threads << Thread . new do Thread . current [ :rap ] = box . send ( meth , * args , & block ) en... | Run the command on all boxes in parallel |
12,972 | def run_command_serial ( meth , * args , & block ) debug "S: #{meth} on #{@boxes.size} boxes (#{@boxes.collect {|b| b.host }.join(', ')})" raps = Rye :: Rap . new ( self ) ( @boxes || [ ] ) . each do | box | raps << box . send ( meth , * args , & block ) end raps end | Run the command on all boxes in serial |
12,973 | def quote ( value , column = nil ) if value . kind_of? ( GeoRuby :: SimpleFeatures :: Geometry ) "'#{value.as_hex_ewkb}'" else original_quote ( value , column ) end end | Redefines the quote method to add behaviour for when a Geometry is encountered |
12,974 | def add_index ( table_name , column_name , options = { } ) column_names = Array ( column_name ) index_name = index_name ( table_name , :column => column_names ) if Hash === options index_type = options [ :unique ] ? "UNIQUE" : "" index_name = options [ :name ] || index_name index_method = options [ :spatial ] ? 'USING ... | Adds an index to a column . |
12,975 | def ostype return @rye_ostype if @rye_ostype os = self . quietly { uname . first } rescue nil os ||= 'unknown' os &&= os . downcase @rye_ostype = os end | Return the value of uname in lowercase This is a temporary fix . We can use SysInfo for this upload it execute it directly parse the output . |
12,976 | def unsafely ( * args , & block ) previous_state = @rye_safe disable_safe_mode ret = self . instance_exec * args , & block @rye_safe = previous_state ret end | Like batch except it disables safe mode before executing the block . After executing the block safe mode is returned back to whichever state it was previously in . In other words this method won t enable safe mode if it was already disabled . |
12,977 | def quietly ( * args , & block ) previous_state = @rye_quiet enable_quiet_mode ret = self . instance_exec * args , & block @rye_quiet = previous_state ret end | Like batch except it enables quiet mode before executing the block . After executing the block quiet mode is returned back to whichever state it was previously in . In other words this method won t enable quiet mode if it was already disabled . |
12,978 | def sudo ( * args , & block ) if block . nil? run_command ( 'sudo' , args ) ; else previous_state = @rye_sudo enable_sudo ret = self . instance_exec * args , & block @rye_sudo = previous_state ret end end | Like batch except it enables sudo mode before executing the block . If the user is already root this has no effect . Otherwise all commands executed in the block will run via sudo . |
12,979 | def prepend_env ( cmd ) return cmd unless @rye_current_environment_variables . is_a? ( Hash ) env = '' @rye_current_environment_variables . each_pair do | n , v | env << "export #{n}=#{Escape.shell_single_word(v)}; " end [ env , cmd ] . join ( ' ' ) end | Add the current environment variables to the beginning of + cmd + |
12,980 | def run_command ( * args , & blk ) debug "run_command" cmd , args = prep_args ( * args ) connect if ! @rye_ssh || @rye_ssh . closed? raise Rye :: NotConnected , @rye_host unless @rye_ssh && ! @rye_ssh . closed? cmd_clean = Rye . escape ( @rye_safe , cmd , args ) cmd_internal = prepend_env ( cmd_clean ) if @rye_current_... | Execute a command over SSH |
12,981 | def where_values ( attribute , type = :integer ) return @where_values [ attribute ] if @where_values . key? ( attribute ) @where_values [ attribute ] ||= array_of_values ( @wheres [ attribute ] , type ) end | Retrieve the values for the given attribute from the where statements Returns nil if no the attribute is not present |
12,982 | def where_value ( attribute , type = :integer ) values = where_values ( attribute , type ) return nil unless values && values . size == 1 values . first end | Retrieve the single value for the given attribute from the where statements Returns nil if the attribute is not present or if it contains multiple values |
12,983 | def file_append ( filepath , newcontent , backup = false ) content = StringIO . new if self . file_exists? ( filepath ) self . cp filepath , "#{filepath}-previous" if backup content = self . file_download filepath end if newcontent . is_a? ( StringIO ) newcontent . rewind content . puts newcontent . read else content .... | Append + newcontent + to remote + filepath + . If the file doesn t exist it will be created . If + backup + is specified + filepath + will be copied to + filepath - previous + before appending . |
12,984 | def file_write ( filepath , newcontent , backup = false ) if self . file_exists? ( filepath ) self . cp filepath , "#{filepath}-previous" if backup end content = StringIO . new content . puts newcontent self . file_upload content , filepath end | Write + newcontent + to remote + filepath + . If the file exists it will be overwritten . If + backup + is specified + filepath + will be copied to + filepath - previous + before appending . |
12,985 | def template_upload ( * paths ) remote_path = paths . pop templates = [ ] paths . collect! do | path | if StringIO === path path . rewind template = Rye :: Tpl . new ( path . read , "inline-template" ) elsif String === path raise "No such file: #{Dir.pwd}/#{path}" unless File . exists? ( path ) template = Rye :: Tpl . ... | Parse a template and upload that as a file to remote_path . |
12,986 | def file_exists? ( path ) begin ret = self . quietly { ls ( path ) } rescue Rye :: Err => ex ret = ex . rap end ! ( ret . exit_status > 0 ) || ret . stderr . empty? end | Does + path + from the current working directory? |
12,987 | def fetch_port ( host , port = 22 , localport = nil ) connect unless @rye_ssh if localport . nil? port_used = next_port else port_used = localport end @rye_ssh . forward . local ( port_used , host , port ) return port_used end | instance method that will setup a forward and return the port used |
12,988 | def connect ( reconnect = true ) raise Rye :: NoHost unless @rye_host return if @rye_ssh && ! reconnect disconnect if @rye_ssh if @rye_via debug "Opening connection to #{@rye_host} as #{@rye_user}, via #{@rye_via.host}" else debug "Opening connection to #{@rye_host} as #{@rye_user}" end highline = HighLine . new retrie... | Open an SSH session with + |
12,989 | def remove_hops! return unless @rye_ssh && @rye_ssh . forward . active_locals . count > 0 @rye_ssh . forward . active_locals . each { | fport , fhost | @rye_ssh . forward . cancel_local ( fport , fhost ) } if ! @rye_ssh . channels . empty? @rye_ssh . channels . each { | channel | channel [ - 1 ] . close } end return @r... | Cancel the port forward on all active local forwards |
12,990 | def disconnect return unless @rye_ssh && ! @rye_ssh . closed? begin debug "removing active forwards" remove_hops! debug "killing port_loop @rye_port_thread" @rye_port_thread . kill if @rye_ssh . busy? ; info "Is something still running? (ctrl-C to exit)" Timeout :: timeout ( 10 ) do @rye_ssh . loop ( 0.3 ) { @rye_ssh .... | Close the SSH session with + |
12,991 | def next_port port = @next_port @next_port -= 1 @next_port = MAX_PORT if @next_port < MIN_PORT begin TCPSocket . new '127.0.0.1' , port rescue Errno :: EADDRINUSE next_port ( ) rescue Errno :: ECONNREFUSED port else next_port ( ) end end | Grabs the next available port number and returns it . |
12,992 | def current_multi ( id_key_map ) current_versions = @store . read_multi ( * ( id_key_map . values ) ) Hash [ id_key_map . map { | id , key | [ id , current_versions [ key ] ] } ] end | Retrieve the current versions for the given keys |
12,993 | def run ( args ) run_option_parser ( args ) case @options [ :command ] when 'list' load_rewriters list_available_rewriters when 'open' open_rewriter when 'query' load_rewriters query_available_rewriters when 'show' load_rewriters show_rewriter when 'sync' sync_snippets else load_rewriters @options [ :snippet_names ] . ... | Initialize a CLI . Run the CLI . |
12,994 | def run_option_parser ( args ) optparse = OptionParser . new do | opts | opts . banner = 'Usage: synvert [project_path]' opts . on '-d' , '--load SNIPPET_PATHS' , 'load custom snippets, snippet paths can be local file path or remote http url' do | snippet_paths | @options [ :custom_snippet_paths ] = snippet_paths . spl... | Run OptionParser to parse arguments . |
12,995 | def load_rewriters Dir . glob ( File . join ( default_snippets_path , 'lib/**/*.rb' ) ) . each { | file | require file } @options [ :custom_snippet_paths ] . each do | snippet_path | if snippet_path =~ / / uri = URI . parse snippet_path eval ( uri . read ) else require snippet_path end end rescue FileUtils . rm_rf defa... | Load all rewriters . |
12,996 | def list_available_rewriters if Core :: Rewriter . availables . empty? puts 'There is no snippet under ~/.synvert, please run `synvert --sync` to fetch snippets.' else Core :: Rewriter . availables . each do | group , rewriters | puts group rewriters . each do | name , rewriter | puts ' ' + name end end puts end end | List and print all available rewriters . |
12,997 | def open_rewriter editor = [ ENV [ 'SYNVERT_EDITOR' ] , ENV [ 'EDITOR' ] ] . find { | e | ! e . nil? && ! e . empty? } return puts 'To open a synvert snippet, set $EDITOR or $SYNVERT_EDITOR' unless editor path = File . expand_path ( File . join ( default_snippets_path , "lib/#{@options[:snippet_name]}.rb" ) ) if File .... | Open one rewriter . |
12,998 | def query_available_rewriters Core :: Rewriter . availables . each do | group , rewriters | if group . include? @options [ :query ] puts group rewriters . each do | name , rewriter | puts ' ' + name end elsif rewriters . keys . any? { | name | name . include? @options [ :query ] } puts group rewriters . each do | na... | Query and print available rewriters . |
12,999 | def show_rewriter group , name = @options [ :snippet_name ] . split ( '/' ) rewriter = Core :: Rewriter . fetch ( group , name ) if rewriter rewriter . process_with_sandbox puts rewriter . description rewriter . sub_snippets . each do | sub_rewriter | puts puts '=' * 80 puts "snippet: #{sub_rewriter.name}" puts '=' * 8... | Show and print one rewriter . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.