idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
4,100 | def clause ( grouped_columns_calculations = nil ) return nil if sorts_by_method? || default_sorting? order = [ ] each do | sort_column , sort_direction | next if constraint_columns . include? sort_column . name sql = grouped_columns_calculations &. dig ( sort_column . name ) || sort_column . sort [ :sql ] next if sql .... | builds an order - by clause |
4,101 | def get_column ( name_or_column ) return name_or_column if name_or_column . is_a? ActiveScaffold :: DataStructures :: Column name_or_column = name_or_column . to_s . split ( '.' ) . last if name_or_column . to_s . include? '.' @columns [ name_or_column ] end | possibly converts the given argument into a column object from |
4,102 | def add ( * args ) args . flatten! args = args . collect ( & :to_sym ) @_inheritable . concat ( args ) args . each { | a | @set << ActiveScaffold :: DataStructures :: Column . new ( a . to_sym , @active_record_class ) unless find_by_name ( a ) } end | the way to add columns to the set . this is primarily useful for virtual columns . note that this also makes columns inheritable |
4,103 | def set_link ( action , options = { } ) if action . is_a? ( ActiveScaffold :: DataStructures :: ActionLink ) || ( action . is_a? Proc ) @link = action else options [ :label ] ||= label options [ :position ] ||= :after unless options . key? ( :position ) options [ :type ] ||= :member @link = ActiveScaffold :: DataStruct... | associate an action_link with this column |
4,104 | def add ( action , options = { } ) link = if action . is_a? ( ActiveScaffold :: DataStructures :: ActionLink ) || action . is_a? ( ActiveScaffold :: DataStructures :: ActionLinks ) action else options [ :type ] ||= default_type if default_type ActiveScaffold :: DataStructures :: ActionLink . new ( action , options ) en... | adds an ActionLink creating one from the arguments if need be |
4,105 | def add_to_group ( link , group_name = nil ) add_to = root add_to = group_name . split ( '.' ) . inject ( root ) { | group , name | group . send ( name ) } if group_name add_to << link unless link . nil? end | adds a link to a specific group groups are represented as a string separated by a dot eg member . crud |
4,106 | def [] ( val ) links = [ ] @set . each do | item | if item . is_a? ( ActiveScaffold :: DataStructures :: ActionLinks ) collected = item [ val ] links << collected unless collected . nil? elsif item . action . to_s == val . to_s links << item end end links . first end | finds an ActionLink by matching the action |
4,107 | def each ( options = { } , & block ) method = options [ :reverse ] ? :reverse_each : :each @set . sort_by ( & :weight ) . send ( method ) do | item | if item . is_a? ( ActiveScaffold :: DataStructures :: ActionLinks ) && ! options [ :groups ] item . each ( options , & block ) elsif options [ :include_set ] yield item ,... | iterates over the links possibly by type |
4,108 | def add_subgroup ( label , & proc ) columns = ActiveScaffold :: DataStructures :: ActionColumns . new columns . label = label columns . action = action columns . configure ( & proc ) exclude columns . collect_columns add columns end | nests a subgroup in the column set |
4,109 | def do_destroy ( record ) record ||= destroy_find_record begin self . successful = record . destroy rescue StandardError => exception flash [ :warning ] = as_ ( :cant_destroy_record , :record => ERB :: Util . h ( record . to_label ) ) self . successful = false logger . warn do "\n\n#{exception.class} (#{exception.messa... | A simple method to handle the actual destroying of a record May be overridden to customize the behavior |
4,110 | def conditions_from_constraints hash_conditions = { } conditions = [ hash_conditions ] active_scaffold_constraints . each do | k , v | column = active_scaffold_config . columns [ k ] if column if params_hash? v far_association = column . association . klass . reflect_on_association ( v . keys . first ) field = far_asso... | Returns search conditions based on the current scaffold constraints . |
4,111 | def condition_from_association_constraint ( association , value ) field = if association . belongs_to? association . foreign_key else association . klass . primary_key end table = association . belongs_to? ? active_scaffold_config . model . table_name : association . table_name value = association . klass . find ( valu... | We do NOT want to use . search_sql . If anything search_sql will refer to a human - searchable value on the associated record . |
4,112 | def apply_constraints_to_record ( record , options = { } ) options [ :allow_autosave ] = false if options [ :allow_autosave ] . nil? constraints = options [ :constraints ] || active_scaffold_constraints config = record . is_a? ( active_scaffold_config . model ) ? active_scaffold_config : active_scaffold_config_for ( re... | Applies constraints to the given record . |
4,113 | def events ( opts = { } ) enums = @rules . map { | r | r . merge ( opts ) . events } Enumerator . new do | y | loop do enum = active_enums ( enums ) . min_by ( & :peek ) or break y << enum . next end end end | Returns an enumerator for iterating over timestamps in the schedule |
4,114 | def advance ( time ) yes , no = @stack . partition { | rule | rule . include? ( time ) } if no . empty? yes . all? { | rule | rule . advance! ( time ) } or return false puts time if ENV [ "DEBUG" ] yield time if block_given? true else no . any? { | rule | rule . continue? ( time ) } end end | Given a time instance advances state of when all recurrence rules on the stack match and yielding time to the block otherwise invokes break? on non - matching rules . |
4,115 | def add_campaign_id ( campaign_id ) fail ( Mailgun :: ParameterError , 'Too many campaigns added to message.' , campaign_id ) if @counters [ :attributes ] [ :campaign_id ] >= Mailgun :: Chains :: MAX_CAMPAIGN_IDS set_multi_complex ( 'o:campaign' , campaign_id ) @counters [ :attributes ] [ :campaign_id ] += 1 end | Add campaign IDs to message . Limit of 3 per message . |
4,116 | def add_tag ( tag ) if @counters [ :attributes ] [ :tag ] >= Mailgun :: Chains :: MAX_TAGS fail Mailgun :: ParameterError , 'Too many tags added to message.' , tag end set_multi_complex ( 'o:tag' , tag ) @counters [ :attributes ] [ :tag ] += 1 end | Add tags to message . Limit of 3 per message . |
4,117 | def header ( name , data ) fail ( Mailgun :: ParameterError , 'Header name for message must be specified' ) if name . to_s . empty? begin jsondata = make_json data set_single ( "h:#{name}" , jsondata ) rescue Mailgun :: ParameterError set_single ( "h:#{name}" , data ) end end | Add custom data to the message . The data should be either a hash or JSON encoded . The custom data will be added as a header to your message . |
4,118 | def bool_lookup ( value ) return 'yes' if %w( true yes yep ) . include? value . to_s . downcase return 'no' if %w( false no nope ) . include? value . to_s . downcase value end | Converts boolean type to string |
4,119 | def send_message rkey = 'recipient-variables' set_multi_simple rkey , JSON . generate ( @recipient_variables ) @message [ rkey ] = @message [ rkey ] . first if @message . key? ( rkey ) response = @client . send_message ( @domain , @message ) . to_h! message_id = response [ 'id' ] . gsub ( / \> \< / , '' ) @message_ids ... | This method initiates a batch send to the API . It formats the recipient variables posts to the API gathers the message IDs then flushes that data to prepare for the next batch . This method implements the Mailgun Client thus an exception will be thrown if a communication error occurs . |
4,120 | def store_recipient_variables ( recipient_type , address , variables ) variables = { id : @counters [ :recipients ] [ recipient_type ] } unless variables @recipient_variables [ address ] = variables end | This method stores recipient variables for each recipient added if variables exist . |
4,121 | def to_yaml YAML . dump ( to_h ) rescue => err raise ParseError . new ( err ) , err end | Return response as Yaml |
4,122 | def deliver! ( mail ) mg_message = Railgun . transform_for_mailgun ( mail ) response = @mg_client . send_message ( @domain , mg_message ) if response . code == 200 then mg_id = response . to_h [ 'id' ] mail . message_id = mg_id end response end | Initialize the Railgun mailer . |
4,123 | def send_message ( working_domain , data ) if test_mode? then Mailgun :: Client . deliveries << data return Response . from_hash ( { :body => '{"id": "test-mode-mail@localhost", "message": "Queued. Thank you."}' , :code => 200 , } ) end case data when Hash data = data . select { | k , v | v != nil } if data . key? ( :m... | Simple Message Sending |
4,124 | def post ( resource_path , data , headers = { } ) response = @http_client [ resource_path ] . post ( data , headers ) Response . new ( response ) rescue => err raise communication_error err end | Generic Mailgun POST Handler |
4,125 | def get ( resource_path , params = nil , accept = '*/*' ) if params response = @http_client [ resource_path ] . get ( params : params , accept : accept ) else response = @http_client [ resource_path ] . get ( accept : accept ) end Response . new ( response ) rescue => err raise communication_error err end | Generic Mailgun GET Handler |
4,126 | def put ( resource_path , data ) response = @http_client [ resource_path ] . put ( data ) Response . new ( response ) rescue => err raise communication_error err end | Generic Mailgun PUT Handler |
4,127 | def delete ( resource_path ) response = @http_client [ resource_path ] . delete Response . new ( response ) rescue => err raise communication_error err end | Generic Mailgun DELETE Handler |
4,128 | def convert_string_to_file ( string ) file = Tempfile . new ( 'MG_TMP_MIME' ) file . write ( string ) file . rewind file end | Converts MIME string to file for easy uploading to API |
4,129 | def communication_error ( e ) return CommunicationError . new ( e . message , e . response ) if e . respond_to? :response CommunicationError . new ( e . message ) end | Raises CommunicationError and stores response in it if present |
4,130 | def get_interfaces pref = facts [ :ansible_default_ipv4 ] && facts [ :ansible_default_ipv4 ] [ 'interface' ] if pref . present? ( facts [ :ansible_interfaces ] - [ pref ] ) . unshift ( pref ) else ansible_interfaces end end | Move ansible s default interface first in the list of interfaces since Foreman picks the first one that is usable . If ansible has no preference otherwise at least sort the list . |
4,131 | def download ( spec , target = nil ) if target . nil? ext = File . extname ( spec [ 'file_name' ] ) base = File . basename ( spec [ 'file_name' ] , ext ) target = Dir :: Tmpname . create ( [ base , ext ] ) { } end File . open ( target , 'wb' ) do | output | retrieve ( spec ) do | chunk , retrieved , total | output . wr... | Constructor Download a file or resource |
4,132 | def retrieve ( options , & block ) expiry_time_value = options . fetch ( 'expires' , nil ) if expiry_time_value expiry_time = Time . parse ( expiry_time_value ) raise ArgumentError , "Download expired at #{expiry_time}" if expiry_time < Time . now end download_options = extract_download_options ( options ) url = downlo... | Retrieve the resource from the storage service |
4,133 | def extract_download_options ( options ) url = options . fetch ( 'url' ) headers = options . fetch ( 'headers' , { } ) || { } file_size_value = options . fetch ( 'file_size' , 0 ) file_size = file_size_value . to_i output = { url : :: Addressable :: URI . parse ( url ) , headers : headers , file_size : file_size } outp... | Extract and parse options used to download a file or resource from an HTTP API |
4,134 | def retrieve_file ( options ) file_uri = options . fetch ( :url ) file_size = options . fetch ( :file_size ) retrieved = 0 File . open ( file_uri . path , 'rb' ) do | f | until f . eof? chunk = f . read ( chunk_size ) retrieved += chunk . length yield ( chunk , retrieved , file_size ) end end end | Retrieve the file from the file system |
4,135 | def retrieve_http ( options ) file_size = options . fetch ( :file_size ) headers = options . fetch ( :headers ) url = options . fetch ( :url ) retrieved = 0 request = Typhoeus :: Request . new ( url . to_s , method : :get , headers : headers ) request . on_headers do | response | raise DownloadError . new ( "#{self.cla... | Retrieve a resource over the HTTP |
4,136 | def get_file_size ( options ) url = options . fetch ( :url ) headers = options . fetch ( :headers ) file_size = options . fetch ( :file_size ) case url . scheme when 'file' File . size ( url . path ) when / / response = Typhoeus . head ( url . to_s , headers : headers ) length_value = response . headers [ 'Content-Leng... | Retrieve the file size |
4,137 | def update_attributes ( attr = { } ) attr . each_pair do | k , v | if v . is_a? ( Array ) || v . is_a? ( Hash ) send ( "#{k}=" , v . dup ) else send ( "#{k}=" , v ) end end end | Create a new empty packet Set packet attributes from a hash of attribute names and values |
4,138 | def to_s header = [ ( ( type_id . to_i & 0x0F ) << 4 ) | ( flags [ 3 ] ? 0x8 : 0x0 ) | ( flags [ 2 ] ? 0x4 : 0x0 ) | ( flags [ 1 ] ? 0x2 : 0x0 ) | ( flags [ 0 ] ? 0x1 : 0x0 ) ] body = encode_body body_length = body . bytesize if body_length > 268_435_455 raise 'Error serialising packet: body is more than 256MB' end loo... | Serialise the packet |
4,139 | def shift_bits ( buffer ) buffer . slice! ( 0 ... 1 ) . unpack ( 'b8' ) . first . split ( '' ) . map { | b | b == '1' } end | Remove 8 bits from the front of buffer |
4,140 | def shift_string ( buffer ) len = shift_short ( buffer ) str = shift_data ( buffer , len ) str . force_encoding ( 'UTF-8' ) end | Remove string from the front of buffer |
4,141 | def key_file = ( * args ) path , passphrase = args . flatten ssl_context . key = OpenSSL :: PKey :: RSA . new ( File . open ( path ) , passphrase ) end | Set a path to a file containing a PEM - format client private key |
4,142 | def key = ( * args ) cert , passphrase = args . flatten ssl_context . key = OpenSSL :: PKey :: RSA . new ( cert , passphrase ) end | Set to a PEM - format client private key |
4,143 | def ca_file = ( path ) ssl_context . ca_file = path ssl_context . verify_mode = OpenSSL :: SSL :: VERIFY_PEER unless path . nil? end | Set a path to a file containing a PEM - format CA certificate and enable peer verification |
4,144 | def set_will ( topic , payload , retain = false , qos = 0 ) self . will_topic = topic self . will_payload = payload self . will_retain = retain self . will_qos = qos end | Set the Will for the client |
4,145 | def connect ( clientid = nil ) @client_id = clientid unless clientid . nil? if @client_id . nil? || @client_id . empty? raise 'Must provide a client_id if clean_session is set to false' unless @clean_session @client_id = MQTT :: Client . generate_client_id if @version == '3.1.0' end raise 'No MQTT server host set when ... | Connect to the MQTT server If a block is given then yield to that block and then disconnect again . |
4,146 | def disconnect ( send_msg = true ) @read_thread . kill if @read_thread && @read_thread . alive? @read_thread = nil return unless connected? if send_msg packet = MQTT :: Packet :: Disconnect . new send_packet ( packet ) end @socket . close unless @socket . nil? @socket = nil end | Disconnect from the MQTT server . If you don t want to say goodbye to the server set send_msg to false . |
4,147 | def publish ( topic , payload = '' , retain = false , qos = 0 ) raise ArgumentError , 'Topic name cannot be nil' if topic . nil? raise ArgumentError , 'Topic name cannot be empty' if topic . empty? packet = MQTT :: Packet :: Publish . new ( :id => next_packet_id , :qos => qos , :retain => retain , :topic => topic , :pa... | Publish a message on a particular topic to the MQTT server . |
4,148 | def get ( topic = nil , options = { } ) if block_given? get_packet ( topic ) do | packet | yield ( packet . topic , packet . payload ) unless packet . retain && options [ :omit_retained ] end else loop do packet = get_packet ( topic ) return packet . topic , packet . payload unless packet . retain && options [ :omit_re... | Return the next message received from the MQTT server . An optional topic can be given to subscribe to . |
4,149 | def get_packet ( topic = nil ) subscribe ( topic ) unless topic . nil? if block_given? loop do packet = @read_queue . pop yield ( packet ) puback_packet ( packet ) if packet . qos > 0 end else packet = @read_queue . pop puback_packet ( packet ) if packet . qos > 0 return packet end end | Return the next packet object received from the MQTT server . An optional topic can be given to subscribe to . |
4,150 | def unsubscribe ( * topics ) topics = topics . first if topics . is_a? ( Enumerable ) && topics . count == 1 packet = MQTT :: Packet :: Unsubscribe . new ( :topics => topics , :id => next_packet_id ) send_packet ( packet ) end | Send a unsubscribe message for one or more topics on the MQTT server |
4,151 | def receive_packet result = IO . select ( [ @socket ] , [ ] , [ ] , SELECT_TIMEOUT ) unless result . nil? packet = MQTT :: Packet . read ( @socket ) handle_packet packet end keep_alive! rescue Exception => exp unless @socket . nil? @socket . close @socket = nil end Thread . current [ :parent ] . raise ( exp ) end | Try to read a packet from the server Also sends keep - alive ping packets . |
4,152 | def receive_connack Timeout . timeout ( @ack_timeout ) do packet = MQTT :: Packet . read ( @socket ) if packet . class != MQTT :: Packet :: Connack raise MQTT :: ProtocolException , "Response wasn't a connection acknowledgement: #{packet.class}" end if packet . return_code != 0x00 @socket . close raise MQTT :: Protocol... | Read and check a connection acknowledgement packet |
4,153 | def send_packet ( data ) raise MQTT :: NotConnectedException unless connected? @write_semaphore . synchronize do @socket . write ( data . to_s ) end end | Send a packet to server |
4,154 | def run loop do Thread . new ( @server . accept ) do | client_socket | logger . info "Accepted client: #{client_socket.peeraddr.join(':')}" server_socket = TCPSocket . new ( @server_host , @server_port ) begin process_packets ( client_socket , server_socket ) rescue Exception => exp logger . error exp . to_s end logger... | Create a new MQTT Proxy instance . |
4,155 | def configure_hosts! ( hosts ) @hosts_queue = Queue . new Array ( hosts ) . each do | host | @hosts_queue . push ( host ) end end | load the hosts into a Queue for thread safety |
4,156 | def opts_from_url ( url ) url = URI . parse ( url ) unless url . is_a? ( URI ) opts_from_non_params ( url ) . merge opts_from_params ( url . query ) rescue URI :: InvalidURIError { } end | merges URI options into opts |
4,157 | def on_complete_match promise . add_observer do | _time , try , _error | Fear :: Try . matcher { | m | yield ( m ) } . call_or_else ( try , & :itself ) end self end | When this future is completed match against result . |
4,158 | def transform ( success , failure ) promise = Promise . new ( @options ) on_complete_match do | m | m . success { | value | promise . success ( success . call ( value ) ) } m . failure { | error | promise . failure ( failure . call ( error ) ) } end promise . to_future end | Creates a new future by applying the + success + function to the successful result of this future or the + failure + function to the failed result . If there is any non - fatal error raised when + success + or + failure + is applied that error will be propagated to the resulting future . |
4,159 | def map ( & block ) promise = Promise . new ( @options ) on_complete do | try | promise . complete! ( try . map ( & block ) ) end promise . to_future end | Creates a new future by applying a block to the successful result of this future . If this future is completed with an error then the new future will also contain this error . |
4,160 | def flat_map promise = Promise . new ( @options ) on_complete_match do | m | m . case ( Fear :: Failure ) { | failure | promise . complete! ( failure ) } m . success do | value | begin yield ( value ) . on_complete { | callback_result | promise . complete! ( callback_result ) } rescue StandardError => error promise . f... | Creates a new future by applying a block to the successful result of this future and returns the result of the function as the new future . If this future is completed with an exception then the new future will also contain this exception . |
4,161 | def zip ( other ) promise = Promise . new ( @options ) on_complete_match do | m | m . success do | value | other . on_complete do | other_try | promise . complete! ( other_try . map { | other_value | [ value , other_value ] } ) end end m . failure do | error | promise . failure! ( error ) end end promise . to_future en... | Zips the values of + self + and + other + future and creates a new future holding the array of their results . |
4,162 | def fallback_to ( fallback ) promise = Promise . new ( @options ) on_complete_match do | m | m . success { | value | promise . complete! ( value ) } m . failure do | error | fallback . on_complete_match do | m2 | m2 . success { | value | promise . complete! ( value ) } m2 . failure { promise . failure! ( error ) } end ... | Creates a new future which holds the result of + self + future if it was completed successfully or if not the result of the + fallback + future if + fallback + is completed successfully . If both futures are failed the resulting future holds the error object of the first future . |
4,163 | def some ( * conditions , & effect ) branch = Fear . case ( Fear :: Some , & GET_METHOD ) . and_then ( Fear . case ( * conditions , & effect ) ) or_else ( branch ) end | Match against Some |
4,164 | def used_images result = content . scan ( / \[ \] \( \/ \/ \d \/ \) / ) image_ids = result . nil? ? nil : result . map { | i | i [ 0 ] . to_i } . uniq image_ids end | Returns array of images used in content |
4,165 | def update_used_images ActionController :: Base . new . expire_fragment ( self ) image_ids = self . used_images if ! image_ids . nil? Picture . where ( id : image_ids ) . each do | picture | picture . update_attributes ( article_id : self . id ) end end end | Finds images used in an articles content and associates each image to the blog article |
4,166 | def refresh_sitemap if self . published if Rails . env == 'production' && ENV [ "CONFIG_FILE" ] SitemapGenerator :: Interpreter . run ( config_file : ENV [ "CONFIG_FILE" ] ) SitemapGenerator :: Sitemap . ping_search_engines end end end | Refreshes the sitemap and pings the search engines |
4,167 | def index respond_to do | format | format . html { @first_page = ( params [ :page ] and params [ :page ] . to_i > 0 ) ? false : true if params [ :tag ] @articles = Lines :: Article . published . tagged_with ( params [ :tag ] ) . page ( params [ :page ] . to_i ) else @articles = Lines :: Article . published . page ( par... | Lists all published articles . Responds to html and atom |
4,168 | def show @first_page = true @article = Lines :: Article . published . find ( params [ :id ] ) @article . teaser = nil unless @article . teaser . present? meta_tags = { title : @article . title , type : 'article' , url : url_for ( @article ) , site_name : SITE_TITLE , } meta_tags [ :image ] = CONFIG [ :host ] + @article... | Shows specific article |
4,169 | def render_teaser ( article , article_counter = 0 ) if article_counter < 0 teaser = article . teaser && article . teaser . present? ? markdown ( article . teaser ) : nil else teaser = article . teaser && article . teaser . present? ? format_code ( article . teaser ) : format_code ( article . content ) end teaser end | Renders the teaser for an article . |
4,170 | def markdown ( text ) renderer = HTMLwithPygments . new ( hard_wrap : true , filter_html : false , with_toc_data : false ) options = { autolink : true , no_intra_emphasis : true , fenced_code_blocks : true , lax_html_blocks : true , tables : true , strikethrough : true , superscript : true , xhtml : true } Redcarpet ::... | Returns formatted and highlighted code fragments |
4,171 | def nav_link ( link_text , link_path ) recognized = Rails . application . routes . recognize_path ( link_path ) class_name = recognized [ :controller ] == params [ :controller ] ? 'active' : '' content_tag ( :li , class : class_name ) do link_to link_text , link_path end end | Returns links in active or inactive state for highlighting current page |
4,172 | def display_article_authors ( article , with_info = false ) authors = article . authors . map { | author | author . gplus_profile . blank? ? author . name : link_to ( author . name , author . gplus_profile ) } . to_sentence ( two_words_connector : " & " , last_word_connector : " & " ) . html_safe if with_info authors +... | Returns HTML with all authors of an article |
4,173 | def render_navbar ( & block ) action_link = get_action_link if ! action_link action_link = CONFIG [ :title_short ] end html = content_tag ( :div , id : 'navbar' ) do content_tag ( :div , class : 'navbar-inner' ) do if current_lines_user content_tag ( :span , class : 'buttons' , & block ) + "<div class='btn-menu'><div c... | Renders the navigation bar for logged in users |
4,174 | def get_action_link if controller_path == 'admin/articles' case action_name when 'index' then t ( 'lines/buttons/all_articles' ) . html_safe when 'new' then t ( 'lines/buttons/new_article' ) . html_safe when 'edit' then t ( 'lines/buttons/edit_article' ) . html_safe when 'show' then t ( 'lines/buttons/preview' ) . html... | Returns site name for actionbar dependend on current site |
4,175 | def create_reset_digest self . reset_token = Lines :: User . generate_token update_attribute ( :reset_digest , Lines :: User . digest ( reset_token ) ) update_attribute ( :reset_sent_at , Time . zone . now ) end | Sets + rest_digest + and + reset_sent_at + for password reset . |
4,176 | def create user = Lines :: User . find_by ( email : params [ :email ] ) if user && user . authenticate ( params [ :password ] ) session [ :user_id ] = user . id redirect_to admin_root_url else flash . now [ :error ] = t ( 'lines.login_error' ) render "new" end end | Authenticate user and create a new session . |
4,177 | def type text , options = { } packet = 0 . chr * 8 packet [ 0 ] = 4 . chr text . split ( / / ) . each do | char | packet [ 7 ] = char [ 0 ] packet [ 1 ] = 1 . chr socket . write packet packet [ 1 ] = 0 . chr socket . write packet end wait options end | this types + text + on the server |
4,178 | def type_string text , options = { } shift_key_down = nil text . each_char do | char | key_to_press = KEY_PRESS_CHARS [ char ] unless key_to_press . nil? key_press key_to_press else key_needs_shift = SHIFTED_CHARS . include? char if shift_key_down . nil? || shift_key_down != key_needs_shift if key_needs_shift key_down ... | This types + text + on the server but it holds the shift key down when necessary . It will also execute key_press for tabs and returns . |
4,179 | def valid_paths ( paths ) paths = GemContent . get_gem_paths ( "veewee-templates" ) valid_paths = paths . collect { | path | if File . exists? ( path ) && File . directory? ( path ) env . logger . info "Path #{path} exists" File . expand_path ( path ) else env . logger . info "Path #{path} does not exist, skipping" nil... | Traverses path to see which exist or not and checks if available |
4,180 | def load_veewee_config ( ) veewee_configurator = self begin filename = @env . config_filepath if File . exists? ( filename ) env . logger . info ( "Loading config file: #{filename}" ) veeweefile = File . read ( filename ) veeweefile [ "Veewee::Config.run" ] = "veewee_configurator.define" instance_eval ( veeweefile ) el... | We put a long name to not clash with any function in the Veewee file itself |
4,181 | def declare ( options ) options . each do | key , value | instance_variable_set ( "@#{key}" . to_sym , options [ key ] ) env . logger . info ( "definition" ) { " - #{key} : #{options[key]}" } end end | This function takes a hash of options and injects them into the definition |
4,182 | def mac_address raise :: Fission :: Error , "VM #{@name} does not exist" unless self . exists? line = File . new ( vmx_path ) . grep ( / / ) if line . nil? return nil end address = line . first . split ( "=" ) [ 1 ] . strip . split ( / \" / ) [ 1 ] return address end | Retrieve the first mac address for a vm This will only retrieve the first auto generate mac address |
4,183 | def ip_address raise :: Fission :: Error , "VM #{@name} does not exist" unless self . exists? unless mac_address . nil? lease = LeasesFile . new ( "/var/db/vmware/vmnet-dhcpd-vmnet8.leases" ) . find_lease_by_mac ( mac_address ) if lease . nil? return nil else return lease . ip end else return nil end end | Retrieve the ip address for a vm . This will only look for dynamically assigned ip address via vmware dhcp |
4,184 | def each ( & block ) definitions = Hash . new env . logger . debug ( "[Definition] Searching #{env.definition_dir} for definitions:" ) subdirs = Dir . glob ( "#{env.definition_dir}/*" ) subdirs . each do | sub | name = File . basename ( sub ) env . logger . debug ( "[Definition] possible definition '#{name}' found" ) b... | Fetch all definitions |
4,185 | def frequest ( on_fiber , & blk ) return capture_exception ( & blk ) unless on_fiber result , cthred = nil , Thread . current EM . schedule { Fiber . new { result = capture_exception ( & blk ) ; cthred . run } . resume } Thread . stop result end | Runs given block on a thread or fiber and returns result . If eventmachine is running on another thread the fiber must be on the same thread hence EM . schedule and the restriction that the given block cannot include rspec matchers . |
4,186 | def bad_params? ( params , required , optional = nil ) required . each { | r | next if params [ r ] reply . json ( 400 , error : 'invalid_request' , error_description : "no #{r} in request" ) return true } return false unless optional params . each { | k , v | next if required . include? ( k ) || optional . include? ( ... | if required and optional arrays are given extra params are an error |
4,187 | def completed? ( str ) str , @prelude = @prelude + str , "" unless @prelude . empty? add_lines ( str ) return unless @state == :body && @body . bytesize >= @content_length @prelude = bslice ( @body , @content_length .. - 1 ) @body = bslice ( @body , 0 .. @content_length ) @state = :init end | adds data to the request returns true if request is complete |
4,188 | def type_to_sql ( type , limit = nil , precision = nil , scale = nil ) return super unless NO_LIMIT_TYPES . include? ( t = type . to_s . downcase . to_sym ) native_type = NATIVE_DATABASE_TYPES [ t ] native_type . is_a? ( Hash ) ? native_type [ :name ] : native_type end | Convert the specified column type to a SQL string . |
4,189 | def default_owner unless defined? @default_owner username = config [ :username ] ? config [ :username ] . to_s : jdbc_connection . meta_data . user_name @default_owner = username . nil? ? nil : username . upcase end @default_owner end | default schema owner |
4,190 | def execute_and_auto_confirm ( sql , name = nil ) begin @connection . execute_update "call qsys.qcmdexc('QSYS/CHGJOB INQMSGRPY(*SYSRPYL)',0000000031.00000)" @connection . execute_update "call qsys.qcmdexc('ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY(''I'')',0000000045.00000)" rescue Exception => e raise "Could not call CH... | holy moly batman! all this to tell AS400 yes i am sure |
4,191 | def table_exists? ( name ) return false unless name schema ? @connection . table_exists? ( name , schema ) : @connection . table_exists? ( name ) end | disable all schemas browsing when default schema is specified |
4,192 | def exec_proc ( proc_name , * variables ) vars = if variables . any? && variables . first . is_a? ( Hash ) variables . first . map { | k , v | "@#{k} = #{quote(v)}" } else variables . map { | v | quote ( v ) } end . join ( ', ' ) sql = "EXEC #{proc_name} #{vars}" . strip log ( sql , 'Execute Procedure' ) do result = @c... | Support for executing a stored procedure . |
4,193 | def exec_query ( sql , name = 'SQL' , binds = [ ] ) sql = to_sql ( sql , binds ) if sql . respond_to? ( :to_sql ) sql = repair_special_columns ( sql ) if prepared_statements? log ( sql , name , binds ) { @connection . execute_query ( sql , binds ) } else log ( sql , name ) { @connection . execute_query ( sql ) } end en... | AR - SQLServer - Adapter naming |
4,194 | def configure_connection self . client_min_messages = config [ :min_messages ] || 'warning' self . schema_search_path = config [ :schema_search_path ] || config [ :schema_order ] set_standard_conforming_strings if ActiveRecord :: Base . default_timezone == :utc execute ( "SET time zone 'UTC'" , 'SCHEMA' ) elsif tz = lo... | Configures the encoding verbosity schema search path and time zone of the connection . This is called on connection . connect and should not be called manually . |
4,195 | def next_migration_number ( dirname ) next_migration_number = current_migration_number ( dirname ) + 1 if ActiveRecord :: Base . timestamped_migrations [ Time . now . utc . strftime ( "%Y%m%d%H%M%S" ) , format ( "%.14d" , next_migration_number ) ] . max else format ( "%.3d" , next_migration_number ) end end | while methods have moved around this has been the implementation since ActiveRecord 3 . 0 |
4,196 | def enabled ( n , options = { } ) health = Diplomat :: Health . new ( @conn ) result = health . node ( n , options ) . select { | check | check [ 'CheckID' ] == '_node_maintenance' } if result . empty? { enabled : false , reason : nil } else { enabled : true , reason : result . first [ 'Notes' ] } end end | Get the maintenance state of a host |
4,197 | def enable ( enable = true , reason = nil , options = { } ) custom_params = [ ] custom_params << use_named_parameter ( 'enable' , enable . to_s ) custom_params << use_named_parameter ( 'reason' , reason ) if reason custom_params << use_named_parameter ( 'dc' , options [ :dc ] ) if options [ :dc ] raw = send_put_request... | Enable or disable maintenance mode . This endpoint only works on the local agent . |
4,198 | def create ( value = nil , options = { } ) custom_params = [ ] custom_params << use_named_parameter ( 'dc' , options [ :dc ] ) if options [ :dc ] data = value . is_a? ( String ) ? value : JSON . generate ( value ) unless value . nil? raw = send_put_request ( @conn , [ '/v1/session/create' ] , options , data , custom_pa... | Create a new session |
4,199 | def destroy ( id , options = { } ) custom_params = [ ] custom_params << use_named_parameter ( 'dc' , options [ :dc ] ) if options [ :dc ] raw = send_put_request ( @conn , [ "/v1/session/destroy/#{id}" ] , options , nil , custom_params ) raw . body end | Destroy a session |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.