idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
23,000
def count_expected count = @expected . inject ( 0 ) do | n , exp | case exp . first when :list return [ n , true ] unless exp [ 3 ] n + exp [ 3 ] else n + 1 end end [ count , false ] end
Count the number of arguments expected to be supplied .
23,001
def parse_list! ( type , sym , count ) args = if count @args . shift count else @args end @results [ sym ] = Parser . parse_list type , args end
Parse a one or more expected arguments of a given type and add them to the results .
23,002
def getReservation response = conncetion . post do | req | req . url "res" , options end return_error_or_body ( response , response . body ) end
Book a Reservation
23,003
def getAlternateProperties response = conncetion . get do | req | req . url "altProps" , options end return_error_or_body ( response , response . body ) end
Request Alternate Properties
23,004
def index @sessions = Gricer . config . session_model . browsers . between_dates ( @stat_from , @stat_thru ) @requests = Gricer . config . request_model . browsers . between_dates ( @stat_from , @stat_thru ) end
This action renders the frame for the statistics tool
23,005
def overview @sessions = Gricer . config . session_model . browsers . between_dates ( @stat_from , @stat_thru ) @requests = Gricer . config . request_model . browsers . between_dates ( @stat_from , @stat_thru ) render partial : 'overview' , formats : [ :html ] , locals : { sessions : @sessions , requests : @requests } end
This action renderes the overview of some data in the statistics tool
23,006
def [] ( key ) if self . map? && @data . has_key? ( key ) @data [ key ] elsif ( self . map? && @data . has_value? ( key ) ) || ( self . list? && @data . include? ( key ) ) key else nil end end
lookup collection value by a key
23,007
def key ( value ) if self . map? && @data . has_value? ( value ) @data . invert [ value ] elsif ( self . map? && @data . has_key? ( value ) ) || ( self . list? && @data . include? ( value ) ) value else nil end end
lookup collection key by a value
23,008
def initialize_bindings bindings = self . class . get_class_bindings bindings . each do | binding | binding [ :proc ] . observed_properties . each do | key_path | register_observer ( self , key_path ) do new_value = binding [ :proc ] . call ( self ) if binding [ :name ] self . setValue ( new_value , forKey : binding [ :name ] ) end end end end end
Create the bindings for the computed properties and observers
23,009
def add_entry ( id , title , updated , link , options = { } ) entries << { :id => id , :title => title , :updated => updated , :link => link } . merge ( options ) end
Add an entry to the feed
23,010
def machined ( config = { } ) @machined = nil if config . delete ( :reload ) @machined ||= Machined :: Environment . new ( config . reverse_merge ( :skip_bundle => true , :skip_autoloading => true ) ) end
Convenience method for creating a new Machined environment
23,011
def build_context ( logical_path = 'application.js' , options = { } ) pathname = options [ :pathname ] || Pathname . new ( 'assets' ) . join ( logical_path ) . expand_path env = options [ :env ] || machined . assets env . context_class . new env , logical_path , pathname end
Returns a fresh context that can be used to test helpers .
23,012
def machined_cli ( args , silence = true ) capture ( :stdout ) { Machined :: CLI . start args . split ( ' ' ) } end
Runs the CLI with the given args .
23,013
def modify ( file , content = nil ) Pathname . new ( file ) . tap do | file | file . open ( 'w' ) { | f | f . write ( content ) } if content future = Time . now + 60 file . utime future , future end end
Modifies the given file
23,014
def verify ( partial ) unless partial . kind_of? ( Partial ) raise ArgumentError , 'you can only push Osheet::Partial objs to the partial set' end pkey = partial_key ( partial ) self [ pkey ] ||= nil pkey end
verify the partial init and return the key otherwise ArgumentError it up
23,015
def verify ( template ) unless template . kind_of? ( Template ) raise ArgumentError , 'you can only push Osheet::Template objs to the template set' end key = template_key ( template ) self [ key . first ] ||= { } self [ key . first ] [ key . last ] ||= nil key end
verify the template init the key set and return the key string otherwise ArgumentError it up
23,016
def get ( url ) stdin , stdout , stderr , t = Open3 . popen3 ( curl_get_cmd ( url ) ) output = encode_utf8 ( stdout . read ) . strip error = encode_utf8 ( stderr . read ) . strip if ! error . nil? && ! error . empty? if error . include? "SSL" raise FaviconParty :: Curl :: SSLError . new ( error ) elsif error . include? "Couldn't resolve host" raise FaviconParty :: Curl :: DNSError . new ( error ) else raise FaviconParty :: CurlError . new ( error ) end end output end
Encodes output as utf8 - Not for binary http responses
23,017
def exchange_auth_code_for_token ( opts = { } ) unless ( opts [ :params ] && opts [ :params ] [ :code ] ) raise ArgumentError . new ( "You must include an authorization code as a parameter" ) end opts [ :authenticate ] ||= :body code = opts [ :params ] . delete ( :code ) authorization_code . get_token ( code , opts ) end
Makes a request to Plangrade server that will swap your authorization code for an access token
23,018
def dump_soap_options ( options ) @soap_dump = true @soap_dump_log = nil if options [ :directory ] @soap_dump_dir = options [ :directory ] else @soap_dump_log = File . open ( options [ :file ] , "w" ) end @soap_dump_format = false || options [ :format ] @soap_dump_interceptor = options [ :interceptor ] if options [ :interceptor ] end
set the options for the dumping soap message
23,019
def call! ( env ) env [ 'rack.logger' ] = @logger status , headers , body = nil , nil , nil benchmark = Benchmark . measure do status , headers , body = @app . call ( env ) end log_error ( env [ 'deas.error' ] ) env [ 'deas.time_taken' ] = RoundedTime . new ( benchmark . real ) [ status , headers , body ] end
The real Rack call interface . This is the common behavior for both the verbose and summary logging middlewares . It sets rack s logger times the response and returns it as is .
23,020
def call! ( env ) log "===== Received request =====" Rack :: Request . new ( env ) . tap do | request | log " Method: #{request.request_method.inspect}" log " Path: #{request.path.inspect}" end env [ 'deas.logging' ] = Proc . new { | msg | log ( msg ) } status , headers , body = super ( env ) log " Redir: #{headers['Location']}" if headers . key? ( 'Location' ) log "===== Completed in #{env['deas.time_taken']}ms (#{response_display(status)}) =====" [ status , headers , body ] end
This the real Rack call interface . It adds logging before and after super - ing to the common logging behavior .
23,021
def call! ( env ) env [ 'deas.logging' ] = Proc . new { | msg | } status , headers , body = super ( env ) request = Rack :: Request . new ( env ) line_attrs = { 'method' => request . request_method , 'path' => request . path , 'params' => env [ 'deas.params' ] , 'splat' => env [ 'deas.splat' ] , 'time' => env [ 'deas.time_taken' ] , 'status' => status } if env [ 'deas.handler_class' ] line_attrs [ 'handler' ] = env [ 'deas.handler_class' ] . name end if headers . key? ( 'Location' ) line_attrs [ 'redir' ] = headers [ 'Location' ] end log SummaryLine . new ( line_attrs ) [ status , headers , body ] end
This the real Rack call interface . It adds logging after super - ing to the common logging behavior .
23,022
def to_jq_upload { "name" => read_attribute ( :asset_name ) , "size" => asset_size , "url" => asset_url , "thumbnail_url" => asset . thumb ( '80x80#' ) . url , "delete_url" => Wafflemix :: Engine :: routes . url_helpers . admin_asset_path ( :id => id ) , "delete_type" => "DELETE" } end
one convenient method to pass jq_upload the necessary information
23,023
def claim ( task , force = false ) raise UnauthorizedClaimAttempt unless has_role? ( task . role ) release! ( task ) if force task . claim ( claim_token ) end
Attempts to set self as the claimant of the given task . If not authorized to claim the task raises exception . Also bubbles exception from Task when task is already claimed by a different claimant .
23,024
def release ( task , force = false ) return unless task . claimed? raise UnauthorizedReleaseAttempt unless force || task . claimant == claim_token task . release end
If we are the current claimant of the given task release the task . Does nothing if the task is not claimed but raises exception if the task is currently claimed by someone else .
23,025
def validate java_path = ` ` . rstrip raise "You do not have a Java installed, but it is required." if java_path . blank? output_header Blueprint :: CSS_FILES . keys . each do | file_name | css_output_path = File . join ( Blueprint :: BLUEPRINT_ROOT_PATH , file_name ) puts "\n\n Testing #{css_output_path}" puts " Output ============================================================\n\n" @error_count += 1 if ! system ( "#{java_path} -jar '#{Blueprint::VALIDATOR_FILE}' -e '#{css_output_path}'" ) end output_footer end
Validates all three CSS files
23,026
def occurrences_between ( t1 , t2 ) return ( ( start_time < t1 || @start_time >= t2 ) ? [ ] : [ start_time ] ) if @occurrence . nil? @occurrence . occurrences_between ( t1 , t2 ) end
occurrences in [ t1 t2 )
23,027
def destroy response = JSON . parse ( CrateAPI :: Base . call ( "#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:destroy] % ["#{self.id}"]}" , :post ) ) raise CrateDestroyError , response [ "message" ] unless response [ "status" ] != "failure" end
Destroys the given crate object .
23,028
def rename ( name ) response = JSON . parse ( CrateAPI :: Base . call ( "#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:rename] % ["#{self.id}"]}" , :post , { :body => { :name => name } } ) ) raise CrateRenameError , response [ "message" ] unless response [ "status" ] != "failure" end
Renamed the given crate object .
23,029
def add_file ( path ) file = File . new ( path ) response = CrateAPI :: Base . call ( "#{CrateAPI::Base::ITEMS_URL}/#{CrateAPI::Items::ITEM_ACTIONS[:upload]}" , :post , { :body => { :file => file , :crate_id => @id } } ) raise CrateFileAlreadyExistsError , response [ "message" ] unless response [ "status" ] != "failure" end
Add a file to the given crate object .
23,030
def last_modified rails_root_mtime = Time . zone . at ( :: File . new ( "#{Rails.root}" ) . mtime ) timestamps = [ rails_root_mtime , self . updated_at ] timestamps . sort . last end
Return the logical modification time for the element .
23,031
def substitute ( init , value , depth ) if depth > VAR_SUBSTITUTION_MAX_DEPTH raise SystemStackError , "Maximal recursive depth (#{VAR_SUBSTITUTION_MAX_DEPTH}) reached for resolving variable #{init}, reached #{value} before stopping." end original = value . clone value . gsub! ( / / ) do next @appliance_config . variables [ $2 ] if @appliance_config . variables . has_key? ( $2 ) next ENV [ $2 ] unless ENV [ $2 ] . nil? $1 end substitute ( init , value , depth + 1 ) unless original == value end
Replace variables with values . This will occur recursively upto a limited depth if the resolved values themselves contain variables .
23,032
def merge_partitions partitions = { } merge_field ( 'hardware.partitions' ) do | parts | parts . each do | root , partition | if partitions . keys . include? ( root ) partitions [ root ] [ 'size' ] = partition [ 'size' ] if partitions [ root ] [ 'size' ] < partition [ 'size' ] unless partition [ 'type' ] . nil? partitions [ root ] . delete ( 'options' ) if partitions [ root ] [ 'type' ] != partition [ 'type' ] partitions [ root ] [ 'type' ] = partition [ 'type' ] else partitions [ root ] [ 'type' ] = @appliance_config . default_filesystem_type end else partitions [ root ] = { } partitions [ root ] [ 'size' ] = partition [ 'size' ] unless partition [ 'type' ] . nil? partitions [ root ] [ 'type' ] = partition [ 'type' ] else partitions [ root ] [ 'type' ] = @appliance_config . default_filesystem_type end end partitions [ root ] [ 'passphrase' ] = partition [ 'passphrase' ] unless partition [ 'passphrase' ] . nil? partitions [ root ] [ 'options' ] = partition [ 'options' ] unless partition [ 'options' ] . nil? end end partitions [ '/boot' ] = { 'type' => 'ext3' , 'size' => 0.1 } if partitions [ '/boot' ] . nil? and ( @appliance_config . os . name == 'sl' or @appliance_config . os . name == 'centos' or @appliance_config . os . name == 'rhel' ) and @appliance_config . os . version == '5' @appliance_config . hardware . partitions = partitions end
This will merge partitions from multiple appliances .
23,033
def copy_truncate return unless :: File . exist? ( @fn ) FileUtils . concat @fn , @fn_copy @io . truncate 0 if @age FileUtils . touch @age_fn @age_fn_mtime = nil end @roller . roll = true end
Copy the contents of the logfile to another file . Truncate the logfile to zero length . This method will set the roll flag so that all the current logfiles will be rolled along with the copied file .
23,034
def inline_diff ( line , start , ending ) if start != 0 || ending != 0 last = ending + line . length str = line [ 0 ... start ] + '\0' + line [ start ... last ] + '\1' + line [ last ... line . length ] end str || line end
Inserts string formating characters around the section of a string that differs internally from another line so that the Line class can insert the desired formating
23,035
def function ( vec1 , vec2 ) case @func when :linear return normalized_radius ( vec1 , vec2 ) when :cubic_alt return normalized_radius ( vec1 , vec2 ) ** ( 1.5 ) when :thin_plate_splines return 0.0 if radius ( vec1 , vec2 ) == 0.0 return normalized_radius ( vec1 , vec2 ) ** 2.0 * Math . log ( normalized_radius ( vec1 , vec2 ) ) when :thin_plate_splines_alt rnorm = ( ( @r0 . prod . abs ) ** ( 2.0 / @r0 . size ) * ( ( ( vec1 - vec2 ) . square / @r0 . square ) . sum + 1.0 ) ) return rnorm * Math . log ( rnorm ) when :multiquadratic ( @r0 . prod . abs ) ** ( 1.0 / @r0 . size ) * Math . sqrt ( ( ( vec1 - vec2 ) . square / @r0 . square ) . sum + 1.0 ) when :inverse_multiquadratic 1.0 / ( ( @r0 . prod . abs ) ** ( 1.0 / @r0 . size ) * Math . sqrt ( ( ( vec1 - vec2 ) . square / @r0 . square ) . sum + 1.0 ) ) when :cubic ( ( @r0 . prod . abs ) ** ( 2.0 / @r0 . size ) * ( ( ( vec1 - vec2 ) . square / @r0 . square ) . sum + 1.0 ) ) ** ( 1.5 ) else raise ArgumentError . new ( "Bad radial basis function: #{@func}" ) end end
Return the value of the interpolation kernel for the separation between the two given vectors . If linear was chosen this will just be the normalised distance between the two points .
23,036
def eval ( * pars ) raise ArgumentError ( "wrong number of points" ) if pars . size != @dim pars = GSL :: Vector . alloc ( pars ) return @npoints . times . inject ( 0.0 ) do | sum , i | sum + function ( pars , @gridpoints . row ( i ) ) * @weights [ i ] end end
Return the interpolated value for the given parameters .
23,037
def gaussian_smooth_eval ( * vals , sigma_vec ) npix = 7 raise "npix must be odd" if npix % 2 == 0 case vals . size when 2 vals0 = GSL :: Vector . linspace ( vals [ 0 ] - 3.0 * sigma_vec [ 0 ] , vals [ 0 ] + 3.0 * sigma_vec [ 0 ] , npix ) vals1 = GSL :: Vector . linspace ( vals [ 1 ] - 3.0 * sigma_vec [ 1 ] , vals [ 1 ] + 3.0 * sigma_vec [ 1 ] , npix ) mat = GSL :: Matrix . alloc ( vals0 . size , vals1 . size ) for i in 0 ... vals0 . size for j in 0 ... vals1 . size mat [ i , j ] = eval ( vals0 [ i ] , vals1 [ j ] ) end end mat . gaussian_smooth ( * sigma_vec . to_a ) cent = ( npix - 1 ) / 2 return mat [ cent , cent ] else raise 'Not supported for this number of dimensions yet' end end
Evaluate the function
23,038
def graphkit ( * args ) if args . size == 0 conts = @last_contours else conts = contours ( * args ) end graphs = conts . map do | val , cons | unless cons [ 0 ] nil else ( cons . map do | con | contour = con . transpose kit = CodeRunner :: GraphKit . autocreate ( { x : { data : contour [ 0 ] } , y : { data : contour [ 1 ] , title : val . to_s } } ) kit . data [ 0 ] . with = "l" kit end ) . sum end end graphs . compact . reverse . sum end
Create a GraphKit object of the contours .
23,039
def method_missing ( meth , * args , & block ) if ( matches? meth ) self . class . send ( :define_method , meth ) do @csf :: config ( ) :: getStringArray ( meth . to_s . to_java_name ) . to_a end send meth , * args , & block else super end end
Initialize the CSF object with data The method_missing override checks to see if the called method can be evaluated to a key then stores it and calls it if it can . For example . itemType or . authors .
23,040
def set_credentials ( req , creds ) return unless creds if String === creds req . add_field ( 'Cookie' , creds ) elsif creds [ :username ] && creds [ :password ] req . basic_auth ( creds [ :username ] , creds [ :password ] ) end end
Sets credentials on a request object .
23,041
def wait ( flags = 0 ) config . ui . logger . debug { "wait" } config . ui . logger . debug { "forks(#{@forks.inspect})" } return nil if @forks . count <= 0 pid , status = ( Process . wait2 ( - 1 , Process :: WUNTRACED ) rescue nil ) if ! pid . nil? && ! status . nil? && ! ( fork = @forks . select { | f | f [ :pid ] == pid } . first ) . nil? data = nil begin data = Marshal . load ( Zlib :: Inflate . inflate ( Base64 . decode64 ( fork [ :reader ] . read ) . to_s ) ) rescue Zlib :: BufError config . ui . logger . fatal { "Encountered Zlib::BufError when reading child pipe." } end config . ui . logger . debug { "read(#{data.inspect})" } data = process_data ( data ) ! data . nil? and @results . push ( data ) fork [ :reader ] . close fork [ :writer ] . close @forks -= [ fork ] return [ pid , status , data ] end nil end
Wait for a single fork to finish .
23,042
def signal_all ( signal = "KILL" ) signaled = 0 if ( ! @forks . nil? && ( @forks . count > 0 ) ) @forks . each do | fork | begin Process . kill ( signal , fork [ :pid ] ) signaled += 1 rescue nil end end end signaled end
Signals all forks .
23,043
def register ( key , value = nil , & block ) block = lambda { value } if value @actions [ key ] = block end
Register a callable by key .
23,044
def get ( key ) return nil if ! @actions . has_key? ( key ) return @results_cache [ key ] if @results_cache . has_key? ( key ) @results_cache [ key ] = @actions [ key ] . call end
Get an action by the given key .
23,045
def check_file_presence spec . icons . values . each do | path | fail_if_not_exist "Icon" , path end if spec . browser_action fail_if_not_exist "Browser action popup" , spec . browser_action . popup fail_if_not_exist "Browser action icon" , spec . browser_action . icon end if spec . page_action fail_if_not_exist "Page action popup" , spec . page_action . popup fail_if_not_exist "Page action icon" , spec . page_action . icon end if spec . packaged_app fail_if_not_exist "App launch page" , spec . packaged_app . page end spec . content_scripts . each do | content_script | content_script . javascripts . each do | script_path | fail_if_not_exist "Content script javascript" , script_path end content_script . stylesheets . each do | style_path | fail_if_not_exist "Content script style" , style_path end end spec . background_scripts . each do | script_path | fail_if_not_exist "Background script style" , script_path end fail_if_not_exist "Background page" , spec . background_page fail_if_not_exist "Options page" , spec . options_page spec . web_intents . each do | web_intent | fail_if_not_exist "Web intent href" , web_intent . href end spec . nacl_modules . each do | nacl_module | fail_if_not_exist "NaCl module" , nacl_module . path end spec . web_accessible_resources . each do | path | fail_if_not_exist "Web accessible resource" , path end end
Go through the specification checking that files that are pointed to actually exist
23,046
def set ( container , & declarations ) struct = OpenStruct . new declarations . call ( struct ) send ( "#{container}=" , struct . table ) end
Use this method to setup your request s payload and headers .
23,047
def run ( & block ) if block_given? set ( :params , & block ) end if post? and multipart? put_multipart_params_into_body else put_params_into_url end request = RestClient :: Request . execute ( :method => http_method , :url => url , :headers => headers , :payload => body ) self . response = parse_response ( request ) end
Send http request to Viddler API .
23,048
def authenticate begin @backend . transaction ( true ) { raise NotInitializedError . new ( @backend . path . path ) unless @backend [ :user ] && @backend [ :system ] && @backend [ :system ] [ :created ] check_salt! } rescue OpenSSL :: Cipher :: CipherError raise WrongMasterPasswordError end end
Check that the master password is correct . This is done to prevent opening an existing but blank locker with the wrong password .
23,049
def get ( key ) raise BlankKeyError if key . blank? @backend . transaction { timestamp! ( :last_accessed ) value = @backend [ :user ] [ encrypt ( key ) ] raise KeyNotFoundError . new ( key ) unless value EntryMapper . from_json ( decrypt ( value ) ) } end
Return the value stored under key
23,050
def add ( entry_or_key , value = nil ) if value . nil? and entry_or_key . is_a? ( Entry ) entry = entry_or_key else entry = Entry . new ( entry_or_key ) entry . password = value end entry . validate! @backend . transaction { timestamp! ( :last_modified ) @backend [ :user ] [ encrypt ( entry . name ) ] = encrypt ( EntryMapper . to_json ( entry ) ) } end
Store entry or value under key
23,051
def delete ( key ) raise BlankKeyError if key . blank? @backend . transaction { timestamp! ( :last_modified ) old_value = @backend [ :user ] . delete ( encrypt ( key ) ) raise KeyNotFoundError . new ( key ) unless old_value EntryMapper . from_json ( decrypt ( old_value ) ) } end
Delete the value that is stored under key and return it
23,052
def all result = [ ] @backend . transaction ( true ) { @backend [ :user ] . each { | k , v | result << EntryMapper . from_json ( decrypt ( v ) ) } } result end
Return all entries as array
23,053
def change_password! ( new_master_password ) self . class . password_policy . validate! ( new_master_password ) @backend . transaction { copy = { } @backend [ :user ] . each { | k , v | new_key = Encryptor . encrypt ( decrypt ( k ) , :key => new_master_password ) new_val = Encryptor . encrypt ( decrypt ( v ) , :key => new_master_password ) copy [ new_key ] = new_val } @backend [ :user ] = copy @master_password = new_master_password timestamp! ( :last_modified ) @backend [ :system ] [ :salt ] = encrypt ( Random . rand . to_s ) } end
Change the master password to + new_master_password + . Note that we don t take a password confirmation here . This is up to a UI layer .
23,054
def pull_object ( id ) local_object = @factory . with_remote_id ( id ) if local_object @service . set_contexts ( local_object . contexts ) else local_object = @factory . new end local_object . before_pull ( self ) if local_object . respond_to? ( :before_pull ) object_hash = @service . show ( object_name , id ) @service . clear_contexts local_object . _remote_id = object_hash . delete ( 'id' ) fields = configuration . synchronizable_for_pull fields . each do | key | value = object_hash [ key . to_s ] local_object . send ( "#{key}=" , value ) end local_object . after_pull ( self ) if local_object . respond_to? ( :after_pull ) local_object . save end
Pulls object from remote service
23,055
def push_object ( local_object ) object_name = @factory . object_name . to_sym local_object . before_push ( self ) if local_object . respond_to? ( :before_push ) changes = { } fields = configuration . synchronizable_for_push fields . each do | atr | value = local_object . send ( atr ) changes [ atr . to_s ] = value end @service . set_contexts ( local_object . contexts ) if local_object . _remote_id @service . update ( object_name , local_object . _remote_id , changes ) else result = @service . create ( object_name , changes ) if result local_object . _remote_id = result [ 'id' ] fields = configuration . synchronizable_for_pull fields . each do | atr | local_object . write_attribute ( atr , result [ atr . to_s ] ) end local_object . save end end local_object . after_push ( self ) if local_object . respond_to? ( :after_push ) @service . clear_contexts end
Pushes local object to remote services . Er I mean its attributes . Like not object itself . Just attributes .
23,056
def pull_collection @service . set_contexts ( @contexts ) collection = @service . list ( object_name ) @service . clear_contexts collection . each_with_index do | remote_object_hash , index | remote_id = remote_object_hash . delete ( "id" ) local_object = @factory . with_remote_id ( remote_id ) unless local_object local_object = @factory . new local_object . update_remote_id ( remote_id ) end local_object . before_pull ( self ) if local_object . respond_to? ( :before_pull ) local_object . _collection_order = index fields = configuration . synchronizable_for_pull fields . each do | field | value = remote_object_hash [ field . to_s ] local_object . send ( "#{field}=" , value ) end local_object . after_pull ( self ) if local_object . respond_to? ( :after_pull ) local_object . save end collection . count end
Pulls whole remote collection . If it cannot find matching local object it will create one . This method is slow useful for initial import not for regular updates . For regular updates only changed remote objects should be updates using pull_object
23,057
def xml ( t ) t . campaignId campaign . id t . name name t . status "ENABLED" @bids . to_xml ( t ) if @bids end
Build xml into Builder
23,058
def keyword ( text = nil , match = nil , & block ) biddable_criterion = BiddableAdGroupCriterion . new ( self ) criterion = CriterionKeyword . new ( self , text , match , & block ) biddable_criterion . criterion = criterion @criterions ||= [ ] @criterions . push ( biddable_criterion ) biddable_criterion end
instantiate an BiddableAdGroupCriterion but it is called keyword for convenience
23,059
def ad_param ( criterion , index = nil , text = nil , & block ) ad_param = AdParam . new ( self , criterion , index , text , & block ) ad_param . save unless inside_initialize? or criterion . inside_initialize? @ad_params ||= [ ] @ad_params . push ( ad_param ) ad_param end
ad param management
23,060
def add_bookmark ( title , href , attributes = { } , & block ) attributes = attributes . merge :title => title , :href => href add_child build ( :bookmark , attributes , & block ) end
Builds a bookmark with given attributes and add it .
23,061
def add_folder ( title , attributes = { } , & block ) attributes = attributes . merge :title => title add_child build ( :folder , attributes , & block ) end
Builds a folder with given attributes and add it .
23,062
def add_alias ( ref ) node = Nokogiri :: XML :: Node . new 'alias' , document node . ref = ( Entry === ref ) ? ref . id : ref . to_s add_child node end
Builds an alias with given attributes and add it .
23,063
def generate ( * args ) init_vars ( options ) controller = args . shift actions = args if controller sanitize ( controller , actions , options ) else puts "Please provide a controller name." exit end end
end to end tests
23,064
def new_artifact_content name , options = { } , & block type = get_type ( options ) content = extract_content type , options , & block %Q{class #{marker(name, type)} #{content}end} end
def new_artifact_content name type content = nil &block
23,065
def json @json ||= begin JSON . parse ( osc_message . to_a . first ) rescue => ex puts ex . message { } end end
Actually perform the message unpacking
23,066
def glpk_type ( type ) case type when :integer GLPK :: GLP_IV when :binary GLPK :: GLP_BV when :continuous GLPK :: GLP_CV else fail type end end
Get the constant GLPK uses to represent our variable types
23,067
def listUsage ( * args ) options = args . last . is_a? ( Hash ) ? args . pop : { } get ( 'applications/listUsage' , options ) end
Returns the API usage per day for this application .
23,068
def auth ( email , pass ) json = secure_web_method_call ( { :method => 'smugmug.login.withPassword' , :EmailAddress => email , :Password => pass } ) self . session . id = json [ "login" ] [ "session" ] [ "id" ] json end
Login to SmugMug using a specific user account .
23,069
def find_chapter ( slug ) chapters . find { | c | c . slug . to_s == slug . to_s } end
Tries to find chapter in this course by chapter slug .
23,070
def parse tags = [ ] while tokens = @tokenizer . read_line_tokens ( ) if tokens . last . type == :START_BLOCK tag = construct_tag ( tokens [ 0 ... - 1 ] ) add_children ( tag ) tags << tag elsif tokens . first . type == :END_BLOCK parse_error ( "No opening block ({) for close block (})." , tokens . first . line , tokens . first . position ) else tags << construct_tag ( tokens ) end end @tokenizer . close ( ) return tags end
Creates an SDL parser on the specified + IO + .
23,071
def add_children ( parent ) while tokens = @tokenizer . read_line_tokens ( ) if tokens . first . type == :END_BLOCK return elsif tokens . last . type == :START_BLOCK tag = construct_tag ( tokens [ 0 ... - 1 ] ) ; add_children ( tag ) parent . add_child ( tag ) else parent . add_child ( construct_tag ( tokens ) ) end end parse_error ( "No close block (})." , @tokenizer . line_no , UNKNOWN_POSITION ) end
Parses the children tags of + parent + until an end of block is found .
23,072
def combine ( date , time_span_with_zone ) time_zone_offset = time_span_with_zone . time_zone_offset time_zone_offset = TimeSpanWithZone . default_time_zone_offset if time_zone_offset . nil? new_date_time ( date . year , date . month , date . day , time_span_with_zone . hour , time_span_with_zone . min , time_span_with_zone . sec , time_zone_offset ) end
Combines a simple Date with a TimeSpanWithZone to create a DateTime
23,073
def expecting_but_got ( expecting , got , line , position ) @tokenizer . expecting_but_got ( expecting , got , line , position ) end
Close the reader and throw a SdlParseError using the format Was expecting X but got Y .
23,074
def build text = @word . hyphenated? ? remove_dash ( @word . to_s ) : add_dash ( @word . to_s ) Word . new ( text ) end
Builds the complementary word .
23,075
def initialize_from_hash ( hsh ) hsh . first . each_pair do | k , v | if self . class . members . include? ( k . to_sym ) self . public_send ( "#{k}=" , v ) else raise NameError , "Trying to assign non-existing member #{k}=#{v}" end end end
Entity constructor from a Hash
23,076
def initialize_from_ordered_args ( values ) raise ArgumentError , "wrong number of arguments(#{values.size} for #{self.class.members.size})" if values . size > self . class . members . size values . each_with_index do | v , i | self . public_send ( "#{self.class.members[i]}=" , v ) end end
Entity constructor from ordered params
23,077
def call ( env ) @request = Rack :: Request . new ( env ) xml_response = @xmlrpc_handler . process ( request_body ) [ 200 , { 'Content-Type' => 'text/xml' } , [ xml_response ] ] end
A new instance of Server .
23,078
def duration = ( value ) new_duration = value . to_s . split ( ":" ) . reverse s , m = new_duration self [ :duration ] = ( s . to_i + ( m . to_i * 60 ) ) end
Set the duration
23,079
def provide ( prompt , options = { } ) options . reverse_merge! required : true , default : nil required = options [ :required ] && ! options [ :default ] prompt = "#{defaulted_prompt(prompt, options[:default])}: " if Stairs . configuration . use_defaults && options [ :default ] options [ :default ] else Stairs :: Util :: CLI . collect ( prompt . blue , required : required ) || options [ :default ] end end
Prompt user to provide input
23,080
def env ( name , value ) ENV [ name ] = value if value Stairs . configuration . env_adapter . set name , value else Stairs . configuration . env_adapter . unset name end end
Set or update env var
23,081
def from_dir ( dirname ) unless File . directory? ( dirname ) raise "'#{dirname}' is not a directory or doesn't exists" end @dirname = File . expand_path dirname @ctime = DateTime . now _load_from_dir self end
Build a catalog from a directory
23,082
def from_file ( filename ) unless File . exist? ( filename ) raise DirCatException . new , "'#{filename}' not exists" end dircat_ser = File . open ( filename ) { | f | YAML :: load ( f ) } @dirname = dircat_ser . dirname @ctime = dircat_ser . ctime dircat_ser . entries . each do | entry_ser | add_entry ( Entry . from_ser ( entry_ser ) ) end self end
Load catalog from a file
23,083
def save_to ( file ) if file . kind_of? ( String ) begin File . open ( file , "w" ) do | f | f . puts to_ser . to_yaml end rescue Errno :: ENOENT raise DirCatException . new , "DirCat: cannot write into '#{file}'" , caller end else file . puts to_ser . to_yaml end end
Save serialized catalog to file
23,084
def report dups = duplicates s = "Base dir: #{@dirname}\n" s += "Nr. file: #{size}" if dups . size > 0 s += " (duplicates #{dups.size})" end s += "\nBytes: #{bytes.with_separator}" s end
simple report with essential information about this catalog
23,085
def script_dup r = "require 'fileutils'\n" duplicates . each do | entries | flg_first = true r += "\n" entries . each do | entry | src = File . join ( @dirname , entry . path , entry . name ) if flg_first flg_first = false r += "# FileUtils.mv( \"#{src}\", \"#{Dir.tmpdir}\" )\n" else r += "FileUtils.mv( \"#{src}\", \"#{Dir.tmpdir}\" )\n" end end end r end
return ruby script to eliminate duplicated
23,086
def add ( channel , client ) @lock . synchronize do _remove ( client ) if @clients . include? client and @clients [ client ] != channel debug { "Adding #{client} to #{channel}." } @clients [ client ] = channel @channels [ channel ] = @channels [ channel ] ? @channels [ channel ] + 1 : 1 end end
Creates a new registry . Registers a new client for that channel . Migrates client to new channel if client already exists .
23,087
def _remove ( client ) return unless @clients . include? client channel = @clients . delete ( client ) debug { "Removing #{client} from #{channel}." } @channels [ channel ] -= 1 @channels . delete ( channel ) if @channels [ channel ] . zero? end
Removes client from +
23,088
def system_command ( * command_args ) cmd = Mixlib :: ShellOut . new ( * command_args ) cmd . run_command cmd end
Runs given commands using mixlib - shellout
23,089
def work ( message ) message = JSON . parse ( message ) RenoteDac :: Mailer . enqueue ( message [ 'postmark_data' ] [ 'template' ] , message [ 'postmark_data' ] [ 'address' ] , message [ 'postmark_data' ] [ 'params' ] , message [ 'postmark_data' ] [ 'attachments' ] ) ack! end
work method receives message payload in raw format in our case it is JSON encoded string which we can pass to RecentPosts service without changes
23,090
def update_source ( source , instance ) begin data = instance . fetch publish_data ( source , data ) ensure @after_update_callback . call end rescue Exception => ex puts "Failed to update #{source}: #{ex.message}" puts ex . backtrace @error_callback . call ( ex ) end
Public because the old tests depend on it
23,091
def method_missing ( method_name , * args , & block ) if @object . loaded? || METHODS_WITHOUT_RELOAD . include? ( method_name ) else StorageRoom . log ( "Reloading #{@object['url']} due to #{method_name}" ) @object . reload ( @object [ 'url' ] , @parameters ) end @object . send ( method_name , * args , & block ) end
Forward all method calls to the proxied object reload if necessary
23,092
def tagged_to_same_mainstream_browse_page return [ ] unless content_item . parent @tagged_to_same_mainstream_browse_page ||= content_item . related_links . select do | related_item | related_item . mainstream_browse_pages . map ( & :content_id ) . include? ( content_item . parent . content_id ) end end
This will return related items that are tagged to the same mainstream browse page as the main content item .
23,093
def parents_tagged_to_same_mainstream_browse_page return [ ] unless content_item . parent && content_item . parent . parent common_parent_content_ids = tagged_to_same_mainstream_browse_page . map ( & :content_id ) @parents_tagged_to_same_mainstream_browse_page ||= content_item . related_links . select do | related_item | next if common_parent_content_ids . include? ( related_item . content_id ) related_item . mainstream_browse_pages . map ( & :parent ) . map ( & :content_id ) . include? ( content_item . parent . parent . content_id ) end end
This will return related items whose parents are tagged to the same mainstream browse page as the main content item s parent .
23,094
def tagged_to_different_mainstream_browse_pages all_content_ids = ( tagged_to_same_mainstream_browse_page + parents_tagged_to_same_mainstream_browse_page ) . map ( & :content_id ) @tagged_to_different_mainstream_browse_pages ||= content_item . related_links . reject do | related_item | all_content_ids . include? ( related_item . content_id ) end end
This will return related links that are tagged to mainstream browse pages unrelated to the main content item .
23,095
def render ( template , context = { } ) return nil unless exist? ( template ) path = File . join ( @template_path , template + ".erb" ) layout_context = context . merge ( partial : ERB . new ( File . read ( path ) ) . result ( Yokunai :: RenderContext . new ( context ) . get_binding ) ) ERB . new ( @raw_layout ) . result ( Yokunai :: RenderContext . new ( layout_context ) . get_binding ) end
Render an ERB template with the given name and cache the result for subsequent calls .
23,096
def connection_params ( host , port ) params = { } if ! host . nil? params [ :host ] = host elsif ! Nagios :: Connection . instance . host . nil? params [ :host ] = Nagios :: Connection . instance . host else raise ArgumentError , "You must provide a Nagios host or use Nagios::Connection" end if ! port . nil? params [ :port ] = port elsif ! Nagios :: Connection . instance . port . nil? params [ :port ] = Nagios :: Connection . instance . port else raise ArgumentError , "You must provide a Nagios port or use Nagios::Connection" end return params end
check that we have the Nagios server details
23,097
def concat ( urls ) if ! urls . nil? converted = urls . map { | url | convert_remote_url ( url ) } super ( converted ) else super ( nil ) end end
Appends the elements in other_array to self as standardized URL Hashes
23,098
def replace ( other_array ) if ! other_array . nil? converted = other_array . map { | url | convert_remote_url ( url ) } super ( converted ) else super ( nil ) end end
Replaces the contents of self with the contents of other_array truncating or expanding if necessary . The contents of other_array is converted standardized URL Hashes .
23,099
def request ( new_url , shrinker ) shrinker . url = new_url Typhoeus :: Request . new ( shrinker . api_url , method : shrinker . http_method , body : shrinker . body_parameters ( shrinker . url ) , headers : { 'Content-Type' => shrinker . content_type } ) . run end
Calls URL API