idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
7,200
def start_of_month ( year , month_param ) merch_month = get_merch_month_param ( month_param ) retail_calendar . start_of_month ( year , merch_month ) end
The start date of the month
7,201
def end_of_month ( year , month_param ) merch_month = get_merch_month_param ( month_param ) retail_calendar . end_of_month ( year , merch_month ) end
The end date of the month
7,202
def add_to_base ( file ) occurence = file . scan ( / \s \s \n / ) . last . first replacement = occurence + mount_point file . sub! ( occurence , replacement ) end
adding mount point to base class
7,203
def valid? validations = properties_instances . collect do | property_type | if property_type . property . respond_to? ( :valid? ) property_type . property . valid? else true end end validations . all? end
Validate each property_type s property .
7,204
def store_settings ( settings_hash ) settings_hash . each do | key , value | section . public_send "#{key}=" , value end self . settings = section . attributes end
Because the submitted data is always strings send everything through virtus attrs so it gets cast to the correct class .
7,205
def sections_are_all_valid sections . each do | section | unless section . valid? errors . add :base , section . errors . messages [ :base ] end end end
Validate all sections and rebuild the sections array with the instances which now contain error messages
7,206
def url_is_unique if container . is_a? ( Page ) && url . present? url_exists = Ninetails :: Container . where . not ( id : container . id ) . includes ( :current_revision ) . where ( ninetails_revisions : { url : url } ) . exists? errors . add :url , "is already in use" if url_exists end end
Check the url is unique across revisions but only if a container has a matching revision set as its current_revision . Otherwise it d be impossible to change one page s url to a url which was previously used by another page in the past .
7,207
def add ( klass , formatter = nil , & block ) formatter ||= block if formatter . is_a? ( Symbol ) formatter_class_name = "#{formatter.to_s.gsub(/(^|_)([a-z])/){|m| $~[2].upcase}}Formatter" formatter = Formatter . const_get ( formatter_class_name ) . new end @class_formatters [ klass ] = formatter self end
Add a formatter for a class . The formatter can be specified as either an object that responds to the + call + method or as a symbol representing one of the predefined formatters or as a block to the method call .
7,208
def formatter_for ( klass ) while klass != nil do formatter = @class_formatters [ klass ] return formatter if formatter klass = klass . superclass end @_default_formatter end
Find the formatter for a class by looking it up using the class hierarchy .
7,209
def add ( severity , message = nil , progname = nil ) severity = Severity . label_to_level ( severity ) if severity . is_a? ( String ) || severity . is_a? ( Symbol ) return unless severity && severity >= level time = Time . now if message . nil? if block_given? message = yield else message = progname progname = nil end...
Add a message to the log with a given severity . The message can be either passed in the + message + argument or supplied with a block . This method is not normally called . Instead call one of the helper functions + fatal + + error + + warn + + info + or + debug + .
7,210
def set_thread_local_value ( name , value ) values = Thread . current [ name ] unless values values = { } Thread . current [ name ] = values end if value . nil? values . delete ( self ) Thread . current [ name ] = nil if values . empty? else values [ self ] = value end end
Set a local value for a thread tied to this object .
7,211
def push_thread_local_value ( name , value ) save_val = thread_local_value ( name ) set_thread_local_value ( name , value ) begin yield ensure set_thread_local_value ( name , save_val ) end end
Set a local value for a thread tied to this object within a block .
7,212
def open_device ( device , options ) if device . is_a? ( Device ) device elsif device . respond_to? ( :write ) && device . respond_to? ( :flush ) Device :: Writer . new ( device , options ) elsif device == :null Device :: Null . new else device = device . to_s if options [ :roll ] Device :: DateRollingLogFile . new ( d...
Open a logging device .
7,213
def create_flusher_thread ( flush_seconds ) if flush_seconds > 0 begin logger = self Thread . new do loop do begin sleep ( flush_seconds ) logger . flush if Time . now - logger . last_flushed_at >= flush_seconds rescue => e STDERR . puts ( "Error flushing log: #{e.inspect}" ) end end end end end end
Create a thread that will periodically call flush .
7,214
def compile ( template ) template . gsub ( / / ) do | match | position = TEMPLATE_ARGUMENT_ORDER . index ( match ) if position "%#{position + 1}$s" else match end end end
Compile the template string into a value that can be used with sprintf .
7,215
def vm_compute_attributes ( vm ) vm_attrs = vm . attributes . reject { | key , value | [ :config , :vmid ] . include? ( key . to_sym ) || value . to_s . empty? } vm_attrs = set_vm_config_attributes ( vm , vm_attrs ) vm_attrs = set_vm_volumes_attributes ( vm , vm_attrs ) vm_attrs = set_vm_interfaces_attributes ( vm , vm...
used by host . clone
7,216
def timestamp return nil if self . version != 1 gmt_timestamp_100_nanoseconds = 0 gmt_timestamp_100_nanoseconds += ( ( self . time_hi_and_version & 0x0FFF ) << 48 ) gmt_timestamp_100_nanoseconds += ( self . time_mid << 32 ) gmt_timestamp_100_nanoseconds += self . time_low return Time . at ( ( gmt_timestamp_100_nanoseco...
Returns the timestamp used to generate this UUID
7,217
def generate_s result = sprintf ( "%8.8x-%4.4x-%4.4x-%2.2x%2.2x-" , @time_low , @time_mid , @time_hi_and_version , @clock_seq_hi_and_reserved , @clock_seq_low ) ; 6 . times do | i | result << sprintf ( "%2.2x" , @nodes [ i ] ) end return result . downcase end
Generates a string representation for this UUID .
7,218
def process_value ( value ) case value when Hash then self . class . new ( @_agent , value ) when Array then value . map { | v | process_value ( v ) } else value end end
Initializes a Resource with the given data .
7,219
def method_missing ( method , * args ) attr_name , suffix = method . to_s . scan ( / \_ \? \= /i ) . first if suffix == ATTR_SETTER @_metaclass . send ( :attr_accessor , attr_name ) @_fields << attr_name . to_sym send ( method , args . first ) elsif attr_name && @_fields . include? ( attr_name . to_sym ) value = @attrs...
Provides access to a resource s attributes .
7,220
def call ( method , url , data = nil , options = nil ) if NO_BODY . include? ( method ) options ||= data data = nil end options ||= { } url = expand_url ( url , options [ :uri ] ) started = nil res = @conn . send method , url do | req | if data req . body = data . is_a? ( String ) ? data : encode_body ( data ) end if p...
Makes a request through Faraday .
7,221
def process_data ( data ) case data when Hash then Resource . new ( agent , data ) when Array then data . map { | hash | process_data ( hash ) } when nil then nil else data end end
Turns parsed contents from an API response into a Resource or collection of Resources .
7,222
def process_rels links = ( @headers [ "Link" ] || "" ) . split ( ', ' ) . map do | link | href , name = link . match ( / \w / ) . captures [ name . to_sym , Relation . from_link ( @agent , name , :href => href ) ] end Hash [ * links . flatten ] end
Finds link relations from Link response header
7,223
def check_cipher_options ( c_opts ) if @opts [ :max_iter ] < c_opts [ :iter ] raise CipherOptionsError . new ( "Iteration count of #{c_opts[:iter]} exceeds the maximum of #{@opts[:max_iter]}" ) elsif ! ALLOWED_MODES . include? ( c_opts [ :mode ] ) raise CipherOptionsError . new ( "Mode '#{c_opts[:mode]}' not supported"...
Assume the worst
7,224
def encrypt ( data , opts = { } ) salt = generate_salt ( opts [ :salt ] ) setup_cipher ( :encrypt , salt ) e = cipher . update ( data ) + cipher . final e = "Salted__#{salt}#{e}" opts [ :binary ] ? e : Base64 . encode64 ( e ) end
Initialize with the password
7,225
def encrypt ( data , opts = { } ) data = data . to_s enc = @key . public_encrypt ( data ) if opts [ :binary ] enc else Base64 . encode64 ( enc ) end end
Expects a public key at the minumum
7,226
def decrypt ( data , opts = { } ) data = data . to_s raise "No private key set!" unless @key . private? unless opts [ :binary ] data = Base64 . decode64 ( data ) end @key . private_decrypt ( data ) end
Decrypt data using the key
7,227
def acts_as_api class_eval do include ActsAsApi :: Base :: InstanceMethods extend ActsAsApi :: Base :: ClassMethods end if block_given? yield ActsAsApi :: Config end end
When invoked it enriches the current model with the class and instance methods to act as api .
7,228
def add ( val , options = { } ) item_key = ( options [ :as ] || val ) . to_sym self [ item_key ] = val @options [ item_key ] = options end
Adds a field to the api template
7,229
def allowed_to_render? ( fieldset , field , model , options ) return true unless fieldset . is_a? ActsAsApi :: ApiTemplate fieldset_options = fieldset . options_for ( field ) if fieldset_options [ :unless ] ! ( condition_fulfilled? ( model , fieldset_options [ :unless ] , options ) ) elsif fieldset_options [ :if ] cond...
Decides if the passed item should be added to the response based on the conditional options passed .
7,230
def to_response_hash ( model , fieldset = self , options = { } ) api_output = { } fieldset . each do | field , value | next unless allowed_to_render? ( fieldset , field , model , options ) out = process_value ( model , value , options ) if out . respond_to? ( :as_api_response ) sub_template = api_template_for ( fieldse...
Generates a hash that represents the api response based on this template for the passed model instance .
7,231
def render_for_api ( api_template_or_options , render_options ) if api_template_or_options . is_a? ( Hash ) api_template = [ ] api_template << api_template_or_options . delete ( :prefix ) api_template << api_template_or_options . delete ( :template ) api_template << api_template_or_options . delete ( :postfix ) api_tem...
Provides an alternative to the + render + method used within the controller to simply generate API outputs .
7,232
def as_api_response ( api_template , options = { } ) collect do | item | if item . respond_to? ( :as_api_response ) item . as_api_response ( api_template , options ) else item end end end
The collection checks all its items if they respond to the + as_api_response + method . If they do the result of this method will be collected . If they don t the item itself will be collected .
7,233
def condition ( proc ) return unless block_given? @template . add_node Nodes :: Condition . new ( proc , sub_compile ( nil , true ) { yield } ) end
Provide a conditionnal block
7,234
def ensure_configuration_file config = @options [ :config_paths ] return true if File . exists? ( config ) && File . readable? ( config ) puts "Could not find the asset configuration file \"#{config}\"" exit ( 1 ) end
Make sure that we have a readable configuration file . The
7,235
def precache_all ( output_dir = nil , base_url = nil ) output_dir ||= File . join ( Jammit . public_root , Jammit . package_path ) cacheable ( :js , output_dir ) . each { | p | cache ( p , 'js' , pack_javascripts ( p ) , output_dir ) } cacheable ( :css , output_dir ) . each do | p | cache ( p , 'css' , pack_stylesheets...
Creating a new Packager will rebuild the list of assets from the Jammit . configuration . When assets . yml is being changed on the fly create a new Packager . Ask the packager to precache all defined assets along with their gzip d versions . In order to prebuild the MHTML stylesheets we need to know the base_url becau...
7,236
def cache ( package , extension , contents , output_dir , suffix = nil , mtime = nil ) FileUtils . mkdir_p ( output_dir ) unless File . exists? ( output_dir ) raise OutputNotWritable , "Jammit doesn't have permission to write to \"#{output_dir}\"" unless File . writable? ( output_dir ) mtime ||= latest_mtime package_fo...
Caches a single prebuilt asset package and gzips it at the highest compression level . Ensures that the modification time of both both variants is identical for web server caching modules as well as MHTML .
7,237
def pack_stylesheets ( package , variant = nil , asset_url = nil ) compressor . compress_css ( package_for ( package , :css ) [ :paths ] , variant , asset_url ) end
Return the compressed contents of a stylesheet package .
7,238
def package_for ( package , extension ) pack = @packages [ extension ] && @packages [ extension ] [ package ] pack || not_found ( package , extension ) end
Look up a package asset list by name raising an exception if the package has gone missing .
7,239
def package parse_request template_ext = Jammit . template_extension . to_sym case @extension when :js render :js => ( @contents = Jammit . packager . pack_javascripts ( @package ) ) when template_ext render :js => ( @contents = Jammit . packager . pack_templates ( @package ) ) when :css render :text => generate_styles...
The package action receives all requests for asset packages that haven t yet been cached . The package will be built cached and gzipped .
7,240
def include_stylesheets ( * packages ) options = packages . extract_options! return html_safe ( individual_stylesheets ( packages , options ) ) unless should_package? disabled = ( options . delete ( :embed_assets ) == false ) || ( options . delete ( :embed_images ) == false ) return html_safe ( packaged_stylesheets ( p...
If embed_assets is turned on writes out links to the Data - URI and MHTML versions of the stylesheet package otherwise the package is regular compressed CSS and in development the stylesheet URLs are passed verbatim .
7,241
def include_javascripts ( * packages ) options = packages . extract_options! options . merge! ( :extname => false ) html_safe packages . map { | pack | should_package? ? Jammit . asset_url ( pack , :js ) : Jammit . packager . individual_urls ( pack . to_sym , :js ) } . flatten . map { | pack | "<script src=\"#{pack}\">...
Writes out the URL to the bundled and compressed javascript package except in development where it references the individual scripts .
7,242
def individual_stylesheets ( packages , options ) tags_with_options ( packages , options ) { | p | Jammit . packager . individual_urls ( p . to_sym , :css ) } end
HTML tags in order for all of the individual stylesheets .
7,243
def packaged_stylesheets ( packages , options ) tags_with_options ( packages , options ) { | p | Jammit . asset_url ( p , :css ) } end
HTML tags for the stylesheet packages .
7,244
def embedded_image_stylesheets ( packages , options ) datauri_tags = tags_with_options ( packages , options ) { | p | Jammit . asset_url ( p , :css , :datauri ) } ie_tags = Jammit . mhtml_enabled ? tags_with_options ( packages , options ) { | p | Jammit . asset_url ( p , :css , :mhtml ) } : packaged_stylesheets ( packa...
HTML tags for the datauri and mhtml versions of the packaged stylesheets using conditional comments to load the correct variant .
7,245
def tags_with_options ( packages , options ) packages . dup . map { | package | yield package } . flatten . map { | package | stylesheet_link_tag package , options } . join ( "\n" ) end
Generate the stylesheet tags for a batch of packages with options by yielding each package to a block .
7,246
def compile_jst ( paths ) namespace = Jammit . template_namespace paths = paths . grep ( Jammit . template_extension_matcher ) . sort base_path = find_base_path ( paths ) compiled = paths . map do | path | contents = read_binary_file ( path ) contents = contents . gsub ( / \r \n / , "\\n" ) . gsub ( "'" , '\\\\\'' ) na...
Compiles a single JST file by writing out a javascript that adds template properties to a top - level template namespace object . Adds a JST - compilation function to the top of the package unless you ve specified your own preferred function or turned it off . JST templates are named with the basename of their file .
7,247
def find_base_path ( paths ) return nil if paths . length <= 1 paths . sort! first = paths . first . split ( '/' ) last = paths . last . split ( '/' ) i = 0 while first [ i ] == last [ i ] && i <= first . length i += 1 end res = first . slice ( 0 , i ) . join ( '/' ) res . empty? ? nil : res end
Given a set of paths find a common prefix path .
7,248
def concatenate_and_tag_assets ( paths , variant = nil ) stylesheets = [ paths ] . flatten . map do | css_path | contents = read_binary_file ( css_path ) contents . gsub ( EMBED_DETECTOR ) do | url | ipath , cpath = Pathname . new ( $1 ) , Pathname . new ( File . expand_path ( css_path ) ) is_url = URI . parse ( $1 ) ....
In order to support embedded assets from relative paths we need to expand the paths before contatenating the CSS together and losing the location of the original stylesheet path . Validate the assets while we re at it .
7,249
def absolute_path ( asset_pathname , css_pathname ) ( asset_pathname . absolute? ? Pathname . new ( File . join ( Jammit . public_root , asset_pathname ) ) : css_pathname . dirname + asset_pathname ) . cleanpath end
Get the site - absolute public path for an asset file path that may or may not be relative given the path of the stylesheet that contains it .
7,250
def rails_asset_id ( path ) asset_id = ENV [ "RAILS_ASSET_ID" ] return asset_id if asset_id File . exists? ( path ) ? File . mtime ( path ) . to_i . to_s : '' end
Similar to the AssetTagHelper s method of the same name this will determine the correct asset id for a file .
7,251
def embeddable? ( asset_path , variant ) font = EMBED_FONTS . include? ( asset_path . extname ) return false unless variant return false unless asset_path . to_s . match ( EMBEDDABLE ) && asset_path . exist? return false unless EMBED_EXTS . include? ( asset_path . extname ) return false unless font || encoded_contents ...
An asset is valid for embedding if it exists is less than 32K and is stored somewhere inside of a folder named embed . IE does not support Data - URIs larger than 32K and you probably shouldn t be embedding assets that large in any case . Because we need to check the base64 length here save it so that we don t have to ...
7,252
def encoded_contents ( asset_path ) return @asset_contents [ asset_path ] if @asset_contents [ asset_path ] data = read_binary_file ( asset_path ) @asset_contents [ asset_path ] = Base64 . encode64 ( data ) . gsub ( / \n / , '' ) end
Return the Base64 - encoded contents of an asset on a single line .
7,253
def say ( text , quick_replies : [ ] , user : @user ) message_options = { recipient : { id : user . id } , message : { text : text } } if quick_replies && ! quick_replies . empty? message_options [ :message ] [ :quick_replies ] = UI :: QuickReplies . build ( * quick_replies ) end send_message ( message_options ) end
abstraction over Bot . deliver to send messages declaratively and directly
7,254
def change_dylib_id ( new_id , options = { } ) raise ArgumentError , "argument must be a String" unless new_id . is_a? ( String ) return unless machos . all? ( & :dylib? ) each_macho ( options ) do | macho | macho . change_dylib_id ( new_id , options ) end repopulate_raw_machos end
Changes the file s dylib ID to new_id . If the file is not a dylib does nothing .
7,255
def change_install_name ( old_name , new_name , options = { } ) each_macho ( options ) do | macho | macho . change_install_name ( old_name , new_name , options ) end repopulate_raw_machos end
Changes all dependent shared library install names from old_name to new_name . In a fat file this changes install names in all internal Mach - Os .
7,256
def change_rpath ( old_path , new_path , options = { } ) each_macho ( options ) do | macho | macho . change_rpath ( old_path , new_path , options ) end repopulate_raw_machos end
Change the runtime path old_path to new_path in the file s Mach - Os .
7,257
def add_rpath ( path , options = { } ) each_macho ( options ) do | macho | macho . add_rpath ( path , options ) end repopulate_raw_machos end
Add the given runtime path to the file s Mach - Os .
7,258
def delete_rpath ( path , options = { } ) each_macho ( options ) do | macho | macho . delete_rpath ( path , options ) end repopulate_raw_machos end
Delete the given runtime path from the file s Mach - Os .
7,259
def populate_fat_header raise TruncatedFileError if @raw_data . size < 8 fh = Headers :: FatHeader . new_from_bin ( :big , @raw_data [ 0 , Headers :: FatHeader . bytesize ] ) raise MagicError , fh . magic unless Utils . magic? ( fh . magic ) raise MachOBinaryError unless Utils . fat_magic? ( fh . magic ) raise JavaClas...
Obtain the fat header from raw file data .
7,260
def populate_fat_archs archs = [ ] fa_klass = Utils . fat_magic32? ( header . magic ) ? Headers :: FatArch : Headers :: FatArch64 fa_off = Headers :: FatHeader . bytesize fa_len = fa_klass . bytesize header . nfat_arch . times do | i | archs << fa_klass . new_from_bin ( :big , @raw_data [ fa_off + ( fa_len * i ) , fa_l...
Obtain an array of fat architectures from raw file data .
7,261
def populate_machos machos = [ ] fat_archs . each do | arch | machos << MachOFile . new_from_bin ( @raw_data [ arch . offset , arch . size ] , ** options ) end machos end
Obtain an array of Mach - O blobs from raw file data .
7,262
def repopulate_raw_machos machos . each_with_index do | macho , i | arch = fat_archs [ i ] @raw_data [ arch . offset , arch . size ] = macho . serialize end end
Repopulate the raw Mach - O data with each internal Mach - O object .
7,263
def each_macho ( options = { } ) strict = options . fetch ( :strict , true ) errors = [ ] machos . each_with_index do | macho , index | begin yield macho rescue RecoverableModificationError => e e . macho_slice = index raise e if strict errors << e end end raise errors . first if errors . size == machos . size end
Yield each Mach - O object in the file rescuing and accumulating errors .
7,264
def insert_command ( offset , lc , options = { } ) context = LoadCommands :: LoadCommand :: SerializationContext . context_for ( self ) cmd_raw = lc . serialize ( context ) fileoff = offset + cmd_raw . bytesize raise OffsetInsertionError , offset if offset < header . class . bytesize || fileoff > low_fileoff new_sizeof...
Inserts a load command at the given offset .
7,265
def replace_command ( old_lc , new_lc ) context = LoadCommands :: LoadCommand :: SerializationContext . context_for ( self ) cmd_raw = new_lc . serialize ( context ) new_sizeofcmds = sizeofcmds + cmd_raw . bytesize - old_lc . cmdsize raise HeaderPadError , @filename if header . class . bytesize + new_sizeofcmds > low_f...
Replace a load command with another command in the Mach - O preserving location .
7,266
def delete_command ( lc , options = { } ) @raw_data . slice! ( lc . view . offset , lc . cmdsize ) update_ncmds ( ncmds - 1 ) update_sizeofcmds ( sizeofcmds - lc . cmdsize ) @raw_data . insert ( header . class . bytesize + sizeofcmds - lc . cmdsize , Utils . nullpad ( lc . cmdsize ) ) populate_fields if options . fetch...
Delete a load command from the Mach - O .
7,267
def segment_alignment return 12 if %i[ i386 x86_64 ppc ppc64 ] . include? ( cputype ) return 14 if %i[ arm arm64 ] . include? ( cputype ) cur_align = Sections :: MAX_SECT_ALIGN segments . each do | segment | if filetype == :object align = magic32? ? 2 : 3 segment . sections . each do | section | align = section . align...
The segment alignment for the Mach - O . Guesses conservatively .
7,268
def change_dylib_id ( new_id , _options = { } ) raise ArgumentError , "new ID must be a String" unless new_id . is_a? ( String ) return unless dylib? old_lc = command ( :LC_ID_DYLIB ) . first raise DylibIdMissingError unless old_lc new_lc = LoadCommands :: LoadCommand . create ( :LC_ID_DYLIB , new_id , old_lc . timesta...
Changes the Mach - O s dylib ID to new_id . Does nothing if not a dylib .
7,269
def change_install_name ( old_name , new_name , _options = { } ) old_lc = dylib_load_commands . find { | d | d . name . to_s == old_name } raise DylibUnknownError , old_name if old_lc . nil? new_lc = LoadCommands :: LoadCommand . create ( old_lc . type , new_name , old_lc . timestamp , old_lc . current_version , old_lc...
Changes the shared library old_name to new_name
7,270
def change_rpath ( old_path , new_path , _options = { } ) old_lc = command ( :LC_RPATH ) . find { | r | r . path . to_s == old_path } raise RpathUnknownError , old_path if old_lc . nil? raise RpathExistsError , new_path if rpaths . include? ( new_path ) new_lc = LoadCommands :: LoadCommand . create ( :LC_RPATH , new_pa...
Changes the runtime path old_path to new_path
7,271
def add_rpath ( path , _options = { } ) raise RpathExistsError , path if rpaths . include? ( path ) rpath_cmd = LoadCommands :: LoadCommand . create ( :LC_RPATH , path ) add_command ( rpath_cmd ) end
Add the given runtime path to the Mach - O .
7,272
def delete_rpath ( path , _options = { } ) rpath_cmds = command ( :LC_RPATH ) . select { | r | r . path . to_s == path } raise RpathUnknownError , path if rpath_cmds . empty? rpath_cmds . reverse_each { | cmd | delete_command ( cmd , :repopulate => false ) } populate_fields end
Delete the given runtime path from the Mach - O .
7,273
def populate_mach_header raise TruncatedFileError if @raw_data . size < 28 magic = populate_and_check_magic mh_klass = Utils . magic32? ( magic ) ? Headers :: MachHeader : Headers :: MachHeader64 mh = mh_klass . new_from_bin ( endianness , @raw_data [ 0 , mh_klass . bytesize ] ) check_cputype ( mh . cputype ) check_cpu...
The file s Mach - O header structure .
7,274
def populate_and_check_magic magic = @raw_data [ 0 .. 3 ] . unpack ( "N" ) . first raise MagicError , magic unless Utils . magic? ( magic ) raise FatBinaryError if Utils . fat_magic? ( magic ) @endianness = Utils . little_magic? ( magic ) ? :little : :big magic end
Read just the file s magic number and check its validity .
7,275
def populate_load_commands permissive = options . fetch ( :permissive , false ) offset = header . class . bytesize load_commands = [ ] header . ncmds . times do fmt = Utils . specialize_format ( "L=" , endianness ) cmd = @raw_data . slice ( offset , 4 ) . unpack ( fmt ) . first cmd_sym = LoadCommands :: LOAD_COMMANDS [...
All load commands in the file .
7,276
def update_ncmds ( ncmds ) fmt = Utils . specialize_format ( "L=" , endianness ) ncmds_raw = [ ncmds ] . pack ( fmt ) @raw_data [ 16 .. 19 ] = ncmds_raw end
Updates the number of load commands in the raw data .
7,277
def update_sizeofcmds ( size ) fmt = Utils . specialize_format ( "L=" , endianness ) size_raw = [ size ] . pack ( fmt ) @raw_data [ 20 .. 23 ] = size_raw end
Updates the size of all load commands in the raw data .
7,278
def number_of_arguments ( method_sexp ) arguments = method_sexp [ 2 ] arguments = arguments [ 1 ] if arguments . first == :paren arguments [ 1 ] == nil ? 0 : arguments [ 1 ] . size end
MOVE to method scanner class
7,279
def execute ( method , path , data = nil , options = { } ) response = request ( method , path , data , options ) case response . code when 200 .. 299 response when 401 raise AuthenticationFailed , response [ "message" ] when 404 raise NotFoundError , response else raise RequestError , response end end
Executes a request validates and returns the response .
7,280
def request ( method , path , data = nil , options = { } ) request_options = request_options ( options ) if data request_options [ :headers ] [ "Content-Type" ] = content_type ( request_options [ :headers ] ) request_options [ :body ] = content_data ( request_options [ :headers ] , data ) end HTTParty . send ( method ,...
Make a HTTP request .
7,281
def remote_addr if respond_to? ( :remote_ip ) __send__ ( :remote_ip ) elsif respond_to? ( :ip ) __send__ ( :ip ) else if env [ 'HTTP_X_FORWARDED_FOR' ] env [ 'HTTP_X_FORWARDED_FOR' ] . split ( ',' ) . pop else env [ 'REMOTE_ADDR' ] end end end
for reverse proxy .
7,282
def variants return @_variants if @_variants @_variants = self . class . ancestors . select { | c | c . to_s =~ / / && c . to_s !~ / / } . map do | klass | klass = klass . to_s . gsub ( / / , '' ) . gsub ( / / , '' ) . gsub ( / / , 'smart_phone' ) . gsub ( / / , 'tablet' ) . gsub ( / / , '_' ) . gsub ( / / , '\1_\2' ) ...
for view selector
7,283
def validate_answer ( answer ) if rules [ :presence ] == "1" answer . validates_presence_of :answer_text end if rules [ :minimum ] . present? || rules [ :maximum ] . present? min_max = { minimum : rules [ :minimum ] . to_i } min_max [ :maximum ] = rules [ :maximum ] . to_i if rules [ :maximum ] . present? answer . vali...
answer will delegate its validation to question and question will inturn add validations on answer on the fly!
7,284
def replace_sections ( diary ) return if diary . nil? or ! diary . categorizable? categorized = categorize_diary ( diary ) categories = restore_categories deleted = [ ] ymd = diary . date . strftime ( '%Y%m%d' ) @plugin . __send__ ( :transaction , 'category' ) do | db | categories . each do | c | cat = get ( db , c ) |...
cache each section of diary used in update_proc
7,285
def categorize ( category , years ) categories = category - [ 'ALL' ] if categories . empty? categories = restore_categories else categories &= restore_categories end categorized = { } begin categorized . clear categories . each do | c | @plugin . __send__ ( :transaction , 'category' ) do | db | categorized [ c ] = get...
categorize sections of category of years
7,286
def categorize_diary ( diary ) categorized = { } ymd = diary . date . strftime ( '%Y%m%d' ) idx = 1 diary . each_section do | s | shorten = begin body = %Q|apply_plugin(#{s.body_to_html.dump}, true)| @conf . shorten ( eval ( body , @binding ) ) rescue NameError "" end s . categories . each do | c | categorized [ c ] = ...
categorize sections of diary
7,287
def dispatch_cgi ( request , cgi ) result = @target . run ( request , cgi ) result . headers . reject! { | k , v | k . to_s . downcase == "status" } result . to_a end
FIXME rename method name to more suitable one .
7,288
def fake_stdin_as_params stdin_spy = StringIO . new if $RACK_ENV && $RACK_ENV [ 'rack.input' ] stdin_spy . print ( $RACK_ENV [ 'rack.input' ] . read ) stdin_spy . rewind end $stdin = stdin_spy end
FIXME dirty hack
7,289
def load_cgi_conf def_vars1 = '' def_vars2 = '' [ :tdiary_version , :html_title , :author_name , :author_mail , :index_page , :hour_offset , :description , :icon , :banner , :x_frame_options , :header , :footer , :section_anchor , :comment_anchor , :date_format , :latest_limit , :show_nyear , :theme , :css , :show_comm...
loading tdiary . conf in
7,290
def configure_attrs @options = { } eval ( File :: open ( 'tdiary.conf' ) { | f | f . read } , nil , "(tdiary.conf)" , 1 ) @lang = 'ja' unless @lang begin instance_eval ( File :: open ( "#{TDiary::PATH}/tdiary/lang/#{@lang}.rb" ) { | f | f . read } , "(tdiary/lang/#{@lang}.rb)" , 1 ) rescue Errno :: ENOENT @lang = 'ja' ...
loading tdiary . conf in current directory
7,291
def close! ( controller ) self . each_with_rescue ( @@klasses ) { | klass | klass . close! ( controller ) } self . each_with_rescue ( Footnotes . after_hooks ) { | hook | hook . call ( controller , self ) } end
Calls the class method close! in each note Sometimes notes need to finish their work even after being read This method allows this kind of work
7,292
def close javascript = '' each_with_rescue ( @notes ) do | note | next unless note . has_fieldset? javascript << close_helper ( note ) end javascript end
Process notes to get javascript code to close them . This method is only used when multiple_notes is false .
7,293
def link_helper ( note ) onclick = note . onclick unless href = note . link href = '#' onclick ||= "Footnotes.hideAllAndToggle('#{note.to_sym}_debug_info');return false;" if note . has_fieldset? end "<a href=\"#{href}\" onclick=\"#{onclick}\">#{note.title}</a>" end
Helper that creates the link and javascript code when note is clicked
7,294
def request ( method , request ) response = AsyncResponse . new ( request ) @packages . push ( method : method , request : request , response : response ) response end
Spawns a number of threads with persistent HTTP connection to the specified URI . Sets a default timeout of 60 seconds . Create an asynchronous request and response package put it in the pending queue and return the response object .
7,295
def get_status status = @http . aget ( PredictionIO :: AsyncRequest . new ( '/' ) ) . get begin status . body rescue status end end
Returns PredictionIO s status in string .
7,296
def to_hash h = { :width => width , :height => height , :bits => bits , :comment => comment } h . merge! ( exif ) if exif? h end
Get a hash presentation of the image .
7,297
def method_missing ( method , * args ) super unless args . empty? super unless methods . include? ( method ) @exif . send method if defined? ( @exif ) && @exif end
Dispatch to EXIF . When no EXIF data is available but the + method + does exist for EXIF data + nil + will be returned .
7,298
def method_missing ( method , * args ) super unless args . empty? if @ifds . first . respond_to? ( method ) @ifds . first . send ( method ) elsif TAGS . include? ( method ) @ifds . first . to_hash [ method ] else super end end
Dispatch to first image .
7,299
def gps return nil unless gps_latitude && gps_longitude altitude = gps_altitude . is_a? ( Array ) ? gps_altitude . first : gps_altitude GPS . new ( gps_latitude . to_f * ( gps_latitude_ref == 'S' ? - 1 : 1 ) , gps_longitude . to_f * ( gps_longitude_ref == 'W' ? - 1 : 1 ) , altitude && ( altitude . to_f * ( gps_altitude...
Get GPS location altitude and image direction return nil when not available .