idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
22,100 | def uncolored ( string = nil ) if block_given? yield . gsub ( COLORED_REGEXP , '' ) elsif string string . gsub ( COLORED_REGEXP , '' ) elsif respond_to? ( :to_str ) gsub ( COLORED_REGEXP , '' ) else '' end end | Returns an uncolored version of the string that is all ANSI - sequences are stripped from the string . |
22,101 | def try_update old_value = get new_value = yield old_value unless compare_and_set ( old_value , new_value ) raise ConcurrentUpdateError , "Update failed" end new_value end | Pass the current value to the given block replacing it with the block s result . Raise an exception if the update fails . |
22,102 | def _compare_and_set ( old_value , new_value ) return false unless @mutex . try_lock begin return false unless @value . equal? old_value @value = new_value ensure @mutex . unlock end true end | Atomically sets the value to the given updated value if the current value is equal the expected value . |
22,103 | def fulfill ( value = nil ) raise CannotTransitionError if rejected? return if fulfilled? unless resolved? self . value = value resolve_to ( :fulfilled ) end self end | Fulfill this promise with an optional value . The value will be stored in the deferred and passed along to any registered done callbacks . |
22,104 | def reject ( reason = nil ) raise CannotTransitionError if fulfilled? return if rejected? unless resolved? self . reason = reason resolve_to ( :rejected ) end self end | Reject this promise with an optional reason . The reason will be stored in the deferred and passed along to any registered fail callbacks . |
22,105 | def fail ( & block ) cb = Callback . new ( block ) rejected_callbacks << cb cb . call ( * callback_response ) if rejected? cb . promise end | Register a callback to be run when the deferred is rejected . |
22,106 | def always ( & block ) cb = Callback . new ( block ) always_callbacks << cb cb . call ( * callback_response ) if resolved? cb . promise end | Register a callback to be run when the deferred is resolved . |
22,107 | def get_component ( ctype , * args ) registry . lookup_ctype ( ctype ) . new ( * args ) . tap do | comp | comp . scope = full_scope comp . validate! end end | Fetch a component from within this component |
22,108 | def clean_aged ( time_now ) near_past = time_now - @time_window_in_seconds @errors = @errors . reverse . select { | time_stamp | time_stamp > near_past } . reverse . to_a end | clean up errors that are older than time_window_in_secons |
22,109 | def illustrate ( content , * args ) illustration = { :text => content . to_s , :show_when_passed => true , :show_when_failed => true , :show_when_pending => true } args . each { | arg | illustration [ arg ] = true if arg . is_a? ( Symbol ) illustration . merge! ( arg ) if arg . kind_of? ( Hash ) } RSpec . current_example . metadata [ :illustrations ] << illustration content end | Stores an object in the surrounding example s metadata which can be used by the output formatter as an illustration for the example . |
22,110 | def connect ( signal , * args , & block ) if block_given? observer = block if args . size == 1 && args . first . is_a? ( Hash ) options = args . first elsif args . size == 0 options = { } else raise ArgumentError , 'When given a block, #connect only expects a signal and options hash as arguments' end else observer = args . shift raise ArgumentError , 'Use a block, method or proc to specify an observer' unless observer . respond_to? ( :call ) if args . any? options = args . shift raise ArgumentError , '#connect only expects a signal, method and options hash as arguments' unless options . is_a? ( Hash ) || args . any? else options = { } end end observers [ signal ] ||= Stack . new observers [ signal ] . push ( observer , options [ :priority ] ) end | Register a observer for a given signal . |
22,111 | def disconnect ( signal , observer ) return nil unless observers . key? ( signal ) observers [ signal ] . delete ( observer ) end | Removes an observer from a signal stack so it no longer gets triggered . |
22,112 | def identifier case @typecode when nil 'void' when BOOL 'char' when BYTE 'char' when UBYTE 'unsigned char' when SINT 'short int' when USINT 'unsigned short int' when INT 'int' when UINT 'unsigned int' when SFLOAT 'float' when DFLOAT 'double' else if @typecode < Pointer_ 'unsigned char *' elsif @typecode < INDEX_ 'int' else raise "No identifier available for #{@typecode.inspect}" end end end | Construct GCC type |
22,113 | def identifiers if @typecode < Composite GCCType . new ( @typecode . element_type ) . identifiers * @typecode . num_elements else [ GCCType . new ( @typecode ) . identifier ] end end | Get array of C identifiers for native type |
22,114 | def r2c case @typecode when BOOL [ proc { | expr | "( #{expr} ) != Qfalse" } ] when BYTE , UBYTE , SINT , USINT , INT , UINT [ proc { | expr | "NUM2INT( #{expr} )" } ] when SFLOAT , DFLOAT [ proc { | expr | "NUM2DBL( #{expr} )" } ] else if @typecode < Pointer_ [ proc { | expr | "(#{identifier})mallocToPtr( #{expr} )" } ] elsif @typecode < Composite GCCType . new ( @typecode . element_type ) . r2c * @typecode . num_elements else raise "No conversion available for #{@typecode.inspect}" end end end | Get code for converting Ruby VALUE to C value |
22,115 | def add ( item , weight ) delta = Integer ( weight ) if delta > 0 new_weight = @total_weight + delta weights [ @total_weight ... new_weight ] = item @total_weight = new_weight end end | Sets initial weights |
22,116 | def extract_item weight = Random . rand ( @total_weight ) @weights . each do | range , item | return item if range === weight end end | Extract item based on weights distribution |
22,117 | def entries extract_detail ( :hostlist ) . map do | host | host =~ / / ? HostGroup . new ( host ) : ExecuteHost . new ( host ) end end | Direct entries in this HostGroup s hostlist attribute |
22,118 | def hosts entries . map do | entry | entry . is_a? ( HostGroup ) ? entry . hosts : entry end . flatten . uniq end | A recursive listing of all hosts associated with this HostGroup |
22,119 | def datify ( str ) pttrn = / \d \/ \d \/ \d \W \d \: \d / day , month , year , dummy , hour , min = str . match ( pttrn ) . captures . map { | d | d ? d . to_i : 0 } case year when 0 .. 69 year += 2000 when 70 .. 99 year += 1900 end DateTime . civil year , month , day , hour , min end | Extracts and returns the first provable DateTime from a string |
22,120 | def format idx case idx when Integer @formats [ idx ] || @default_format when String @formats . find do | fmt | fmt . name == idx end end end | The Format at _idx_ or - if _idx_ is a String - the Format with name == _idx_ |
22,121 | def execute_next ( & block ) @mutex . synchronize do if @active_thread condition_variable = ConditionVariable . new @waiting_threads . unshift ( condition_variable ) condition_variable . wait ( @mutex ) end @active_thread = true end return_value = yield ensure @mutex . synchronize do @active_thread = false next_waiting_thread = @waiting_threads . shift next_waiting_thread &. signal end end | Execute a block next . If no other thread is executing a block the block will be executed immediately . If another thread is executing a block add the thread to the front of the queue and executes the block when the current thread has finished its block . |
22,122 | def transform_file_name ( file ) if @bind variables = file . scan ( / / ) . flatten variables . each do | v | file . sub! ( "{{#{v}}}" , @bind . get_binding . eval ( v ) ) end end ( ! @nomodify && file . end_with? ( ".erb" ) && ! File . directory? ( file ) ) ? File . basename ( file , ".*" ) : file end | Expands the variable - in - file - name notation . |
22,123 | def which ( prog , path = ENV [ 'PATH' ] ) path . split ( File :: PATH_SEPARATOR ) . each do | dir | file = File . join ( dir , prog ) return file if File . executable? ( file ) && ! File . directory? ( file ) end nil end | Looks for the first occurrence of program within path . |
22,124 | def whereis ( prog , path = ENV [ 'PATH' ] ) dirs = [ ] path . split ( File :: PATH_SEPARATOR ) . each do | dir | f = File . join ( dir , prog ) if File . executable? ( f ) && ! File . directory? ( f ) if block_given? yield f else dirs << f end end end dirs . empty? ? nil : dirs end | In block form yields each program within path . In non - block form returns an array of each program within path . Returns nil if not found found . |
22,125 | def get ( resource_uri ) result = connection . get ( "resource" ) do | request | request . query [ :uri ] = resource_uri . to_s request . query . delete ( :graph ) end MaybeGraphResult . new ( result ) . value end | Returns an RDFSource represented by the resource URI . |
22,126 | def delete ( resource_uri ) connection . delete ( "resource" ) do | request | request . query [ :uri ] = resource_uri . to_s request . query . delete ( :graph ) end end | Deletes a subject from the context . |
22,127 | def partial_email @partial_email ||= begin uid , _ , domain = email . partition ( '@' ) if uid . length < 4 uid = '*' * uid . length elsif uid . length < 8 uid = uid [ 0 .. 2 ] + ( '*' * ( uid . length - 3 ) ) else uid = uid [ 0 .. 2 ] + ( '*' * ( uid . length - 6 ) ) + uid [ - 3 .. - 1 ] end "#{uid}@#{domain}" end end | Gets the email address in a partially obfuscated fashion . |
22,128 | def effective_groups ( refresh = false ) @effective_groups = nil if refresh @effective_groups ||= if system_admin? AccessGroup . all . map { | g | g . to_s . upcase } else groups . collect { | g | g . effective_groups } . flatten end . map { | g | g . to_s . upcase } . uniq . sort end | Gets the effective group membership of this user . |
22,129 | def has_any_group? ( * group_list ) return :system_admin if system_admin? return false if anonymous? r = group_list . select { | g | effective_groups . include? ( g . upcase ) } r . blank? ? false : r end | Does this user have the equivalent of one or more of these groups? |
22,130 | def remember self . remember_token = Incline :: User :: new_token update_attribute ( :remember_digest , Incline :: User :: digest ( self . remember_token ) ) end | Generates a remember token and saves the digest to the user model . |
22,131 | def authenticated? ( attribute , token ) return false unless respond_to? ( "#{attribute}_digest" ) digest = send ( "#{attribute}_digest" ) return false if digest . blank? BCrypt :: Password . new ( digest ) . is_password? ( token ) end | Determines if the supplied token digests to the stored digest in the user model . |
22,132 | def disable ( other_user , reason ) return false unless other_user &. system_admin? return false if other_user == self update_columns ( disabled_by : other_user . email , disabled_at : Time . now , disabled_reason : reason , enabled : false ) && refresh_comments end | Disables the user . |
22,133 | def create_reset_digest self . reset_token = Incline :: User :: new_token update_columns ( reset_digest : Incline :: User :: digest ( reset_token ) , reset_sent_at : Time . now ) end | Creates a reset token and stores the digest to the user model . |
22,134 | def failed_login_streak @failed_login_streak ||= begin results = login_histories . where . not ( successful : true ) if last_successful_login results = results . where ( 'created_at > ?' , last_successful_login . created_at ) end results . order ( created_at : :desc ) end end | Gets the failed logins for a user since the last successful login . |
22,135 | def add_hook ( hook , & block ) fail ArgumentError , "Invalid hook `#{hook}'" unless HOOKS . keys . include? hook fail ArgumentError , 'Block require' unless block_given? options [ hook ] = block end | Add hook . In all hook whill be passed + self + |
22,136 | def make_infobase! fail MethodDenied , :make_infobase! if read_only? before_make . call ( self ) maker . execute ( self ) after_make . call ( self ) self end | Make new empty infobase wrpped in + before_make + and + after_make + hooks |
22,137 | def rm_infobase! fail MethodDenied , :rm_infobase! if read_only? before_rm . call ( self ) destroyer . execute ( self ) after_rm . call ( self ) end | Remove infobase wrpped in + before_rm + and + after_rm + hooks |
22,138 | def dump ( path ) designer do dumpIB path end . run . wait . result . verify! path end | Dump infobase to + . dt + file |
22,139 | def restore! ( path ) fail MethodDenied , :restore! if read_only? designer do restoreIB path end . run . wait . result . verify! path end | Restore infobase from + . dt + file |
22,140 | def memoize ( methods , cache = nil ) cache ||= Hoodie :: Stash . new methods . each do | name | uncached_name = "#{name}_uncached" . to_sym singleton_class . class_eval do alias_method uncached_name , name define_method ( name ) do | * a , & b | cache . cache ( name ) { send uncached_name , * a , & b } end end end end | Create a new memoized method . To use extend class with Memoizable then in initialize call memoize |
22,141 | def parallel_finalize active_plugins . each do | namespace , namespace_plugins | namespace_plugins . each do | plugin_type , type_plugins | type_plugins . each do | instance_name , plugin | remove ( plugin ) end end end end | Initialize a new Nucleon environment |
22,142 | def define_plugin ( namespace , plugin_type , base_path , file , & code ) @@environments [ @actor_id ] . define_plugin ( namespace , plugin_type , base_path , file , & code ) myself end | Define a new plugin provider of a specified plugin type . |
22,143 | def authenticate! return unless @authenticated . nil? id , access_token = @params . retrieve_id , @params . retrieve_access_token @key_for_access_token = @scope . key_for_access_token ( id , access_token ) if access_token && ! access_token . empty? ApiWarden . redis { | conn | @value_for_access_token = conn . get ( @key_for_access_token ) } end unless @value_for_access_token @authenticated = false raise AuthenticationError end @authenticated = true @id = id @access_token = access_token self end | This method will only authenticate once and cache the result . |
22,144 | def ttl_for_access_token = ( seconds ) raise_if_authentication_failed! key = @key_for_access_token value = @value_for_access_token ApiWarden . redis { | conn | conn . set ( key , value , ex : seconds ) } end | Set the ttl for access token . |
22,145 | def build controller_name = @klass . name . gsub ( / / , '' ) . underscore Rails . application . routes . routes . each_with_object ( { } ) do | route , comments | if route . defaults [ :controller ] == controller_name verb_match = route . verb . to_s . match ( / \^ \$ / ) verbs = verb_match . nil? ? '*' : verb_match [ 1 ] ( comments [ route . defaults [ :action ] ] ||= [ ] ) << "#{verbs} #{route.ast}" end end end | takes a controller builds the lines to be put into the file |
22,146 | def set ( full_key , node ) fail 'value should be a I18n::Processes::Data::Tree::Node' unless node . is_a? ( Node ) key_part , rest = split_key ( full_key , 2 ) child = key_to_node [ key_part ] if rest unless child child = Node . new ( key : key_part , parent : parent , children : [ ] , warn_about_add_children_to_leaf : @warn_add_children_to_leaf ) append! child end unless child . children warn_add_children_to_leaf child if @warn_about_add_children_to_leaf child . children = [ ] end child . children . set rest , node else remove! child if child append! node end dirty! node end | add or replace node by full key |
22,147 | def decode_irc! ( string , encoding = :irc ) if encoding == :irc string . force_encoding ( "UTF-8" ) if ! string . valid_encoding? string . force_encoding ( "CP1252" ) . encode! ( "UTF-8" , { :invalid => :replace , :undef => :replace } ) end else string . force_encoding ( encoding ) . encode! ( { :invalid => :replace , :undef => :replace } ) string = string . chars . select { | c | c . valid_encoding? } . join end return string end | Decode a message from an IRC connection modifying it in place . |
22,148 | def encode_irc! ( string , encoding = :irc ) if encoding == :irc begin string . encode! ( "CP1252" ) rescue :: Encoding :: UndefinedConversionError end else string . encode! ( encoding , { :invalid => :replace , :undef => :replace } ) . force_encoding ( "ASCII-8BIT" ) end return string end | Encode a message to be sent over an IRC connection modifying it in place . |
22,149 | def reload fields = fetch_fields @mail = Mail . new ( fields [ "BODY[]" ] ) @flags = fields [ "FLAGS" ] @date = Time . parse ( fields [ "INTERNALDATE" ] ) self end | Fetch this message from the server and update all its attributes |
22,150 | def save! mailbox . select! connection . append ( mailbox . name , raw_message , flags , date ) end | Append this message to the remote mailbox |
22,151 | def copy_to! ( mailbox_name ) mailbox . select! connection . uid_copy ( [ uid ] , Luggage :: Mailbox . convert_mailbox_name ( mailbox_name ) ) end | Uses IMAP s COPY command to copy the message into the named mailbox |
22,152 | def generate options = { } options [ :title ] = title if title options [ :format ] = format if format options [ :output ] = output if output options [ :config ] = config if config options [ :files ] = collect_files locat = :: LOCat :: Command . new ( options ) locat . run end | S E R V I C E M E T H O D S Render templates . |
22,153 | def index_authorize if ! :: Authorization :: Fbuser :: V1 :: User . index? ( current_user ) render :json => { errors : "User is not authorized for this action" } , status : :forbidden end end | Authorizations below here |
22,154 | def thePi hash = HashWithThermalFission . new hash . thermal_fission [ :U235 ] = 0.98 hash . thermal_fission [ :Pu239 ] = 0.01 hash . thermal_fission [ :U238 ] = 0.01 hash . thermal_fission end | thePi is Pi in ANS - 5 . 1 - 1979 . |
22,155 | def theU235_alpha array = Array . new ( 23 ) array [ 0 ] = 6.5057E-01 array [ 1 ] = 5.1264E-01 array [ 2 ] = 2.4384E-01 array [ 3 ] = 1.3850E-01 array [ 4 ] = 5.544E-02 array [ 5 ] = 2.2225E-02 array [ 6 ] = 3.3088E-03 array [ 7 ] = 9.3015E-04 array [ 8 ] = 8.0943E-04 array [ 9 ] = 1.9567E-04 array [ 10 ] = 3.2535E-05 array [ 11 ] = 7.5595E-06 array [ 12 ] = 2.5232E-06 array [ 13 ] = 4.9948E-07 array [ 14 ] = 1.8531E-07 array [ 15 ] = 2.6608E-08 array [ 16 ] = 2.2398E-09 array [ 17 ] = 8.1641E-12 array [ 18 ] = 8.7797E-11 array [ 19 ] = 2.5131E-14 array [ 20 ] = 3.2176E-16 array [ 21 ] = 4.5038E-17 array [ 22 ] = 7.4791E-17 array end | theU235_alpha is alpha in ANS - 5 . 1 - 1979 Table 7 . |
22,156 | def theU235_lamda array = Array . new ( 23 ) array [ 0 ] = 2.2138E+01 array [ 1 ] = 5.1587E-01 array [ 2 ] = 1.9594E-01 array [ 3 ] = 1.0314E-01 array [ 4 ] = 3.3656E-02 array [ 5 ] = 1.1681E-02 array [ 6 ] = 3.5870E-03 array [ 7 ] = 1.3930E-03 array [ 8 ] = 6.2630E-04 array [ 9 ] = 1.8906E-04 array [ 10 ] = 5.4988E-05 array [ 11 ] = 2.0958E-05 array [ 12 ] = 1.0010E-05 array [ 13 ] = 2.5438E-06 array [ 14 ] = 6.6361E-07 array [ 15 ] = 1.2290E-07 array [ 16 ] = 2.7213E-08 array [ 17 ] = 4.3714E-09 array [ 18 ] = 7.5780E-10 array [ 19 ] = 2.4786E-10 array [ 20 ] = 2.2384E-13 array [ 21 ] = 2.4600E-14 array [ 22 ] = 1.5699E-14 array end | theU235_lamda is lamda in ANS - 5 . 1 - 1979 Table 7 . |
22,157 | def thePu239_alpha array = Array . new ( 23 ) array [ 0 ] = 2.083E-01 array [ 1 ] = 3.853E-01 array [ 2 ] = 2.213E-01 array [ 3 ] = 9.460E-02 array [ 4 ] = 3.531E-02 array [ 5 ] = 2.292E-02 array [ 6 ] = 3.946E-03 array [ 7 ] = 1.317E-03 array [ 8 ] = 7.052E-04 array [ 9 ] = 1.432E-04 array [ 10 ] = 1.765E-05 array [ 11 ] = 7.347E-06 array [ 12 ] = 1.747E-06 array [ 13 ] = 5.481E-07 array [ 14 ] = 1.671E-07 array [ 15 ] = 2.112E-08 array [ 16 ] = 2.996E-09 array [ 17 ] = 5.107E-11 array [ 18 ] = 5.730E-11 array [ 19 ] = 4.138E-14 array [ 20 ] = 1.088E-15 array [ 21 ] = 2.454E-17 array [ 22 ] = 7.557E-17 array end | thePu239_alpha is alpha in ANS - 5 . 1 - 1979 Table 8 . |
22,158 | def thePu239_lamda array = Array . new ( 23 ) array [ 0 ] = 1.002E+01 array [ 1 ] = 6.433E-01 array [ 2 ] = 2.186E-01 array [ 3 ] = 1.004E-01 array [ 4 ] = 3.728E-02 array [ 5 ] = 1.435E-02 array [ 6 ] = 4.549E-03 array [ 7 ] = 1.328E-03 array [ 8 ] = 5.356E-04 array [ 9 ] = 1.730E-04 array [ 10 ] = 4.881E-05 array [ 11 ] = 2.006E-05 array [ 12 ] = 8.319E-06 array [ 13 ] = 2.358E-06 array [ 14 ] = 6.450E-07 array [ 15 ] = 1.278E-07 array [ 16 ] = 2.466E-08 array [ 17 ] = 9.378E-09 array [ 18 ] = 7.450E-10 array [ 19 ] = 2.426E-10 array [ 20 ] = 2.210E-13 array [ 21 ] = 2.640E-14 array [ 22 ] = 1.380E-14 array end | thePu239_lamda is lamda in ANS - 5 . 1 - 1979 Table 8 . |
22,159 | def theU238_alpha array = Array . new ( 23 ) array [ 0 ] = 1.2311E+0 array [ 1 ] = 1.1486E+0 array [ 2 ] = 7.0701E-01 array [ 3 ] = 2.5209E-01 array [ 4 ] = 7.187E-02 array [ 5 ] = 2.8291E-02 array [ 6 ] = 6.8382E-03 array [ 7 ] = 1.2322E-03 array [ 8 ] = 6.8409E-04 array [ 9 ] = 1.6975E-04 array [ 10 ] = 2.4182E-05 array [ 11 ] = 6.6356E-06 array [ 12 ] = 1.0075E-06 array [ 13 ] = 4.9894E-07 array [ 14 ] = 1.6352E-07 array [ 15 ] = 2.3355E-08 array [ 16 ] = 2.8094E-09 array [ 17 ] = 3.6236E-11 array [ 18 ] = 6.4577E-11 array [ 19 ] = 4.4963E-14 array [ 20 ] = 3.6654E-16 array [ 21 ] = 5.6293E-17 array [ 22 ] = 7.1602E-17 array end | theU238_alpha is alpha in ANS - 5 . 1 - 1979 Table 9 . |
22,160 | def theU238_lamda array = Array . new ( 23 ) array [ 0 ] = 3.2881E+0 array [ 1 ] = 9.3805E-01 array [ 2 ] = 3.7073E-01 array [ 3 ] = 1.1118E-01 array [ 4 ] = 3.6143E-02 array [ 5 ] = 1.3272E-02 array [ 6 ] = 5.0133E-03 array [ 7 ] = 1.3655E-03 array [ 8 ] = 5.5158E-04 array [ 9 ] = 1.7873E-04 array [ 10 ] = 4.9032E-05 array [ 11 ] = 1.7058E-05 array [ 12 ] = 7.0465E-06 array [ 13 ] = 2.3190E-06 array [ 14 ] = 6.4480E-07 array [ 15 ] = 1.2649E-07 array [ 16 ] = 2.5548E-08 array [ 17 ] = 8.4782E-09 array [ 18 ] = 7.5130E-10 array [ 19 ] = 2.4188E-10 array [ 20 ] = 2.2739E-13 array [ 21 ] = 9.0536E-14 array [ 22 ] = 5.6098E-15 array end | theU238_lamda is lamda in ANS - 5 . 1 - 1979 Table 9 . |
22,161 | def run rockit_file = CONFIG_FILES . select { | f | File . exists? ( f ) } . first raise ArgumentError "No Rockitfile found (looking for: #{CONFIG_FILES.join(',')})" unless rockit_file Dsl . new ( self ) . instance_eval ( File . read ( rockit_file ) , rockit_file ) end | Run a Rockit configuration file and Rails dependency checks unless turned off by configuration . |
22,162 | def if_string_digest_changed ( key , input , & block ) if_string_changed ( key , Digest :: SHA256 . new . update ( input . to_s ) . hexdigest . to_s , & block ) end | If the digest of the input is different from the stored key execute the block . |
22,163 | def if_file_changed ( file , & block ) if_string_changed ( file , Digest :: SHA256 . file ( file ) . hexdigest . to_s , & block ) end | If the digest of the file is different from the stored digest execute the block . |
22,164 | def if_string_changed ( key , new_value , & block ) if new_value != @hash_store [ key ] old_value = @hash_store [ key ] @hash_store [ key ] = new_value block . call ( key , new_value , old_value ) if block_given? end end | Execute the given block if the input is different from the output . |
22,165 | def system_exit_on_error ( command , options = { } ) options = { 'print_command' => true } . merge ( string_keys ( options ) ) output command if options [ 'print_command' ] || @debug command_output = system_command ( command ) output command_output if @debug unless last_process . success? result = options [ 'on_failure' ] . call ( command , options ) if options [ 'on_failure' ] . is_a? ( Proc ) return true if result output options [ 'failure_message' ] || command_output return exit ( last_process . exitstatus ) end options [ 'on_success' ] . call ( command , options ) if options [ 'on_success' ] . is_a? ( Proc ) true end | Run system commands and if not successful exit and print out an error message . Default behavior is to print output of a command when it does not return success . |
22,166 | def _find_file! ( name , reference_path ) sub_path = File . expand_path ( name , File . dirname ( reference_path ) ) if File . exist? ( sub_path ) return if sub_path . end_with? ( '.rb' ) sub_path else bade_path = "#{sub_path}.bade" rb_path = "#{sub_path}.rb" bade_exist = File . exist? ( bade_path ) rb_exist = File . exist? ( rb_path ) relative = Pathname . new ( reference_path ) . relative_path_from ( Pathname . new ( File . dirname ( file_path ) ) ) . to_s if bade_exist && rb_exist message = "Found both .bade and .rb files for `#{name}` in file #{relative}, " 'change the import path so it references uniq file.' raise LoadError . new ( name , reference_path , message ) elsif bade_exist return bade_path elsif rb_exist return else message = "Can't find file matching name `#{name}` referenced from file #{relative}" raise LoadError . new ( name , reference_path , message ) end end end | Tries to find file with name if no file could be found or there are multiple files matching the name error is raised |
22,167 | def equals object if table == object . table && database == object . database return true end return false end | Compares the object with another metadata object Return true if they are for the same table |
22,168 | def store! Kernel . p "$$$$$$$$$$$$$$$$$$ @ssh CHECK $$$$$$$$$$$$$$$$$$" cmd = "echo \"#{self.to_json.gsub("\"","\\\\\"")}\" > #{@filepath}.json" puts cmd result = @ssh . exec! ( cmd ) puts result end | Writes Json to file using echo file is written to remote server via SSH Echo is used for writing the file |
22,169 | def formatted copy = dup @formats . rcompact! if copy . length < @formats . size copy . concat Array . new ( @formats . size - copy . length ) end copy end | Returns a copy of self with nil - values appended for empty cells that have an associated Format . This is primarily a helper - function for the writer classes . |
22,170 | def relative_to_local_path ( path ) if path && path . length > 0 case_insensitive_join ( local_path , path ) else case_insensitive_resolve ( local_path ) end end | assumes local_path is defined |
22,171 | def relative_to_remote_path ( path ) if path && path . length > 0 File . join ( remote_path , path ) else remote_path end end | assumes remote_path is defined |
22,172 | def config @config ||= begin Hash . new do | hash , key | raise ConfigurationError , "Configuration key #{key} in task #{name} doesn't exist" end . tap do | hash | hash . define_singleton_method ( :declare ) do | * keys | keys . each { | key | self [ key ] = nil unless self . has_key? ( key ) } end end end end | don t use this if you don t have to! |
22,173 | def deliver! return true unless Apostle . deliver unless template_id && template_id != '' raise DeliveryError , 'No email template_id provided' end queue = Apostle :: Queue . new queue . add self queue . deliver! if queue . results [ :valid ] . include? ( self ) return true else raise _exception end end | Shortcut method to deliver a single message |
22,174 | def start @exchange = @channel . topic ( @exchange_name , :durable => true , :auto_delete => false , :internal => true ) @queue = @channel . queue ( @queue_name , :durable => true , :auto_delete => false ) @queue . bind ( @exchange , :routing_key => 'publish.#' ) @queue . subscribe ( & @consumer . method ( :handle_message ) ) end | begin listening for all topics in publish . |
22,175 | def cached_rate ( original , target ) if defined? ( Rails ) unless rate = Rails . cache . read ( "#{original}_#{target}_#{stringified_exchange_date}" ) rate = ( 1.0 / Rails . cache . read ( "#{target}_#{original}_#{stringified_exchange_date}" ) ) rescue nil end rate end end | Tries to either get rate or calculate the inverse rate from cache . |
22,176 | def pass_method_to_warning_closer ( symbol , closer ) raise "A closer is needed to identify the warning_closer" unless closer . kind_of? Closer warning_closer = warning_closers . where ( :closer_id => closer . id ) . first warning_closer . send ( symbol ) if warning_closer end | Allows acts_as_list methods to be used within the warning . If closers were the act_as_list object you could do things like this |
22,177 | def find ( content = nil , & block ) if content and block_given? raise "TreeNode::find - passed content AND block" end if content if content . class == Regexp block = proc { | l | l . content =~ content } else block = proc { | l | l . content == content } end end return self if block . call ( self ) leaf = @leaves . find { | l | block . call ( l ) } return leaf if leaf @children . each do | child | node = child . find & block return node if node end nil end | Find a node down the hierarchy with content |
22,178 | def matches ( charset ) values . select { | v | v == charset || v == '*' } . sort { | a , b | a == '*' ? 1 : ( b == '*' ? - 1 : 0 ) } end | Returns an array of character sets from this header that match the given + charset + ordered by precedence . |
22,179 | def get_capture_items ( c_uuid ) url = "#{@server_url}/items/#{c_uuid}.json?per_page=500" json = self . get_json ( url ) captures = [ ] capture = json [ "nyplAPI" ] [ "response" ] [ "capture" ] captures << capture totalPages = json [ "nyplAPI" ] [ "request" ] [ "totalPages" ] . to_i if totalPages >= 2 puts "total pages " + totalPages . to_s if @debug ( 2 .. totalPages ) . each do | page | puts "page: " + page . to_s if @debug newurl = url + "&page=#{page}" json = self . get_json ( newurl ) newcapture = json [ "nyplAPI" ] [ "response" ] [ "capture" ] captures << newcapture end end captures . flatten! captures end | Given a container uuid or biblographic uuid returns a list of mods uuids . |
22,180 | def get_mods_item ( mods_uuid ) url = "#{@server_url}/items/mods/#{mods_uuid}.json" json = self . get_json ( url ) item = nil if json [ "nyplAPI" ] [ "response" ] [ "mods" ] item = json [ "nyplAPI" ] [ "response" ] [ "mods" ] end return item end | get the item detail from a uuid |
22,181 | def get_bibl_uuid ( image_id ) url = "#{@server_url}/items/local_image_id/#{image_id}.json" json = self . get_json ( url ) bibl_uuid = nil if json [ "nyplAPI" ] [ "response" ] [ "numResults" ] . to_i > 0 bibl_uuid = json [ "nyplAPI" ] [ "response" ] [ "uuid" ] end return bibl_uuid end | get bibliographic container uuid from an image_id |
22,182 | def get_highreslink ( bibl_uuid , image_id ) url = "#{@server_url}/items/#{bibl_uuid}.json?per_page=500" json = self . get_json ( url ) highreslink = nil json [ "nyplAPI" ] [ "response" ] [ "capture" ] . each do | capture | if capture [ "imageID" ] == image_id highreslink = capture [ "highResLink" ] break end end if json [ "nyplAPI" ] [ "response" ] [ "numResults" ] . to_i > 0 return highreslink end | get highreslink from an item matching up the image idi since some bibliographic items may have many maps under them |
22,183 | def assign_attributes ( new_attributes = { } , options = { } ) return if new_attributes . blank? attributes = new_attributes . stringify_keys multi_parameter_attributes = [ ] nested_parameter_attributes = [ ] attributes . each do | k , v | if k . include? ( "(" ) multi_parameter_attributes << [ k , v ] elsif respond_to? ( "#{k}=" ) if v . is_a? ( Hash ) nested_parameter_attributes << [ k , v ] else send ( "#{k}=" , v ) end else raise UnknownAttributeError , "unknown attribute: #{k}" end end nested_parameter_attributes . each do | k , v | send ( "#{k}=" , v ) end assign_multiparameter_attributes ( multi_parameter_attributes ) end | Assign attributes from the given hash |
22,184 | def find_by_code ( code ) Twinfield :: Process . new ( @session ) . request ( :process_xml_document , get_dimension_xml ( @company , 'DEB' , { code : code } ) ) . body [ :process_xml_document_response ] [ :process_xml_document_result ] [ :dimension ] end | Find customer by twinfield customer code |
22,185 | def find_by_name ( name ) Twinfield :: Finder . new ( @session ) . search ( Twinfield :: FinderSearch . new ( 'DIM' , name , 0 , 1 , 0 , { office : @company , dimtype : 'DEB' } ) ) . body [ :search_response ] [ :data ] end | Find customer by name |
22,186 | def get_dimension_xml ( office , dimtype , opts = { } ) xml = Builder :: XmlMarkup . new xml = xml . read do xml . type ( 'dimensions' ) xml . office ( office ) xml . dimtype ( dimtype ) xml . code ( opts . fetch ( :code ) { } ) end end | The request for getting all elements in a Twinfield dimension |
22,187 | def express! ( emotion , emotive ) emotion = _emotions_about ( emotive ) . where ( emotion : emotion ) . first_or_initialize begin emotion . tap ( & :save! ) rescue ActiveRecord :: RecordInvalid => e raise InvalidEmotion . new ( e . record ) end end | Express an emotion towards another record |
22,188 | def no_longer_express! ( emotion , emotive ) _emotions_about ( emotive ) . where ( emotion : emotion ) . first . tap { | e | e . try ( :destroy ) } end | No longer express an emotion towards another record |
22,189 | def add_entry ( e ) @entries . push ( e ) if @md5_to_entries . has_key? ( e . md5 ) @md5_to_entries [ e . md5 ] . push ( e ) else @md5_to_entries [ e . md5 ] = [ e ] end end | add entry to this catalog |
22,190 | def parse_title ( title ) strip = title . split ( ':' ) . first title = title . gsub ( strip , '' ) title = title [ 2 .. - 1 ] if title [ 0 .. 1 ] == ": " title end | Parse the title from a Favstar RSS title . |
22,191 | def create_queue ( name , attributes = { } ) response = action ( "CreateQueue" , { "QueueName" => Queue . sanitize_name ( "#{queue_prefix}#{name}" ) } . merge ( attributes ) ) if response . success? Queue . new ( self , response . doc . xpath ( "//QueueUrl" ) . text ) else raise "Could not create queue #{name}" end rescue AwsActionError => error if error . code == "AWS.SimpleQueueService.QueueDeletedRecently" raise QueueDeletedRecentlyError , error . message else raise error end end | Creates a new SQS queue and returns a Queue object . |
22,192 | def get_queue ( name , options = { } ) response = action ( "GetQueueUrl" , { "QueueName" => Queue . sanitize_name ( "#{queue_prefix}#{name}" ) } . merge ( options ) ) if response . success? Queue . new ( self , response . doc . xpath ( "//QueueUrl" ) . text ) end rescue Bisques :: AwsActionError => e raise unless e . code == "AWS.SimpleQueueService.NonExistentQueue" end | Get an SQS queue by name . |
22,193 | def list_queues ( prefix = "" ) response = action ( "ListQueues" , "QueueNamePrefix" => "#{queue_prefix}#{prefix}" ) response . doc . xpath ( "//ListQueuesResult/QueueUrl" ) . map ( & :text ) . map do | url | Queue . new ( self , url ) end end | Return an array of Queue objects representing the queues found in SQS . An optional prefix can be supplied to restrict the queues found . This prefix is additional to the client prefix . |
22,194 | def send_message ( queue_url , message_body , delay_seconds = nil ) options = { "MessageBody" => message_body } options [ "DelaySeconds" ] = delay_seconds if delay_seconds tries = 0 md5 = Digest :: MD5 . hexdigest ( message_body ) begin tries += 1 response = action ( "SendMessage" , queue_url , options ) returned_md5 = response . doc . xpath ( "//MD5OfMessageBody" ) . text raise MessageHasWrongMd5Error . new ( message_body , md5 , returned_md5 ) unless md5 == returned_md5 rescue MessageHasWrongMd5Error if tries < 2 retry else raise end end end | Put a message on a queue . Takes the queue url and the message body which should be a string . An optional delay seconds argument can be added if the message should not become visible immediately . |
22,195 | def externalIP ( ) joinThread ( ) external_ip = getCString ( ) r = MiniUPnP . UPNP_GetExternalIPAddress ( @urls . controlURL , @data . servicetype , external_ip ) if r != 0 then raise UPnPException . new , "Error while retriving the external ip address. #{code2error(r)}." end return external_ip . rstrip ( ) end | Returns the external network ip |
22,196 | def status ( ) joinThread ( ) lastconnerror = getCString ( ) status = getCString ( ) uptime = 0 begin uptime_uint = MiniUPnP . new_uintp ( ) r = MiniUPnP . UPNP_GetStatusInfo ( @urls . controlURL , @data . servicetype , status , uptime_uint , lastconnerror ) if r != 0 then raise UPnPException . new , "Error while retriving status info. #{code2error(r)}." end uptime = MiniUPnP . uintp_value ( uptime_uint ) rescue raise ensure MiniUPnP . delete_uintp ( uptime_uint ) end return status . rstrip , lastconnerror . rstrip , uptime end | Returns the status of the router which is an array of 3 elements . Connection status Last error Uptime . |
22,197 | def connectionType ( ) joinThread ( ) type = getCString ( ) if MiniUPnP . UPNP_GetConnectionTypeInfo ( @urls . controlURL , @data . servicetype , type ) != 0 then raise UPnPException . new , "Error while retriving connection info." end type . rstrip end | Router connection information |
22,198 | def totalBytesSent ( ) joinThread ( ) v = MiniUPnP . UPNP_GetTotalBytesSent ( @urls . controlURL_CIF , @data . servicetype_CIF ) if v < 0 then raise UPnPException . new , "Error while retriving total bytes sent." end return v end | Total bytes sent from the router to external network |
22,199 | def totalBytesReceived ( ) joinThread ( ) v = MiniUPnP . UPNP_GetTotalBytesReceived ( @urls . controlURL_CIF , @data . servicetype_CIF ) if v < 0 then raise UPnPException . new , "Error while retriving total bytes received." end return v end | Total bytes received from the external network . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.