idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
21,200 | def repeat ( nx = 1 , ny = 1 , nz = 1 ) raise "Not a periodic system." if self . lattice_vectors . nil? u = self . copy v1 = self . lattice_vectors [ 0 ] v2 = self . lattice_vectors [ 1 ] v3 = self . lattice_vectors [ 2 ] nx_sign = ( 0 < nx ) ? 1 : - 1 ny_sign = ( 0 < ny ) ? 1 : - 1 nz_sign = ( 0 < nz ) ? 1 : - 1 new_a... | Repeat a unit cell nx ny nz times in the directions of the lattice vectors . Negative values of nx ny or nz results in displacement in the negative direction of the lattice vectors |
21,201 | def format_geometry_in output = "" if self . lattice_vectors output << self . lattice_vectors . collect { | v | "lattice_vector #{v[0]} #{v[1]} #{v[2]}" } . join ( "\n" ) output << "\n" end output << self . atoms . collect { | a | a . format_geometry_in } . join ( "\n" ) output end | Return a string formatted in the Aims geometry . in format . |
21,202 | def format_xyz ( title = "Aims Geoemtry" ) output = self . atoms . size . to_s + "\n" output << "#{title} \n" self . atoms . each { | a | output << [ a . species , a . x . to_s , a . y . to_s , a . z . to_s ] . join ( "\t" ) + "\n" } output end | return a string in xyz format |
21,203 | def delta ( aCell ) raise "Cells do not have the same number of atoms" unless self . atoms . size == aCell . atoms . size pseudo_atoms = [ ] self . atoms . size . times { | i | a1 = self . atoms [ i ] a2 = aCell . atoms [ i ] raise "Species do not match" unless a1 . species == a2 . species a = Atom . new a . species = ... | Find the difference between this cell and another cell Return a cell with Pseudo - Atoms whose positions are really the differences |
21,204 | def has_metadata ( serializer = :metadata , * attributes ) serialize ( serializer , HashWithIndifferentAccess ) if RUBY_VERSION < '1.9' raise "has_metadata serializer must be named ':metadata', this restriction is lifted in Ruby 1.9+" unless serializer == :metadata else if serializer != :metadata define_singleton_metho... | Set up the model for serialization to a HashWithIndifferentAccess . |
21,205 | def queue_input ( data ) sync do if options [ :unbuffered_input ] data = data . chars input_fifo . push * data else input_fifo . push data end end end | Adds input to be sent to the shell . |
21,206 | def subject & block @subject ||= CLIntegracon :: shared_config . subject . dup return @subject if block . nil? instance_exec ( @subject , & block ) end | Get or configure the current subject |
21,207 | def file_tree_spec_context & block @file_tree_spec_context ||= CLIntegracon . shared_config . file_tree_spec_context . dup return @file_tree_spec_context if block . nil? instance_exec ( @file_tree_spec_context , & block ) end | Get or configure the current context for FileTreeSpecs |
21,208 | def acquire_read_lock while ( true ) c = @counter . value raise ResourceLimitError , 'Too many reader threads' if max_readers? ( c ) if waiting_writer? ( c ) @reader_mutex . synchronize do @reader_q . wait ( @reader_mutex ) if waiting_writer? end while ( true ) c = @counter . value if running_writer? ( c ) @reader_mute... | Acquire a read lock . If a write lock has been acquired will block until it is released . Will not block if other read locks have been acquired . |
21,209 | def release_read_lock while ( true ) c = @counter . value if @counter . compare_and_swap ( c , c - 1 ) if waiting_writer? ( c ) && running_readers ( c ) == 1 @writer_mutex . synchronize { @writer_q . signal } end break end end true end | Release a previously acquired read lock . |
21,210 | def acquire_write_lock while ( true ) c = @counter . value raise ResourceLimitError , 'Too many writer threads' if max_writers? ( c ) if c == 0 break if @counter . compare_and_swap ( 0 , RUNNING_WRITER ) elsif @counter . compare_and_swap ( c , c + WAITING_WRITER ) while ( true ) @writer_mutex . synchronize do c = @coun... | Acquire a write lock . Will block and wait for all active readers and writers . |
21,211 | def release_write_lock while ( true ) c = @counter . value if @counter . compare_and_swap ( c , c - RUNNING_WRITER ) @reader_mutex . synchronize { @reader_q . broadcast } if waiting_writers ( c ) > 0 @writer_mutex . synchronize { @writer_q . signal } end break end end true end | Release a previously acquired write lock . |
21,212 | def parameters self . class . parameters . each_with_object ( { } ) do | parameter , hash | hash [ parameter . name ] = send ( parameter . name ) end end | Returns hash of all parameter names and values |
21,213 | def user_for_models_auditor user = case when defined? ( current_user ) current_user when defined? ( current_employee ) current_employee else return end ActiveSupport :: VERSION :: MAJOR >= 4 ? user . try! ( :id ) : user . try ( :id ) rescue NoMethodError user end | Returns the user who is responsible for any changes that occur . By default this calls current_user or current_employee and returns the result . |
21,214 | def info_for_models_auditor { ip : request . remote_ip , user_agent : request . user_agent , controller : self . class . name , action : action_name , path : request . path_info } end | Returns any information about the controller or request that you want ModelsAuditor to store alongside any changes that occur . By default this returns an empty hash . |
21,215 | def verify ( code , attribs = { } ) params = parse_request_params ( attribs . merge ( code : code ) , json_root : json_root ) . merge credentials : api_creds parsed , _ = request ( :post , url + '/verify' , params ) load ( parsed ) errors . empty? ? self : false end | code - required |
21,216 | def fetch_library ( name ) library_script = @server_registry [ 'library' , name ] logger . debug { "#{logname}: Tried to fetch script '#{name}' from the registry and it " + "was #{'not ' if library_script.nil?}found." } raise NameError , "Server cannot find a script named #{name}" if library_script . nil? library_scrip... | Grab the library from the registry server |
21,217 | def assert_access_without_login ( * actions ) user_options = actions . extract_options! options = { } if ( self . constants . include? ( 'ASSERT_ACCESS_OPTIONS' ) ) options . merge! ( self :: ASSERT_ACCESS_OPTIONS ) end options . merge! ( user_options ) actions += options [ :actions ] || [ ] m_key = options [ :model ] ... | I can t imagine a whole lot of use for this one . |
21,218 | def to_json ( state = nil ) state = JSON :: State . for ( state ) unless JSON :: State === state to_a . to_json ( state ) end | Adds JSON serialization to collections . |
21,219 | def export Log . run ( :job_type => "export" , :name => schedule_name , :file => filename , :export_id => id ) do | log | exporter = MysqlExporter . new exporter . export_table self end end | Runs the export process using the required Exporter library |
21,220 | def is_running? return false if state != "exporting" begin Process . getpgid ( exporter_pid ) raise Exceptions :: ExportIgnored . new ( "Ignored" ) rescue Errno :: ESRCH return false end end | Throws ExportIgnored if the job is still running Checks the state of the job using PID and state |
21,221 | def run ( cmd ) ret = { :exit_status => 0 , :stdout => "" , :stderr => "" } port = ssh_args [ :port ] Net :: SSH . start ( host , username , ssh_args ) do | ssh | ssh . open_channel do | ch | if stdin ch . send_data ( stdin ) ch . eof! end if require_pty ch . request_pty do | ch , success | unless success raise "The us... | Run the command on the remote host . |
21,222 | def run_time_or_time_elapsed if self . end_time return Time . at ( self . end_time - self . start_time ) else return Time . at ( Time . now - self . start_time ) end end | Creates run time based on start and end time If there is no end_time returns time between start and now |
21,223 | def extra_label ( index ) return nil if index < 1 || index > 5 txt = send ( "extra_#{index}_label" ) txt = extra_name ( index ) . to_s . humanize . capitalize if txt . blank? txt end | Gets the label for an extra value . |
21,224 | def extra_field_type ( index ) t = extra_type ( index ) . to_s case t when 'password' 'password' when 'integer' , 'float' 'number' when 'boolean' 'checkbox' else if t . downcase . index ( 'in:' ) 'select' else 'text' end end end | Gets the field type for an extra value . |
21,225 | def extra_value ( index , convert = false ) return nil if index < 1 || index > 5 val = send "extra_#{index}_value" if convert case extra_type ( index ) when 'boolean' BarkestCore :: BooleanParser . parse_for_boolean_column ( val ) when 'integer' BarkestCore :: NumberParser . parse_for_int_column ( val ) when 'float' Ba... | Gets an extra value . |
21,226 | def resend_to ( destinations ) if destinations . size > 0 message . smtp_envelope_to = destinations message . sender = envelope_sender message . smtp_envelope_from = envelope_sender message . header [ 'Precedence' ] = 'list' message . header [ 'List-Id' ] = list_id deliver ( message ) end end | Send the same mail as is to all receivers if any . |
21,227 | def receiver_from_received_header if received = message . received received = received . first if received . respond_to? ( :first ) received . info [ / \s \s / , 1 ] end end | Heuristic method to find actual receiver of the message . May return nil if could not determine . |
21,228 | def uri = ( uri ) self [ 'SERVER_NAME' ] = uri . host self [ 'SERVER_PORT' ] = uri . port . to_s self [ 'QUERY_STRING' ] = ( uri . query || "" ) self [ 'PATH_INFO' ] = ( ! uri . path || uri . path . empty? ) ? "/" : uri . path self [ 'rack.url_scheme' ] = uri . scheme self [ 'HTTPS' ] = ( uri . scheme == "https" ? "on"... | Sets uri as Rack wants . |
21,229 | def uri uri = %Q{#{self['rack.url_scheme']}://#{self['SERVER_NAME']}:#{self['SERVER_PORT']}#{self['REQUEST_URI']}} begin URI . parse ( uri ) rescue StandardError => e raise ArgumentError , "Invalid #{uri}" , e . backtrace end end | Returns uri from Rack environment . Throws ArgumentError for invalid uri . |
21,230 | def edit @menu = Menu . find ( params [ :id ] ) add_breadcrumb I18n . t ( "controllers.admin.menus.edit.breadcrumb" , menu_name : @menu . name ) set_title ( I18n . t ( "controllers.admin.menus.edit.title" , menu_name : @menu . name ) ) end | get menu object and display it for editing |
21,231 | def destroy @menu = Menu . find ( params [ :id ] ) @menu . destroy respond_to do | format | format . html { redirect_to admin_menus_path , notice : I18n . t ( "controllers.admin.menus.destroy.flash.success" ) } end end | deletes the whole menu . Although there is a delete button on each menu option this just removes it from the list which is then interpreted when you save the menu as a whole . |
21,232 | def symlink_configs paths = Dir . glob ( "#{shared_path}/config/**/*" ) . select { | p | File . file? ( p ) } paths . each do | src | relative_path = src . gsub ( %r{ } , 'config/' ) dest = "#{release_path}/#{relative_path}" dirname = File . dirname ( dest ) FileUtils . mkdir_p ( dirname ) unless File . exist? ( dirnam... | hook helper methods |
21,233 | def apply_attributes ( attributed_string , start , length , styles ) return unless attributed_string && start && length && styles return unless start >= 0 && length > 0 && styles . length > 0 return unless start + length <= attributed_string . length range = [ start , length ] ATTRIBUTES . each_pair do | method_name , ... | applies styles in a range to the attributed string |
21,234 | def with_transaction_retry ( options = { } ) retry_count = options . fetch ( :retry_count , 4 ) backoff = options . fetch ( :backoff , 0.25 ) exit_on_fail = options . fetch ( :exit_on_fail , false ) exit_on_disconnect = options . fetch ( :exit_on_disconnect , true ) count = 0 exceptions = [ 'ActiveRecord::StatementInva... | Intended to be included in an ActiveRecord model class . |
21,235 | def transaction_with_retry ( txn_options = { } , retry_options = { } ) base_obj = self . respond_to? ( :transaction ) ? self : ActiveRecord :: Base with_transaction_retry ( retry_options ) do base_obj . transaction ( txn_options ) do yield end end end | Execute some code in a DB transaction with retry |
21,236 | def connect_to_unit puts "Connecting to '#{@host}..." begin tcp_client = TCPSocket . new @host , @port @ssl_client = OpenSSL :: SSL :: SSLSocket . new tcp_client , @context @ssl_client . connect rescue Exception => e puts "Could not connect to '#{@host}: #{e}" end end | Initializes the TV class . |
21,237 | def fling_uri ( uri ) send_request RequestMessage . new ( fling_message : Fling . new ( uri : uri ) ) end | Fling a URI to the Google TV connected to this object This is used send the Google Chrome browser to a web page |
21,238 | def send_keycode ( keycode ) send_request RequestMessage . new ( key_event_message : KeyEvent . new ( keycode : keycode , action : Action :: DOWN ) ) send_request RequestMessage . new ( key_event_message : KeyEvent . new ( keycode : keycode , action : Action :: UP ) ) end | Send a keystroke to the Google TV This is used for things like hitting the ENTER key |
21,239 | def send_data ( msg ) send_request RequestMessage . new ( data_message : Data1 . new ( type : "com.google.tv.string" , data : msg ) ) end | Send a string to the Google TV . This is used for things like typing into text boxes . |
21,240 | def move_mouse ( x_delta , y_delta ) send_request RequestMessage . new ( mouse_event_message : MouseEvent . new ( x_delta : x_delta , y_delta : y_delta ) ) end | Move the mouse relative to its current position |
21,241 | def scroll_mouse ( x_amount , y_amount ) send_request RequestMessage . new ( mouse_wheel_message : MouseWheel . new ( x_scroll : x_amount , y_scroll : y_amount ) ) end | Scroll the mouse wheel a certain amount |
21,242 | def send_request ( request ) message = RemoteMessage . new ( request_message : request ) . serialize_to_string message_size = [ message . length ] . pack ( 'N' ) @ssl_client . write ( message_size + message ) end | Send a request to the Google TV and don t wait for a response |
21,243 | def send_message ( msg ) message = msg . serialize_to_string message_size = [ message . length ] . pack ( 'N' ) try_again = true begin data = "" @ssl_client . write ( message_size + message ) @ssl_client . readpartial ( 1000 , data ) rescue if try_again try_again = false connect_to_unit retry else puts "message not sen... | Send a message to the Google TV and return the response |
21,244 | def init_routes puts "Adding the caboose store routes..." filename = File . join ( @app_path , 'config' , 'routes.rb' ) return if ! File . exists? ( filename ) return if ! @force str = "" str << "\t# Catch everything with caboose\n" str << "\tmount CabooseStore::Engine => '/'\n" file = File . open ( filename , 'rb' ) c... | Adds the routes to the host app to point everything to caboose |
21,245 | def errors parsed_errors = XmlSimple . xml_in ( response . response . body ) error_hash = { } parsed_errors [ 'error' ] . each do | e | error_hash [ e [ 'field' ] ] = e [ 'content' ] end return error_hash end | Returns a hash of errors keyed on field name . |
21,246 | def clients ( options = { } ) post ( "/clients" , options ) [ "clients" ] . map { | obj | Hashie :: Mash . new obj } end | The clients method will return a list of all clients and can only be accessed by admins on the subscription . |
21,247 | def projects ( options = { } ) post ( "/projects" , options ) [ "projects" ] . map { | obj | Hashie :: Mash . new obj } end | The projects method will return projects filtered by the parameters provided . Admin can see all projects on the subscription while non - admins can only access the projects they are assigned . |
21,248 | def tasks ( options = { } ) post ( "/tasks" , options ) [ "tasks" ] . map { | obj | Hashie :: Mash . new obj } end | The tasks method will return a list of all the current tasks for a specified project and can only be accessed by admins on the subscription . |
21,249 | def entries ( options = { } ) post ( "/entries" , options ) [ "entries" ] . map { | obj | Hashie :: Mash . new obj } end | The entries method will return a list of all entries that meet the provided criteria . Either a start and end date have to be provided or an updated_at time . The entries will be in the start and end date range or they will be after the updated_at time depending on what criteria is provided . Each of the optional param... |
21,250 | def users ( options = { } ) post ( "/users" , options ) [ 'users' ] . map { | obj | Hashie :: Mash . new obj } end | The users method will return a list of users . |
21,251 | def cache ( key = nil ) key ||= BasicCache . caller_name key = key . to_sym if include? key @store [ key ] . value else value = yield @store [ key ] = TimeCacheItem . new Time . now , value value end end | Return a value from the cache or calculate it and store it Recalculate if the cached value has expired |
21,252 | def include? ( key = nil ) key ||= BasicCache . caller_name key = key . to_sym @store . include? ( key ) && Time . now - @store [ key ] . stamp < @lifetime end | Check if a value is cached and not expired |
21,253 | def prune @store . keys . reject { | k | include? k } . map { | k | clear! ( k ) && k } end | Prune expired keys |
21,254 | def create ( contents , params = { :language => "Plain Text" , :private => false } ) params = params . merge ( { :contents => contents } . merge ( @base_params ) ) self . class . post ( "/paste" , :body => params ) . parsed_response end | Create a new paste . If language isn t provided it defaults to Plain Text . If private isn t provided it defaults to false . |
21,255 | def details ( start : nil , count : nil ) q = { res_id : @id } q [ :start ] = start if start q [ :count ] = count if count results = get ( 'restaurant' , q ) @location ||= Location . new zom_conn , attributes [ "location" ] @city_id ||= @location . city_id results . each do | k , v | if k == 'apikey' next elsif k == 'R... | this doesn t actually give any more detailed info .. |
21,256 | def label_with_small ( f , method , text = nil , options = { } , & block ) if text . is_a? ( Hash ) options = text text = nil end small_text = options . delete ( :small_text ) text = text || options . delete ( :text ) || method . to_s . humanize . capitalize lbl = f . label ( method , text , options , & block ) lbl += ... | Creates a label followed by small text . |
21,257 | def text_form_group ( f , method , options = { } ) gopt , lopt , fopt = split_form_group_options ( options ) lbl = f . label_with_small method , lopt . delete ( :text ) , lopt fld = gopt [ :wrap ] . call ( f . text_field ( method , fopt ) ) form_group lbl , fld , gopt end | Creates a form group including a label and a text field . |
21,258 | def multi_input_form_group ( f , methods , options = { } ) gopt , lopt , fopt = split_form_group_options ( options ) lopt [ :text ] ||= gopt [ :label ] if lopt [ :text ] . blank? lopt [ :text ] = methods . map { | k , _ | k . to_s . humanize } . join ( ', ' ) end lbl = f . label_with_small methods . map { | k , _ | k }... | Creates a form group including a label and a multiple input field . |
21,259 | def checkbox_form_group ( f , method , options = { } ) gopt , lopt , fopt = split_form_group_options ( { class : 'checkbox' , field_class : '' } . merge ( options ) ) if gopt [ :h_align ] gopt [ :class ] = gopt [ :class ] . blank? ? "col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" : "#{gopt[:class]} col-sm... | Creates a form group including a label and a checkbox . |
21,260 | def select_form_group ( f , method , collection , value_method = nil , text_method = nil , options = { } ) gopt , lopt , fopt = split_form_group_options ( { field_include_blank : true } . merge ( options ) ) lbl = f . label_with_small method , lopt . delete ( :text ) , lopt value_method ||= :to_s text_method ||= :to_s ... | Creates a form group including a label and a collection select field . |
21,261 | def generate_node_command ( node_command , command , send_command , description ) node_command . desc description node_command . command command do | generated_command | generated_command . action do | global_options , options , args | environment = get_environment ( options ) info _ ( 'cli.current_environment' ) % { e... | For new and set_role commands |
21,262 | def install_redis_object name , klass , opts raise ArgumentError , "Name is blank" if name . to_s . empty? name = name . to_s . to_sym opts ||= { } redis_objects_order << name redis_objects [ name ] = OpenStruct . new redis_objects [ name ] . name = name redis_objects [ name ] . klass = klass redis_objects [ name ] . o... | Creates an instance method called + name + that returns an instance of the RedisObject + klass + |
21,263 | def install_class_redis_object name , klass , opts raise ArgumentError , "Name is blank" if name . to_s . empty? name = name . to_s . to_sym opts = opts . nil? ? { } : opts . clone opts [ :parent ] = self unless opts . has_key? ( :parent ) class_redis_objects_order << name class_redis_objects [ name ] = OpenStruct . ne... | Creates a class method called + name + that returns an instance of the RedisObject + klass + |
21,264 | def load_or_create idx return from_redis ( idx ) if exists? ( idx ) obj = from_index idx obj . save obj end | Returns an instance based on + idx + otherwise it creates and saves a new instance base on + idx + . See from_index |
21,265 | def rediskey idx , suffix = self . suffix raise RuntimeError , "No index for #{self}" if idx . to_s . empty? idx = Familia . join * idx if Array === idx idx &&= idx . to_s Familia . rediskey ( prefix , idx , suffix ) end | idx can be a value or an Array of values used to create the index . We don t enforce a default suffix ; that s left up to the instance . A nil + suffix + will not be included in the key . |
21,266 | def initialize_redis_objects self . class . redis_objects . each_pair do | name , redis_object_definition | klass , opts = redis_object_definition . klass , redis_object_definition . opts opts = opts . nil? ? { } : opts . clone opts [ :parent ] = self unless opts . has_key? ( :parent ) redis_object = klass . new name ,... | A default initialize method . This will be replaced if a class defines its own initialize method after including Familia . In that case the replacement must call initialize_redis_objects . This needs to be called in the initialize method of any class that includes Familia . |
21,267 | def method_missing ( method , * args , & block ) attribute = ActiveSupport :: Inflector . camelize ( method . to_s , false ) if attribute =~ / / attribute = attribute . chop return super unless self . attributes . include? ( attribute ) self . changed_attributes [ attribute ] = args [ 0 ] self . attributes [ attribute ... | Work with data in the data hash |
21,268 | def bank_holidays @bank_holidays ||= begin holidays = [ new_years_day , mlk_day , washingtons_birthday , memorial_day , independence_day , labor_day , columbus_day , veterans_day , thanksgiving , christmas ] if Date . new ( year + 1 , 1 , 1 ) . saturday? holidays << Date . new ( year , 12 , 31 ) end holidays . freeze e... | Initializes instance from a given year Returns the federal holidays for the given year on the dates they will actually be observed . |
21,269 | def init_fixed_holidays @mlk_day = january . mondays [ 2 ] @washingtons_birthday = february . mondays [ 2 ] @memorial_day = may . mondays . last @labor_day = september . mondays . first @columbus_day = october . mondays [ 1 ] @thanksgiving = november . thursdays [ 3 ] end | These holidays are always fixed |
21,270 | def init_rolled_holidays @new_years_day = roll_nominal ( Date . new ( year , 1 , 1 ) ) @independence_day = roll_nominal ( Date . new ( year , 7 , 4 ) ) @veterans_day = roll_nominal ( Date . new ( year , 11 , 11 ) ) @christmas = roll_nominal ( Date . new ( year , 12 , 25 ) ) end | These holidays are potentially rolled if they come on a weekend . |
21,271 | def upgrade_config_file puts "Old config file found, upgrading..." credentials = File . read ( config_file_path ) . split ( "\n" ) config = { } config [ 'api_key' ] = credentials [ 0 ] config [ 'password' ] = credentials [ 1 ] config [ 'url' ] = credentials [ 2 ] config [ 'secret' ] = prompt "Please enter your API Shar... | Old line - based config file format |
21,272 | def contains? ( object ) key , id = to_key_and_id ( object ) @graph [ key ] . is_a? ( Enumerable ) ? @graph [ key ] . include? ( id ) : @graph [ key ] end | Create a new instance of the object tracker . |
21,273 | def add ( object ) key , id = to_key_and_id ( object ) @graph [ key ] ? @graph [ key ] << id : @graph [ key ] = [ id ] end | Add this object to the object tracker . |
21,274 | def subgraph ( included = nil , & selector ) result = clone result . select_vertices! ( included ) unless included . nil? result . select_vertices! ( & selector ) if block_given? result end | Initialize a new graph optionally preloading it with vertices and edges |
21,275 | def add_vertex ( vertex , name : nil ) name ||= callback ( vertex , :name ) insert_vertex ( vertex , name ) define_currified_methods ( vertex , :vertex ) if @currify callback ( vertex , :added_to_graph , self ) self end | Add a vertex into the graph |
21,276 | def remove_vertex ( vertex ) @vertices [ vertex ] . each do | edge | remove_edge ( edge ) if edge . include? ( vertex ) end delete_vertex ( vertex ) callback ( vertex , :removed_from_graph , self ) end | Remove a vertex from the graph |
21,277 | def add_edge ( * vertices , ** kvargs ) edge = new_edge ( * vertices , mixins : @mixins , ** kvargs ) insert_edge ( edge ) vertices . each { | vertex | callback ( vertex , :edge_added , edge ) } edge end | Add a new edge to the graph |
21,278 | def remove_edge ( edge ) delete_edge ( edge ) edge . each_vertex { | vertex | callback ( vertex , :edge_removed , edge ) } end | Remove an edge from the graph |
21,279 | def disconnect control_request LS_op : :destroy if @stream_connection @processing_thread . join 5 if @processing_thread ensure @stream_connection . disconnect if @stream_connection @processing_thread . exit if @processing_thread @subscriptions . each { | subscription | subscription . after_control_request :stop } @subs... | Disconnects this Lightstreamer session and terminates the session on the server . All worker threads are exited and all subscriptions created during the connected session can no longer be used . |
21,280 | def create_processing_thread @processing_thread = Thread . new do Thread . current . abort_on_exception = true loop { break unless processing_thread_tick @stream_connection . read_line } @processing_thread = @stream_connection = nil end end | Starts the processing thread that reads and processes incoming data from the stream connection . |
21,281 | def process_stream_line ( line ) return if @mutex . synchronize { @subscriptions . any? { | subscription | subscription . process_stream_data line } } return if process_send_message_outcome line warn "Lightstreamer: unprocessed stream data '#{line}'" end | Processes a single line of incoming stream data . This method is always run on the processing thread . |
21,282 | def process_send_message_outcome ( line ) outcome = SendMessageOutcomeMessage . parse line return unless outcome @mutex . synchronize do @callbacks [ :on_message_result ] . each do | callback | callback . call outcome . sequence , outcome . numbers , outcome . error end end true end | Attempts to process the passed line as a send message outcome message . |
21,283 | def vote ( value , voted_by ) mark = Vote . new ( value : value , voted_by_id : voted_by . id , voter_type : voted_by . class . name ) add_vote_mark ( mark ) end | Creates an embedded vote record and updates number of votes and vote value . |
21,284 | def retract ( voted_by ) mark = votes . find_by ( voted_by_id : voted_by . id ) mark && remove_vote_mark ( mark ) end | Removes previously added vote . |
21,285 | def voted_by? ( voted_by ) ! ! votes . find_by ( voted_by_id : voted_by . id ) rescue NoMethodError , Mongoid :: Errors :: DocumentNotFound false end | Indicates whether the document has a vote from particular voter object . |
21,286 | def run ( & block ) sync do raise Shells :: AlreadyRunning if running? self . run_flag = true end begin run_hook :on_before_run debug 'Connecting...' connect debug 'Starting output buffering...' buffer_output debug 'Starting session thread...' self . session_thread = Thread . start ( self ) do | sh | begin begin debug ... | Runs a shell session . |
21,287 | def fast_forward ( dt ) adjusted_dt = dt * @relative_rate @now += adjusted_dt @children . each { | sub_clock | sub_clock . fast_forward ( adjusted_dt ) } end | fast - forward this clock and all children clocks by the given time delta |
21,288 | def schedule ( obj , time = nil ) time ||= now @occurrences [ obj ] = time parent . schedule ( [ :clock , self ] , unscale_time ( time ) ) if parent && @occurrences . min_key == obj end | schedules an occurrence at the given time with the given object defaulting to the current time |
21,289 | def unschedule ( obj ) if @occurrences . has_key? obj last_priority = @occurrences . min_priority obj , time = @occurrences . delete obj if parent && @occurrences . min_priority != last_priority if @occurrences . min_priority parent . schedule ( [ :clock , self ] , unscale_time ( @occurrences . min_priority ) ) else pa... | dequeues the earliest occurrence from this clock or any child clocks . returns nil if it wasn t there or its relative_time otherwise |
21,290 | def attr_search ( * attributes ) options = attributes . last . is_a? ( Hash ) ? attributes . pop : { } type = ( options . fetch ( :type ) { :simple } ) . to_sym accepted_keys = [ :simple ] + self . reflections . keys . map ( & :to_sym ) unless accepted_keys . include? ( type . to_sym ) raise ArgumentError , 'incorect t... | assuming the last attribute could be a hash |
21,291 | def reify_from_row ( row ) self . new . tap do | card | self . attributes . keys . each . with_index do | key , index | card . send ( "#{key}=" , row [ index ] ) end end end | opposite of abstraction is reification i . e . I m getting the raw data of these variables |
21,292 | def exec ( command , options = { } , & block ) raise Shells :: NotRunning unless running? options ||= { } options = { timeout_error : true , get_output : true } . merge ( options ) options = self . options . merge ( options . inject ( { } ) { | m , ( k , v ) | m [ k . to_sym ] = v ; m } ) options [ :retrieve_exit_code ... | Executes a command during the shell session . |
21,293 | def command_output ( command , expect_command = true ) ret = if ( prompt_pos = ( output =~ prompt_match ) ) output [ 0 ... prompt_pos ] else output end if expect_command command_regex = command_match ( command ) result_cmd , _ , result_data = ret . partition ( "\n" ) until result_data . to_s . strip == '' || result_cmd... | Gets the output from a command . |
21,294 | def decrypt ( encrypted_text , password = nil , salt = nil ) password = password . nil? ? Garcon . crypto . password : password salt = salt . nil? ? Garcon . crypto . salt : salt iv_ciphertext = Base64 . decode64 ( encrypted_text ) cipher = new_cipher ( :decrypt , password , salt ) cipher . iv , ciphertext = separate_i... | Decrypt the given string using the salt and password supplied . |
21,295 | def salted_hash ( password ) salt = SecureRandom . random_bytes ( SALT_BYTE_SIZE ) pbkdf2 = OpenSSL :: PKCS5 :: pbkdf2_hmac_sha1 ( password , salt , CRYPTERATIONS , HASH_BYTE_SIZE ) { salt : salt , pbkdf2 : Base64 . encode64 ( pbkdf2 ) } end | Generates a special hash known as a SPASH a PBKDF2 - HMAC - SHA1 Salted Password Hash for safekeeping . |
21,296 | def new_cipher ( direction , password , salt ) cipher = OpenSSL :: Cipher :: Cipher . new ( CIPHER_TYPE ) direction == :encrypt ? cipher . encrypt : cipher . decrypt cipher . key = encrypt_key ( password , salt ) cipher end | A T T E N Z I O N E A R E A P R O T E T T A Create a new cipher machine with its dials set in the given direction . |
21,297 | def combine_iv_ciphertext ( iv , message ) message . force_encoding ( 'BINARY' ) if message . respond_to? ( :force_encoding ) iv . force_encoding ( 'BINARY' ) if iv . respond_to? ( :force_encoding ) iv + message end | Prepend the initialization vector to the encoded message . |
21,298 | def separate_iv_ciphertext ( cipher , iv_ciphertext ) idx = cipher . iv_len [ iv_ciphertext [ 0 .. ( idx - 1 ) ] , iv_ciphertext [ idx .. - 1 ] ] end | Pull the initialization vector from the front of the encoded message . |
21,299 | def encrypt_key ( password , salt ) iterations , length = CRYPTERATIONS , HASH_BYTE_SIZE OpenSSL :: PKCS5 :: pbkdf2_hmac_sha1 ( password , salt , iterations , length ) end | Convert the password into a PBKDF2 - HMAC - SHA1 salted key used for safely encrypting and decrypting all your ciphers strings . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.