idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
14,100 | def flat_map & block if empty? then None . new else res = block . call ( get ) if res . is_a? ( Some ) then res else Some . new ( res ) end end end | Same as map but flatten the results |
14,101 | def relation ( name ) if @relations . key? name Relation . new @context , @relations . fetch ( name ) else Relation . new @context , @relations . fetch ( name . to_s ) end end | Return relation with given name . |
14,102 | def apply_annotation ( path , suffix = nil , extension = "rb" , plural = false ) pn_models = Pathname . new ( path ) return unless pn_models . exist? suffix = "_#{suffix}" unless suffix == nil extension = ( extension == nil ) ? "" : ".#{extension}" @annotations . each do | model , annotation | prefix = ( plural ) ? mod... | Apply annotations to a file |
14,103 | def generate Dir [ "app/models/*.rb" ] . each do | path | result = File . basename ( path ) . scan ( / \. / ) [ 0 ] [ 0 ] model = eval ( ActiveSupport :: Inflector . camelize ( result ) ) next if model . respond_to? ( :abstract_class ) && model . abstract_class next unless model < ActiveRecord :: Base @annotations [ mo... | Gather model classes and generate annotation for each one . |
14,104 | def generate_annotation ( model ) max_column_length = model . columns . collect { | c | c . name . length } . max annotation = [ ] annotation << "#-#{'--' * 38}-" annotation << "# #{model.name}" annotation << "#" annotation << sprintf ( "# %-#{max_column_length}s SQL Type Null Primary Default" , "Name" )... | Generate annotation text . |
14,105 | def get ( url , params ) request = HTTPI :: Request . new ( resource_url ( url , query_params ( params [ :query ] ) ) ) execute_request ( :get , request , params ) end | Sends a GET request to the supplied resource using the supplied params hash |
14,106 | def put ( url , params ) request = HTTPI :: Request . new ( resource_url ( url , query_params ( params [ :query ] ) ) ) request . body = params [ :body ] . to_json execute_request ( :put , request , params ) end | Sends a PUT request to the supplied resource using the supplied params hash |
14,107 | def login response = post ( '/login' , body : { username : configuration . username , password : configuration . password } , headers : { 'Content-Type' => 'application/json' } ) if response . code == 200 @token = JSON . parse ( response . body , symbolize_names : true , quirks_mode : true ) true else false end end | Sends a POST request to the Filebound API s login endpoint to request a new security token |
14,108 | def write_out ( path = nil ) return img unless path FileUtils . mkdir_p File . dirname ( path ) img . write ( path ) path rescue Errno :: ENOENT puts_and_exit ( "Path not found '#{path}'" ) end | Writes image to disk |
14,109 | def errors if response . decoded_body response . decoded_body [ 'errors' ] || response . decoded_body [ :errors ] || response . decoded_body else response . body end end | Return hash or array of errors if response included such a thing otherwise it returns nil . |
14,110 | def read_attributes_from_file aliases = { } attributes = FasterCSV . new ( @csv_data , @parser_options ) . readline @start_at_row = [ @start_at_row , 1 ] . max @csv_data . rewind attributes . each_with_index do | name , index | name . strip! use_name = aliases [ name ] || name . gsub ( / \s / , '_' ) . gsub ( / \W / , ... | Allow us to read the first line of a csv file to automatically generate the attribute names . Spaces are replaced with underscores and non - word characters are removed . |
14,111 | def parse ( csv_row ) target = self . map_to_class . new @before_filters . each { | filter | filter . call ( csv_row , target ) } self . mapped_attributes . each do | attr_map | target . send ( "#{attr_map.name}=" , attr_map . parse ( csv_row ) ) end @after_filters . each { | filter | filter . call ( csv_row , target )... | Given a CSV row return an instance of an object defined by this mapping |
14,112 | def initialize_properties_with_values_from_owner ( invoice ) if owner . is_a? ( Debtor ) invoice . debtor = owner invoice . debtor_name ||= owner . name invoice . debtor_address ||= owner . address invoice . debtor_postal_code ||= owner . postal_code invoice . debtor_city ||= owner . city invoice . term_of_payment_hand... | Initialize properties in invoice with values from owner |
14,113 | def find ( handle ) handle = Entity :: Handle . build ( :number => handle ) unless handle . is_a? ( Entity :: Handle ) super ( handle ) end | Gets data for CurrentInvoiceLine from the API |
14,114 | def log_entrypoint raise "you must call Imprint.configuration and configure the gem before using LogHelpers" if Imprint . configuration . nil? log_filter = ActionDispatch :: Http :: ParameterFilter . new ( Imprint . configuration [ :log_filters ] || Rails . application . config . filter_parameters ) header_blacklist = ... | Not relying on default rails logging we more often use lograge . We still want to log incoming params safely which lograge doesn t include this does the same sensative param filtering as rails defaults It also allows for logging headers and cookies |
14,115 | def find_by_date_interval ( from , unto ) response = request ( :find_by_date_interval , "first" => from . iso8601 , "last" => unto . iso8601 ) handle_key = "#{Support::String.underscore(entity_class_name)}_handle" . intern handles = [ response [ handle_key ] ] . flatten . reject ( & :blank? ) . collect do | handle | En... | Returns entity objects for a given interval of days . |
14,116 | def get_data response = proxy . get_data ( handle ) update_properties ( response ) self . partial = false self . persisted = true end | Updates Entity with its data from the API |
14,117 | def destroy handleKey = "#{Support::String.camel_back(class_name)}Handle" response = request ( :delete , handleKey => handle . to_hash ) @persisted = false @partial = true response end | Deletes entity permanently from E - conomic . |
14,118 | def update_properties ( hash ) hash . each do | key , value | setter_method = "#{key}=" if respond_to? ( setter_method ) send ( setter_method , value ) end end end | Updates properties of Entity with the values from hash |
14,119 | def send if @to . nil? || @from . nil? || @message . nil? raise ArgumentError , "You need to include 'to' and 'from' numbers and a message to send an SMS" end to = @to . gsub ( " " , "" ) from = @from . gsub ( " " , "" ) parameters = { "sms-send-to" => to , "sms-send-from" => from , "sms-message" => @message [ 0 .. 159... | Constructor to create an SMS - optionally pass in to from and message |
14,120 | def all response = request ( :get_all ) handles = response . values . flatten . collect { | handle | Entity :: Handle . build ( handle ) } get_data_for_handles ( handles ) self end | Fetches all entities from the API . |
14,121 | def find ( handle ) handle = build_handle ( handle ) entity_hash = get_data ( handle ) entity = build ( entity_hash ) entity . persisted = true entity end | Fetches Entity data from API and returns an Entity initialized with that data added to Proxy |
14,122 | def get_data ( handle ) handle = Entity :: Handle . new ( handle ) entity_hash = request ( :get_data , "entityHandle" => handle . to_hash ) entity_hash end | Gets data for Entity from the API . Returns Hash with the response data |
14,123 | def get_data_array ( handles ) return [ ] unless handles && handles . any? entity_class_name_for_soap_request = entity_class . name . split ( "::" ) . last response = request ( :get_data_array , "entityHandles" => { "#{entity_class_name_for_soap_request}Handle" => handles . collect ( & :to_hash ) } ) [ response [ "#{en... | Fetches all data for the given handles . Returns Array with hashes of entity data |
14,124 | def request ( action , data = nil ) session . request ( Endpoint . new . soap_action_name ( entity_class , action ) , data ) end | Requests an action from the API endpoint |
14,125 | def current response = request ( :get_all_current ) handles = response . values . flatten . collect { | handle | Entity :: Handle . build ( handle ) } initialize_items get_data_for_handles ( handles ) self end | Fetches all current orders from the API . |
14,126 | def require_module_to_base file = File . open ( "#{@target_dir}/app/apis/#{@project_name}/base.rb" , "r+" ) file . each do | line | while line == "require_relative './modules/#{@module_name}_apis'\n" do $stdout . puts "\e[33mModule already mounted.\e[0m" return true end end File . open ( "#{@target_dir}/app/apis/#{@pro... | = begin Checks whether the module is already mounted and if not then configures for mounting . = end |
14,127 | def copy_module src = "#{@gem_path}/lib/modules/#{@module_name}/#{@module_name}_apis.rb" dest = "#{@target_dir}/app/apis/#{@project_name}/modules" presence = File . exists? ( "#{dest}/#{@module_name}_apis.rb" ) ? true : false FileUtils . mkdir dest unless File . exists? ( dest ) FileUtils . cp ( src , dest ) unless pre... | = begin Function to copy the module of interest to project location . = end |
14,128 | def create_migrations_and_models src = "#{@gem_path}/lib/modules/migrations" dest = "#{@target_dir}/db/migrate" copy_files ( src , dest , AUTH_MIGRATE ) if @module_name == "oauth" copy_files ( src , dest , OAUTH_MIGRATE ) end src_path = "#{@gem_path}/lib/modules/models" dest_path = "#{@target_dir}/app/models" copy_file... | = begin Function to create the necessary migrations and models . = end |
14,129 | def copy_files ( src , dest , module_model ) module_model . each do | file | presence = File . exists? ( "#{dest}/#{file}" ) ? true : false unless presence FileUtils . cp ( "#{src}/#{file}" , dest ) path = if dest . include? "app" then "app/models" else "db/migrate" end $stdout . puts "\e[1;32m \tcreate\e[0m\t#{path}/#... | = begin Function to copy the module files to project location . = end |
14,130 | def configure_module_files source = "#{@target_dir}/app/apis/#{@project_name}/modules/#{@module_name}_apis.rb" application_module = @project_name . split ( '_' ) . map ( & :capitalize ) * '' file = File . read ( source ) replace = file . gsub ( / / , "module #{application_module}" ) File . open ( source , "w" ) { | f |... | = begin Function to configure the module files . = end |
14,131 | def add_gems file = File . open ( "#{@target_dir}/Gemfile" , "r+" ) file . each do | line | while line == "gem 'oauth2'\n" do return end end File . open ( "#{@target_dir}/Gemfile" , "a+" ) do | f | f . write ( "gem 'multi_json'\ngem 'oauth2'\ngem 'songkick-oauth2-provider'\ngem 'ruby_regex'\ngem 'oauth'\n" ) end $stdou... | = begin Function to add the module dependency gems to project Gemfile . = end |
14,132 | def unmount_module path = "#{@target_dir}/app/apis/#{@project_name}" temp_file = "#{path}/tmp.rb" source = "#{path}/base.rb" delete_file = "#{path}/modules/#{@module_name}_apis.rb" File . open ( temp_file , "w" ) do | out_file | File . foreach ( source ) do | line | unless line == "require_relative './modules/#{@module... | = begin Unmounts the modules by removing the respective module files . = end |
14,133 | def rule ( field , definition ) field = field . to_sym rules [ field ] = [ ] if rules [ field ] . nil? begin if definition . respond_to? ( :each_pair ) add_parameterized_rules ( field , definition ) elsif definition . respond_to? ( :each ) definition . each do | item | if item . respond_to? ( :each_pair ) add_parameter... | Define a rule for this object |
14,134 | def valid? valid = true rules . each_pair do | field , rules | if ! @obj . respond_to? ( field ) raise InvalidKey , "cannot validate non-existent field '#{field}'" end rules . each do | r | if ! r . valid_value? ( @obj . send ( field ) ) valid = false errors [ field ] = { :rule => r . error_key , :params => r . params ... | Determines if this object is valid . When a rule fails for a field this will stop processing further rules . In this way you ll only get one error per field |
14,135 | def add_single_rule ( field , key_or_klass , params = nil ) klass = if key_or_klass . respond_to? ( :new ) key_or_klass else get_rule_class_by_name ( key_or_klass ) end args = [ params ] . compact rule = klass . new ( * args ) rule . obj = @obj if rule . respond_to? ( :obj= ) rules [ field ] << rule end | Adds a single rule to this object |
14,136 | def add_parameterized_rules ( field , rules ) rules . each_pair do | key , params | add_single_rule ( field , key , params ) end end | Adds a set of parameterized rules to this object |
14,137 | def get_rule_class_by_name ( klass ) klass = camelize ( klass ) Validation :: Rule . const_get ( klass ) rescue NameError => e raise InvalidRule . new ( e ) end | Resolves the specified rule name to a rule class |
14,138 | def camelize ( term ) string = term . to_s string = string . sub ( / \d / ) { $& . capitalize } string . gsub ( / \/ \d /i ) { $2 . capitalize } . gsub ( '/' , '::' ) end | Converts a symbol to a class name taken from rails |
14,139 | def remember_validation_metadata ( validation_type , * attr_names ) configuration = attr_names . last . is_a? ( :: Hash ) ? attr_names . pop : { } self . validations ||= [ ] attr_names . flatten . each do | attr_name | self . validations << :: ActiveRecord :: Reflection :: MacroReflection . new ( validation_type , attr... | Store validation info for easy and fast access . |
14,140 | def element ( name , selector , options = { } ) define_singleton_method ( name ) { Element . new ( selector , options . merge ( :base_element => self ) ) } end | Creates an element |
14,141 | def create_base_dirs BASE_DIR . each do | dir | FileUtils . mkdir "#{@project_name}/#{dir}" $stdout . puts "\e[1;32m \tcreate\e[0m\t#{dir}" end FileUtils . mkdir "#{@project_name}/app/apis/#{@project_name}" $stdout . puts "\e[1;32m \tcreate\e[0m\tapp/apis/#{@project_name}" end | = begin Creates the application base directories . = end |
14,142 | def create_api_module File . open ( "#{@project_name}/app/apis/#{@project_name}/base.rb" , "w" ) do | f | f . write ( 'module ' ) f . puts ( @module_name ) f . write ( "\tclass Base < Grape::API\n\tend\nend" ) end $stdout . puts "\e[1;32m \tcreate\e[0m\tapp/apis/#{@project_name}/base.rb" end | = begin Function to create the API modules . = end |
14,143 | def config_server file = File . open ( "#{@project_name}/server.rb" , "r+" ) file . each do | line | while line == " def response(env)\n" do pos = file . pos rest = file . read file . seek pos file . write ( "\t::" ) file . write ( @module_name ) file . write ( "::Base.call(env)\n" ) file . write ( rest ) $stdout . pu... | = begin Function to configure the Goliath server . = end |
14,144 | def copy_files_to_target COMMON_RAMMER_FILES . each do | file | source = File . join ( "#{@gem_path}/lib/modules/common/" , file ) FileUtils . cp ( source , "#{@project_name}" ) $stdout . puts "\e[1;32m \tcreate\e[0m\t#{file}" end end | = begin Function to copy the template files project location . = end |
14,145 | def create_model_file dir = "/app/models/#{@scaffold_name}.rb" unless File . exists? ( File . join ( Dir . pwd , dir ) ) File . join ( Dir . pwd , dir ) source = "#{@gem_path}/lib/modules/scaffold/model.rb" FileUtils . cp ( source , File . join ( Dir . pwd , dir ) ) config_model @valid = true $stdout . puts "\e[1;32m \... | = begin Generates the model file with CRED functionality . = end |
14,146 | def create_migration migration_version = Time . now . to_i dir = "/db/migrate/#{migration_version}_create_#{@scaffold_name}s.rb" unless File . exists? ( File . join ( Dir . pwd , dir ) ) source = "#{@gem_path}/lib/modules/scaffold/migration.rb" FileUtils . cp ( source , File . join ( Dir . pwd , dir ) ) config_migratio... | = begin Generates migration files for the scaffold . = end |
14,147 | def config_migration ( migration_version ) source = "#{Dir.pwd}/db/migrate/#{migration_version}_create_#{@scaffold_name}s.rb" modify_content ( source , 'CreateMigration' , "Create#{@model_class}s" ) modify_content ( source , 'migration' , "#{@scaffold_name}s" ) @arguments . each do | value | @attributes << value . spli... | = begin Configures the migration file with the required user input . = end |
14,148 | def add_attributes ( source , attribute , data_type ) file = File . open ( source , "r+" ) file . each do | line | while line == " create_table :#{@scaffold_name}s do |t|\n" do pos = file . pos rest = file . read file . seek pos file . write ( " t.#{data_type} :#{attribute}\n" ) file . write ( rest ) break end ... | = begin Edits the migration file with the user specified model attributes . = end |
14,149 | def enable_apis dir = "/app/apis/#{@project_name}/#{@scaffold_name}s/base_apis.rb" base_dir = "#{Dir.pwd}/app/apis/#{@project_name}/#{@scaffold_name}s" unless File . exists? ( File . join ( Dir . pwd , dir ) ) FileUtils . mkdir base_dir unless File . exists? ( base_dir ) source = "#{@gem_path}/lib/modules/scaffold/base... | = begin Generates the api file with CRED functionality apis enabled . = end |
14,150 | def config_apis source = "#{Dir.pwd}/app/apis/#{@project_name}/#{@scaffold_name}s/base_apis.rb" content = [ 'AppName' , 'ScaffoldName' , 'Model' , 'model' ] replacement = [ "#{@project_class}" , "#{model_class}s" , "#{model_class}" , "#{@scaffold_name}" ] for i in 0 .. 3 do modify_content ( source , content [ i ] , rep... | = begin Configures the api file with respect to the user input . = end |
14,151 | def mount_apis require_apis_to_base mount_class = "::#{@project_class}::#{@model_class}s::BaseApis" file = File . open ( "#{Dir.pwd}/app/apis/#{@project_name}/base.rb" , "r+" ) file . each do | line | while line == "\tclass Base < Grape::API\n" do pos = file . pos rest = file . read file . seek pos file . write ( "\t\t... | = begin Mounts the scaffold apis onto the application . = end |
14,152 | def require_apis_to_base File . open ( "#{Dir.pwd}/app/apis/#{@project_name}/base.rb" , "r+" ) do | f | pos = f . pos rest = f . read f . seek pos f . write ( "require_relative '#{@scaffold_name}s/base_apis'\n" ) f . write ( rest ) end end | = begin Configures for mounting the scaffold apis . = end |
14,153 | def to_underscore ( value ) underscore_value = value . gsub ( / / , '/' ) . gsub ( / / , '\1_\2' ) . gsub ( / \d / , '\1_\2' ) . tr ( "-" , "_" ) . downcase return underscore_value end | = begin Converts the string into snake case format . = end |
14,154 | def knows_block ( blockhash ) return true if @chain . include? ( blockhash ) @block_queue . queue . any? { | ( block , proto ) | block . header . full_hash == blockhash } end | if block is in chain or in queue |
14,155 | def load! ( path , environment = nil ) require 'yaml' environment ||= Rails . env conf = YAML . load ( File . new ( path ) . read ) . with_indifferent_access [ environment ] load_configuration ( conf ) end | called in railtie |
14,156 | def chunk ( str ) raise ArgumentError , 'str must be a String' unless str . is_a? ( String ) tokens = tokenizer . tokenize ( str ) pos_tags = pos_tagger . tag ( tokens ) . to_ary chunks = j_instance . chunk ( tokens . to_java ( :String ) , pos_tags . to_java ( :String ) ) . to_ary build_chunks ( chunks , tokens , pos_t... | Initializes new instance of Chunker |
14,157 | def generate_greeklish_words ( greek_words ) @greeklish_list . clear greek_words . each do | greek_word | @per_word_greeklish . clear initial_token = greek_word digraphs . each_key do | key | greek_word = greek_word . gsub ( key , digraphs [ key ] ) end input_token = greek_word . split ( / / ) input_token . each do | g... | Gets a list of greek words and generates the greeklish version of each word . |
14,158 | def detect ( str ) raise ArgumentError , 'str must be a String' unless str . is_a? ( String ) j_instance . sentDetect ( str ) . to_ary end | Detects sentences in a string |
14,159 | def pos_detect ( str ) raise ArgumentError , 'str must be a String' unless str . is_a? ( String ) j_instance . sentPosDetect ( str ) . map do | span | OpenNlp :: Util :: Span . new ( span . getStart , span . getEnd ) end end | Detects sentences in a string and returns array of spans |
14,160 | def generate_greek_variants ( token_string ) @greek_words . clear @greek_words << token_string SUFFIX_STRINGS . each do | suffix | if ( token_string . end_with? ( suffix [ 0 ] ) ) generate_more_greek_words ( token_string , suffix [ 0 ] ) break end end greek_words end | This method generates the greek variants of the greek token that receives . |
14,161 | def detect ( tokens ) raise ArgumentError , 'tokens must be an instance of Array' unless tokens . is_a? ( Array ) j_instance . find ( tokens . to_java ( :String ) ) . to_ary end | Detects names for provided array of tokens |
14,162 | def receive_newblock ( proto , t_block , chain_difficulty ) logger . debug 'newblock' , proto : proto , block : t_block , chain_difficulty : chain_difficulty , client : proto . peer . remote_client_version if @chain . include? ( t_block . header . full_hash ) raise AssertError , 'chain difficulty mismatch' unless chain... | Called if there s a newblock announced on the network . |
14,163 | def receive_status ( proto , blockhash , chain_difficulty ) logger . debug 'status received' , proto : proto , chain_difficulty : chain_difficulty @protocols [ proto ] = chain_difficulty if @chainservice . knows_block ( blockhash ) || @synctask logger . debug 'existing task or known hash, discarding' return end if @for... | Called if a new peer is connected . |
14,164 | def receive_newblockhashes ( proto , newblockhashes ) logger . debug 'received newblockhashes' , num : newblockhashes . size , proto : proto newblockhashes = newblockhashes . select { | h | ! @chainservice . knows_block ( h ) } known = @protocols . include? ( proto ) if ! known || newblockhashes . empty? || @synctask l... | No way to check if this really an interesting block at this point . Might lead to an amplification attack need to track this proto and judge usefulness . |
14,165 | def api_eval ( expr_str ) body = [ "ver:\"#{@haystack_version}\"" ] body << "expr" body << '"' + expr_str + '"' res = self . connection . post ( 'eval' ) do | req | req . headers [ 'Content-Type' ] = 'text/plain' req . body = body . join ( "\n" ) end JSON . parse! res . body end | this function will post expr_str exactly as encoded |
14,166 | def equip_point_meta begin equips = read ( { filter : '"equip"' } ) [ 'rows' ] puts equips equips . map! do | eq | eq . delete ( 'disMacro' ) eq [ 'description' ] = eq [ 'id' ] . match ( / \$ / ) [ 1 ] eq [ 'id' ] = eq [ 'id' ] . match ( / \- / ) [ 1 ] eq [ 'points' ] = [ ] read ( { filter : "\"point and equipRef==#{eq... | return meta data for all equip with related points |
14,167 | def parse ( text ) raise ArgumentError , 'passed text must be a String' unless text . is_a? ( String ) text . empty? ? { } : parse_tokens ( tokenizer . tokenize ( text ) , text ) end | Initializes new instance of Parser |
14,168 | def parse ( response ) if response . is_a? Hash response . each_with_object ( { } ) do | ( key , value ) , new_hash | new_hash [ camel_case_to_snake_case ( key ) . to_sym ] = parse ( value ) end elsif response . is_a? Array response . map { | item | parse item } else response end end | Parses the specified value that was returned from a call to the IG Markets API . |
14,169 | def categorize ( str ) raise ArgumentError , 'str param must be a String' unless str . is_a? ( String ) outcomes = j_instance . categorize ( str ) j_instance . getBestCategory ( outcomes ) end | Categorizes a string passed as parameter to one of the categories |
14,170 | def data { text : @page . description , type : :file , li_attr : list_attributes , data : { id : @page . id , url : @context . edit_translation_backend_page_path ( @page , Udongo . config . i18n . app . default_locale ) , delete_url : @context . backend_page_path ( @page , format : :json ) , deletable : @page . deletab... | Context should contain accessible routes . |
14,171 | def identify_greek_word ( input ) input . each_char do | char | if ( ! GREEK_CHARACTERS . include? ( char ) ) return false end end true end | Identifies words with only Greek lowercase characters . |
14,172 | def close ( options = { } ) options [ :deal_id ] = deal_id options [ :direction ] = { buy : :sell , sell : :buy } . fetch ( direction ) options [ :size ] ||= size model = PositionCloseAttributes . build options model . validate body = RequestBodyFormatter . format model @dealing_platform . session . delete ( 'positions... | Closes this position . If called with no options then this position will be fully closed at current market prices partial closes and greater control over the close conditions can be achieved by using the relevant options . |
14,173 | def update ( new_attributes ) new_attributes = { limit_level : limit_level , stop_level : stop_level , trailing_stop : trailing_stop? , trailing_stop_distance : trailing_stop_distance , trailing_stop_increment : trailing_step } . merge new_attributes unless new_attributes [ :trailing_stop ] new_attributes [ :trailing_s... | Updates this position . No attributes are mandatory and any attributes not specified will be kept at their current value . |
14,174 | def encoded_public_key = ( encoded_public_key ) self . public_key = OpenSSL :: PKey :: RSA . new Base64 . strict_decode64 encoded_public_key end | Initializes this password encryptor with the specified encoded public key and timestamp . |
14,175 | def encrypt ( password ) encoded_password = Base64 . strict_encode64 "#{password}|#{time_stamp}" encrypted_password = public_key . public_encrypt encoded_password Base64 . strict_encode64 encrypted_password end | Encrypts a password using this encryptor s public key and time stamp which must have been set prior to calling this method . |
14,176 | def is_typography_selector? ( node ) node . is_a? ( Sass :: Tree :: RuleNode ) && node . rule [ 0 ] . start_with? ( "%f-" ) rescue false end | determines if node is a placeholder selector starting widht the %f - convention for typography rulesets |
14,177 | def coinbase cb_hex = ( app . config [ :pow ] || { } ) [ :coinbase_hex ] if cb_hex raise ValueError , 'coinbase must be String' unless cb_hex . is_a? ( String ) begin cb = Utils . decode_hex Utils . remove_0x_head ( cb_hex ) rescue TypeError raise ValueError , 'invalid coinbase' end else accts = accounts_with_address r... | Return the address that should be used as coinbase for new blocks . |
14,178 | def add_account ( account , store = true , include_address = true , include_id = true ) logger . info "adding account" , account : account if account . uuid && @accounts . any? { | acct | acct . uuid == account . uuid } logger . error 'could not add account (UUID collision)' , uuid : account . uuid raise ValueError , '... | Add an account . |
14,179 | def update_account ( account , new_password , include_address = true , include_id = true ) raise ValueError , "Account not managed by account service" unless @accounts . include? ( account ) raise ValueError , "Cannot update locked account" if account . locked? raise ValueError , 'Account not stored on disk' unless acc... | Replace the password of an account . |
14,180 | def find ( identifier ) identifier = identifier . downcase if identifier =~ / \A \z / return get_by_id ( identifier ) end begin address = Address . new ( identifier ) . to_bytes raise AssertError unless address . size == 20 return self [ address ] rescue end index = identifier . to_i raise ValueError , 'Index must be 1... | Find an account by either its address its id or its index as string . |
14,181 | def get_by_id ( id ) accts = @accounts . select { | acct | acct . uuid == id } if accts . size == 0 raise KeyError , "account with id #{id} unknown" elsif accts . size > 1 logger . warn "multiple accounts with same UUID found" , uuid : id end accts [ 0 ] end | Return the account with a given id . |
14,182 | def get_by_address ( address ) raise ArgumentError , 'address must be 20 bytes' unless address . size == 20 accts = @accounts . select { | acct | acct . address == address } if accts . size == 0 raise KeyError , "account not found by address #{Utils.encode_hex(address)}" elsif accts . size > 1 logger . warn "multiple a... | Get an account by its address . |
14,183 | def to_h attributes . each_with_object ( { } ) do | ( key , value ) , hash | hash [ key ] = if value . is_a? Model value . to_h else value end end end | Compares this model to another the attributes and class must match for them to be considered equal . |
14,184 | def sign_in ( username , password , api_key , platform ) session . username = username session . password = password session . api_key = api_key session . platform = platform result = session . sign_in @client_account_summary = instantiate_models ClientAccountSummary , result end | Signs in to the IG Markets Dealing Platform either the live platform or the demo platform . |
14,185 | def colored_currency ( amount , currency_name ) return '' unless amount color = amount < 0 ? :red : :green ColorizedString [ currency ( amount , currency_name ) ] . colorize color end | Returns a formatted string for the specified currency amount and currency and colors it red for negative values and green for positive values . Two decimal places are used for all currencies except the Japanese Yen . |
14,186 | def snake_case_to_camel_case ( value ) pieces = value . to_s . split '_' ( pieces . first + pieces [ 1 .. - 1 ] . map ( & :capitalize ) . join ) . to_sym end | Takes a string or symbol that uses snake case and converts it to a camel case symbol . |
14,187 | def dump ( include_address = true , include_id = true ) h = { } h [ :crypto ] = @keystore [ :crypto ] h [ :version ] = @keystore [ :version ] h [ :address ] = Utils . encode_hex address if include_address && address h [ :id ] = uuid if include_id && uuid JSON . dump ( h ) end | Dump the keystore for later disk storage . |
14,188 | def sign_tx ( tx ) if privkey logger . info "signing tx" , tx : tx , account : self tx . sign privkey else raise ValueError , "Locked account cannot sign tx" end end | Sign a Transaction with the private key of this account . |
14,189 | def detect_unstratified missing_populations = [ ] existing_populations = @populations . map { | p | p . values . join ( '-' ) } . uniq @populations . each do | population | keys = population . keys - [ 'STRAT' , 'stratification' ] missing_populations |= [ population . values_at ( * keys ) . compact . join ( '-' ) ] end... | Detects missing unstratified populations from the generated |
14,190 | def put ( localpath , destpath ) create ( destpath ) { | dest | Kernel . open ( localpath ) { | source | while record = source . read ( 1048576 ) dest . write ( record ) end } } end | copy local file to remote |
14,191 | def get ( remotepath , destpath ) Kernel . open ( destpath , 'w' ) { | dest | readchunks ( remotepath ) { | chunk | dest . write chunk } } end | copy remote file to local |
14,192 | def readchunks ( path , chunksize = 1048576 ) open ( path ) { | source | size = source . length index = 0 while index < size yield source . read ( index , chunksize ) index += chunksize end } end | yeild chunksize of path one chunk at a time |
14,193 | def tokenize ( str ) raise ArgumentError , 'str must be a String' unless str . is_a? ( String ) j_instance . tokenize ( str ) . to_ary end | Tokenizes a string |
14,194 | def tag ( tokens ) ! tokens . is_a? ( Array ) && ! tokens . is_a? ( String ) && raise ( ArgumentError , 'tokens must be an instance of String or Array' ) j_instance . tag ( tokens . to_java ( :String ) ) end | Adds tags to tokens passed as argument |
14,195 | def reload self . attributes = @dealing_platform . account . all . detect { | a | a . account_id == account_id } . attributes end | Reloads this account s attributes by re - querying the IG Markets API . |
14,196 | def only ( fields , fields_with_base = nil ) q = { } if [ Array , String ] . include? ( fields_with_base . class ) fields_with_base = [ fields_with_base ] if fields_with_base . class == String q [ fields . to_sym ] = fields_with_base else fields = [ fields ] if fields . class == String q = { BASE : fields } end @query ... | Specifies an array of only keys in BASE object that would be included in the response . |
14,197 | def update ( new_attributes ) existing_attributes = { good_till_date : good_till_date , level : order_level , limit_distance : limit_distance , stop_distance : stop_distance , time_in_force : time_in_force , type : order_type } model = WorkingOrderUpdateAttributes . new existing_attributes , new_attributes model . vali... | Updates this working order . No attributes are mandatory and any attributes not specified will be kept at their current values . |
14,198 | def add_color ( node , key = nil ) key ||= node . expr . to_s self . colors [ key ] ||= { :variables => [ ] , :alternate_values => [ ] } self . colors [ key ] [ :variables ] << node . name self . colors [ key ] [ :alternate_values ] |= ( [ node . expr . to_sass , node . expr . inspect ] - [ key ] ) end | add found color to |
14,199 | def apply_layout ( env , content , opts ) if layout = env [ 'layout' ] layout . format = opts [ :format ] layout . content = content layout . template_name = opts [ :layout ] if layout . template_name? ( opts [ :layout ] , opts ) layout else content end end | Apply the layout if it exists |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.