_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q16400
Lit.Import.upsert
train
def upsert(locale, key, value) # rubocop:disable Metrics/MethodLength I18n.with_locale(locale) do # when an array has to be inserted with a default value, it needs to # be done like: # I18n.t('foo', default: [['bar', 'baz']]) # because without the double array, array items are treated as fallback keys # - then, the last array element is the final fallback; so in this case we # don't specify fallback keys and only specify the final fallback, which # is the array val = value.is_a?(Array) ? [value] : value I18n.t(key, default: val) unless @raw # this indicates that this translation already exists existing_translation = Lit::Localization.joins(:locale, :localization_key) .find_by('localization_key = ? and locale = ?', key, locale) if existing_translation existing_translation.update(translated_value: value, is_changed: true) lkey = existing_translation.localization_key lkey.update(is_deleted: false) if lkey.is_deleted end end end end
ruby
{ "resource": "" }
q16401
Babosa.Identifier.transliterate!
train
def transliterate!(*kinds) kinds.compact! kinds = [:latin] if kinds.empty? kinds.each do |kind| transliterator = Transliterator.get(kind).instance @wrapped_string = transliterator.transliterate(@wrapped_string) end @wrapped_string end
ruby
{ "resource": "" }
q16402
Babosa.Identifier.to_ruby_method!
train
def to_ruby_method!(allow_bangs = true) leader, trailer = @wrapped_string.strip.scan(/\A(.+)(.)\z/).flatten leader = leader.to_s trailer = trailer.to_s if allow_bangs trailer.downcase! trailer.gsub!(/[^a-z0-9!=\\?]/, '') else trailer.downcase! trailer.gsub!(/[^a-z0-9]/, '') end id = leader.to_identifier id.transliterate! id.to_ascii! id.clean! id.word_chars! id.clean! @wrapped_string = id.to_s + trailer if @wrapped_string == "" raise Error, "Input generates impossible Ruby method name" end with_separators!("_") end
ruby
{ "resource": "" }
q16403
Babosa.Identifier.truncate_bytes!
train
def truncate_bytes!(max) return @wrapped_string if @wrapped_string.bytesize <= max curr = 0 new = [] unpack("U*").each do |char| break if curr > max char = [char].pack("U") curr += char.bytesize if curr <= max new << char end end @wrapped_string = new.join end
ruby
{ "resource": "" }
q16404
Babosa.Identifier.send_to_new_instance
train
def send_to_new_instance(*args) id = Identifier.allocate id.instance_variable_set :@wrapped_string, to_s id.send(*args) id end
ruby
{ "resource": "" }
q16405
NyanCat.Common.nyan_cat
train
def nyan_cat if self.failed_or_pending? && self.finished? ascii_cat('x')[@color_index%2].join("\n") #'~|_(x.x)' elsif self.failed_or_pending? ascii_cat('o')[@color_index%2].join("\n") #'~|_(o.o)' elsif self.finished? ascii_cat('-')[@color_index%2].join("\n") # '~|_(-.-)' else ascii_cat('^')[@color_index%2].join("\n") # '~|_(^.^)' end end
ruby
{ "resource": "" }
q16406
NyanCat.Common.terminal_width
train
def terminal_width if defined? JRUBY_VERSION default_width = 80 else default_width = `stty size`.split.map { |x| x.to_i }.reverse.first - 1 end @terminal_width ||= default_width end
ruby
{ "resource": "" }
q16407
NyanCat.Common.scoreboard
train
def scoreboard @pending_examples ||= [] @failed_examples ||= [] padding = @example_count.to_s.length [ @current.to_s.rjust(padding), success_color((@current - @pending_examples.size - @failed_examples.size).to_s.rjust(padding)), pending_color(@pending_examples.size.to_s.rjust(padding)), failure_color(@failed_examples.size.to_s.rjust(padding)) ] end
ruby
{ "resource": "" }
q16408
NyanCat.Common.nyan_trail
train
def nyan_trail marks = @example_results.each_with_index.map{ |mark, i| highlight(mark) * example_width(i) } marks.shift(current_width - terminal_width) if current_width >= terminal_width nyan_cat.split("\n").each_with_index.map do |line, index| format("%s#{line}", marks.join) end.join("\n") end
ruby
{ "resource": "" }
q16409
NyanCat.Common.colors
train
def colors @colors ||= (0...(6 * 7)).map do |n| pi_3 = Math::PI / 3 n *= 1.0 / 6 r = (3 * Math.sin(n ) + 3).to_i g = (3 * Math.sin(n + 2 * pi_3) + 3).to_i b = (3 * Math.sin(n + 4 * pi_3) + 3).to_i 36 * r + 6 * g + b + 16 end end
ruby
{ "resource": "" }
q16410
NyanCat.Common.highlight
train
def highlight(mark = PASS) case mark when PASS; rainbowify PASS_ARY[@color_index%2] when FAIL; "\e[31m#{mark}\e[0m" when ERROR; "\e[33m#{mark}\e[0m" when PENDING; "\e[33m#{mark}\e[0m" else mark end end
ruby
{ "resource": "" }
q16411
InvoicePrinter.PDFDocument.set_fonts
train
def set_fonts(font) font_name = Pathname.new(font).basename @pdf.font_families.update( "#{font_name}" => { normal: font, italic: font, bold: font, bold_italic: font } ) @pdf.font(font_name) end
ruby
{ "resource": "" }
q16412
InvoicePrinter.PDFDocument.build_pdf
train
def build_pdf @push_down = 0 @push_items_table = 0 @pdf.fill_color '000000' build_header build_provider_box build_purchaser_box build_payment_method_box build_info_box build_items build_total build_stamp build_logo build_note build_footer end
ruby
{ "resource": "" }
q16413
InvoicePrinter.PDFDocument.determine_items_structure
train
def determine_items_structure items_params = {} @document.items.each do |item| items_params[:names] = true unless item.name.empty? items_params[:variables] = true unless item.variable.empty? items_params[:quantities] = true unless item.quantity.empty? items_params[:units] = true unless item.unit.empty? items_params[:prices] = true unless item.price.empty? items_params[:taxes] = true unless item.tax.empty? items_params[:taxes2] = true unless item.tax2.empty? items_params[:taxes3] = true unless item.tax3.empty? items_params[:amounts] = true unless item.amount.empty? end items_params end
ruby
{ "resource": "" }
q16414
InvoicePrinter.PDFDocument.build_items_data
train
def build_items_data(items_params) @document.items.map do |item| line = [] line << item.name if items_params[:names] line << item.variable if items_params[:variables] line << item.quantity if items_params[:quantities] line << item.unit if items_params[:units] line << item.price if items_params[:prices] line << item.tax if items_params[:taxes] line << item.tax2 if items_params[:taxes2] line << item.tax3 if items_params[:taxes3] line << item.amount if items_params[:amounts] line end end
ruby
{ "resource": "" }
q16415
InvoicePrinter.PDFDocument.build_items_header
train
def build_items_header(items_params) headers = [] headers << { text: label_with_sublabel(:item) } if items_params[:names] headers << { text: label_with_sublabel(:variable) } if items_params[:variables] headers << { text: label_with_sublabel(:quantity) } if items_params[:quantities] headers << { text: label_with_sublabel(:unit) } if items_params[:units] headers << { text: label_with_sublabel(:price_per_item) } if items_params[:prices] headers << { text: label_with_sublabel(:tax) } if items_params[:taxes] headers << { text: label_with_sublabel(:tax2) } if items_params[:taxes2] headers << { text: label_with_sublabel(:tax3) } if items_params[:taxes3] headers << { text: label_with_sublabel(:amount) } if items_params[:amounts] headers end
ruby
{ "resource": "" }
q16416
MAuth.Proxy.call
train
def call(request_env) request = ::Rack::Request.new(request_env) request_method = request_env['REQUEST_METHOD'].downcase.to_sym request_env['rack.input'].rewind request_body = request_env['rack.input'].read request_env['rack.input'].rewind request_headers = {} request_env.each do |k, v| if k.start_with?('HTTP_') && k != 'HTTP_HOST' name = k.sub(/\AHTTP_/, '') request_headers[name] = v end end request_headers.merge!(@persistent_headers) if @browser_proxy target_uri = request_env["REQUEST_URI"] connection = @target_uris.any? { |u| target_uri.start_with? u } ? @signer_connection : @unsigned_connection response = connection.run_request(request_method, target_uri, request_body, request_headers) else response = @connection.run_request(request_method, request.fullpath, request_body, request_headers) end response_headers = response.headers.reject do |name, _value| %w(Content-Length Transfer-Encoding).map(&:downcase).include?(name.downcase) end [response.status, response_headers, [response.body || '']] end
ruby
{ "resource": "" }
q16417
MAuth.Client.symbolize_keys
train
def symbolize_keys(hash) hash.keys.each do |key| hash[(key.to_sym rescue key) || key] = hash.delete(key) end hash end
ruby
{ "resource": "" }
q16418
Determinator.Control.for_actor
train
def for_actor(id: nil, guid: nil, default_properties: {}) ActorControl.new(self, id: id, guid: guid, default_properties: default_properties) end
ruby
{ "resource": "" }
q16419
Determinator.Control.feature_flag_on?
train
def feature_flag_on?(name, id: nil, guid: nil, properties: {}) determinate_and_notice(name, id: id, guid: guid, properties: properties) do |feature| feature.feature_flag? end end
ruby
{ "resource": "" }
q16420
Determinator.Control.which_variant
train
def which_variant(name, id: nil, guid: nil, properties: {}) determinate_and_notice(name, id: id, guid: guid, properties: properties) do |feature| feature.experiment? end end
ruby
{ "resource": "" }
q16421
Determinator.Feature.parse_outcome
train
def parse_outcome(outcome, allow_exclusion:) valid_outcomes = experiment? ? variants.keys : [true] valid_outcomes << false if allow_exclusion valid_outcomes.include?(outcome) ? outcome : nil end
ruby
{ "resource": "" }
q16422
ROR.SubProcess.stop
train
def stop return self if @pid.nil? _log "stopping (##{@pid})" Process.kill('INT', @pid) Timeout::timeout(10) do sleep(10e-3) until Process.wait(@pid, Process::WNOHANG) @status = $? end @pid = nil self end
ruby
{ "resource": "" }
q16423
ROR.SubProcess.wait_log
train
def wait_log(regexp) cursor = 0 Timeout::timeout(10) do loop do line = @loglines[cursor] sleep(10e-3) if line.nil? break if line && line =~ regexp cursor += 1 unless line.nil? end end self end
ruby
{ "resource": "" }
q16424
Unread.GarbageCollector.readers_to_cleanup
train
def readers_to_cleanup(reader_class) reader_class. reader_scope. joins(:read_marks). where(ReadMark.table_name => { readable_type: readable_class.name }). group("#{ReadMark.quoted_table_name}.reader_type, #{ReadMark.quoted_table_name}.reader_id, #{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}"). having("COUNT(#{ReadMark.quoted_table_name}.id) > 1"). select("#{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}") end
ruby
{ "resource": "" }
q16425
Artifactory.Util.truncate
train
def truncate(string, options = {}) length = options[:length] || 30 if string.length > length string[0..length - 3] + "..." else string end end
ruby
{ "resource": "" }
q16426
Artifactory.Util.rename_keys
train
def rename_keys(options, map = {}) Hash[options.map { |k, v| [map[k] || k, v] }] end
ruby
{ "resource": "" }
q16427
Artifactory.Util.slice
train
def slice(options, *keys) keys.inject({}) do |hash, key| hash[key] = options[key] if options[key] hash end end
ruby
{ "resource": "" }
q16428
Artifactory.Util.xml_to_hash
train
def xml_to_hash(element, child_with_children = "", unique_children = true) properties = {} element.each_element_with_text do |e| if e.name.eql?(child_with_children) if unique_children e.each_element_with_text do |t| properties[t.name] = to_type(t.text) end else children = [] e.each_element_with_text do |t| properties[t.name] = children.push(to_type(t.text)) end end else properties[e.name] = to_type(e.text) end end properties end
ruby
{ "resource": "" }
q16429
Artifactory.Resource::Artifact.properties
train
def properties(props = nil) if props.nil? || props.empty? get_properties else set_properties(props) get_properties(true) end end
ruby
{ "resource": "" }
q16430
Artifactory.Resource::Artifact.download
train
def download(target = Dir.mktmpdir, options = {}) target = File.expand_path(target) # Make the directory if it doesn't yet exist FileUtils.mkdir_p(target) unless File.exist?(target) # Use the server artifact's filename if one wasn't given filename = options[:filename] || File.basename(download_uri) # Construct the full path for the file destination = File.join(target, filename) File.open(destination, "wb") do |file| client.get(download_uri) do |chunk| file.write chunk end end destination end
ruby
{ "resource": "" }
q16431
Artifactory.Resource::Artifact.upload
train
def upload(repo, remote_path, properties = {}, headers = {}) file = File.new(File.expand_path(local_path)) matrix = to_matrix_properties(properties) endpoint = File.join("#{url_safe(repo)}#{matrix}", remote_path) # Include checksums in headers if given. headers["X-Checksum-Md5"] = md5 if md5 headers["X-Checksum-Sha1"] = sha1 if sha1 response = client.put(endpoint, file, headers) return unless response.is_a?(Hash) self.class.from_hash(response) end
ruby
{ "resource": "" }
q16432
Artifactory.Resource::Artifact.get_properties
train
def get_properties(refresh_cache = false) if refresh_cache || @properties.nil? @properties = client.get(File.join("/api/storage", relative_path), properties: nil)["properties"] end @properties end
ruby
{ "resource": "" }
q16433
Artifactory.Resource::Artifact.set_properties
train
def set_properties(properties) matrix = to_matrix_properties(properties) endpoint = File.join("/api/storage", relative_path) + "?properties=#{matrix}" client.put(endpoint, nil) end
ruby
{ "resource": "" }
q16434
Artifactory.Resource::Artifact.copy_or_move
train
def copy_or_move(action, destination, options = {}) params = {}.tap do |param| param[:to] = destination param[:failFast] = 1 if options[:fail_fast] param[:suppressLayouts] = 1 if options[:suppress_layouts] param[:dry] = 1 if options[:dry_run] end endpoint = File.join("/api", action.to_s, relative_path) + "?#{to_query_string_parameters(params)}" client.post(endpoint, {}) end
ruby
{ "resource": "" }
q16435
Artifactory.Resource::Base.to_hash
train
def to_hash attributes.inject({}) do |hash, (key, value)| unless Resource::Base.has_attribute?(key) hash[Util.camelize(key, true)] = send(key.to_sym) end hash end end
ruby
{ "resource": "" }
q16436
Artifactory.Resource::Base.to_matrix_properties
train
def to_matrix_properties(hash = {}) properties = hash.map do |k, v| key = CGI.escape(k.to_s) value = CGI.escape(v.to_s) "#{key}=#{value}" end if properties.empty? nil else ";#{properties.join(';')}" end end
ruby
{ "resource": "" }
q16437
Artifactory.Resource::Base.to_query_string_parameters
train
def to_query_string_parameters(hash = {}) properties = hash.map do |k, v| key = URI.escape(k.to_s) value = URI.escape(v.to_s) "#{key}=#{value}" end if properties.empty? nil else properties.join("&") end end
ruby
{ "resource": "" }
q16438
Artifactory.Resource::Build.promote
train
def promote(target_repo, options = {}) request_body = {}.tap do |body| body[:status] = options[:status] || "promoted" body[:comment] = options[:comment] || "" body[:ciUser] = options[:user] || Artifactory.username body[:dryRun] = options[:dry_run] || false body[:targetRepo] = target_repo body[:copy] = options[:copy] || false body[:artifacts] = true # always move/copy the build's artifacts body[:dependencies] = options[:dependencies] || false body[:scopes] = options[:scopes] || [] body[:properties] = options[:properties] || {} body[:failFast] = options[:fail_fast] || true end endpoint = "/api/build/promote/#{url_safe(name)}/#{url_safe(number)}" client.post(endpoint, JSON.fast_generate(request_body), "Content-Type" => "application/json" ) end
ruby
{ "resource": "" }
q16439
Artifactory.Resource::Build.save
train
def save raise Error::InvalidBuildType.new(type) unless BUILD_TYPES.include?(type) file = Tempfile.new("build.json") file.write(to_json) file.rewind client.put("/api/build", file, "Content-Type" => "application/json" ) true ensure if file file.close file.unlink end end
ruby
{ "resource": "" }
q16440
Artifactory.Resource::BuildComponent.builds
train
def builds @builds ||= Collection::Build.new(self, name: name) do Resource::Build.all(name) end end
ruby
{ "resource": "" }
q16441
Artifactory.Resource::BuildComponent.delete
train
def delete(options = {}) params = {}.tap do |param| param[:buildNumbers] = options[:build_numbers].join(",") if options[:build_numbers] param[:artifacts] = 1 if options[:artifacts] param[:deleteAll] = 1 if options[:delete_all] end endpoint = api_path + "?#{to_query_string_parameters(params)}" client.delete(endpoint, {}) true rescue Error::HTTPError => e false end
ruby
{ "resource": "" }
q16442
Artifactory.Resource::BuildComponent.rename
train
def rename(new_name, options = {}) endpoint = "/api/build/rename/#{url_safe(name)}" + "?to=#{new_name}" client.post(endpoint, {}) true rescue Error::HTTPError => e false end
ruby
{ "resource": "" }
q16443
Artifactory.Resource::Repository.upload
train
def upload(local_path, remote_path, properties = {}, headers = {}) artifact = Resource::Artifact.new(local_path: local_path) artifact.upload(key, remote_path, properties, headers) end
ruby
{ "resource": "" }
q16444
Artifactory.Resource::Repository.upload_from_archive
train
def upload_from_archive(local_path, remote_path, properties = {}) artifact = Resource::Artifact.new(local_path: local_path) artifact.upload_from_archive(key, remote_path, properties) end
ruby
{ "resource": "" }
q16445
Artifactory.Resource::Repository.artifacts
train
def artifacts @artifacts ||= Collection::Artifact.new(self, repos: key) do Resource::Artifact.search(name: ".*", repos: key) end end
ruby
{ "resource": "" }
q16446
Subprocess.Process.drain_fd
train
def drain_fd(fd, buf=nil) loop do tmp = fd.read_nonblock(4096) buf << tmp unless buf.nil? end rescue EOFError, Errno::EPIPE fd.close true rescue Errno::EINTR rescue Errno::EWOULDBLOCK, Errno::EAGAIN false end
ruby
{ "resource": "" }
q16447
Subprocess.Process.select_until
train
def select_until(read_array, write_array, err_array, timeout_at) if !timeout_at return IO.select(read_array, write_array, err_array) end remaining = (timeout_at - Time.now) return nil if remaining <= 0 IO.select(read_array, write_array, err_array, remaining) end
ruby
{ "resource": "" }
q16448
Predictor.InputMatrix.remove_from_set
train
def remove_from_set(set, item) Predictor.redis.multi do |redis| redis.srem(redis_key(:items, set), item) redis.srem(redis_key(:sets, item), set) end end
ruby
{ "resource": "" }
q16449
Predictor.InputMatrix.delete_item
train
def delete_item(item) Predictor.redis.watch(redis_key(:sets, item)) do sets = Predictor.redis.smembers(redis_key(:sets, item)) Predictor.redis.multi do |multi| sets.each do |set| multi.srem(redis_key(:items, set), item) end multi.del redis_key(:sets, item) end end end
ruby
{ "resource": "" }
q16450
ADAL.AuthenticationContext.acquire_token_for_client
train
def acquire_token_for_client(resource, client_cred) fail_if_arguments_nil(resource, client_cred) token_request_for(client_cred).get_for_client(resource) end
ruby
{ "resource": "" }
q16451
ADAL.AuthenticationContext.acquire_token_with_authorization_code
train
def acquire_token_with_authorization_code( auth_code, redirect_uri, client_cred, resource = nil) fail_if_arguments_nil(auth_code, redirect_uri, client_cred) token_request_for(client_cred) .get_with_authorization_code(auth_code, redirect_uri, resource) end
ruby
{ "resource": "" }
q16452
ADAL.AuthenticationContext.acquire_token_with_refresh_token
train
def acquire_token_with_refresh_token( refresh_token, client_cred, resource = nil) fail_if_arguments_nil(refresh_token, client_cred) token_request_for(client_cred) .get_with_refresh_token(refresh_token, resource) end
ruby
{ "resource": "" }
q16453
ADAL.AuthenticationContext.authorization_request_url
train
def authorization_request_url( resource, client_id, redirect_uri, extra_query_params = {}) @authority.authorize_endpoint( extra_query_params.reverse_merge( client_id: client_id, response_mode: FORM_POST, redirect_uri: redirect_uri, resource: resource, response_type: CODE)) end
ruby
{ "resource": "" }
q16454
ADAL.ClientAssertionCertificate.request_params
train
def request_params jwt_assertion = SelfSignedJwtFactory .new(@client_id, @authority.token_endpoint) .create_and_sign_jwt(@certificate, @private_key) ClientAssertion.new(client_id, jwt_assertion).request_params end
ruby
{ "resource": "" }
q16455
ADAL.UserCredential.request_params
train
def request_params case account_type when AccountType::MANAGED managed_request_params when AccountType::FEDERATED federated_request_params else fail UnsupportedAccountTypeError, account_type end end
ruby
{ "resource": "" }
q16456
ADAL.WSTrustRequest.execute
train
def execute(username, password) logger.verbose("Making a WSTrust request with action #{@action}.") request = Net::HTTP::Get.new(@endpoint.path) add_headers(request) request.body = rst(username, password) response = http(@endpoint).request(request) if response.code == '200' WSTrustResponse.parse(response.body) else fail WSTrustResponse::WSTrustError, "Failed request: code #{response.code}." end end
ruby
{ "resource": "" }
q16457
ADAL.MexRequest.execute
train
def execute request = Net::HTTP::Get.new(@endpoint.path) request.add_field('Content-Type', 'application/soap+xml') MexResponse.parse(http(@endpoint).request(request).body) end
ruby
{ "resource": "" }
q16458
ADAL.Authority.authorize_endpoint
train
def authorize_endpoint(params = nil) params = params.select { |_, v| !v.nil? } if params.respond_to? :select if params.nil? || params.empty? URI::HTTPS.build(host: @host, path: '/' + @tenant + AUTHORIZE_PATH) else URI::HTTPS.build(host: @host, path: '/' + @tenant + AUTHORIZE_PATH, query: URI.encode_www_form(params)) end end
ruby
{ "resource": "" }
q16459
ADAL.Authority.discovery_uri
train
def discovery_uri(host = WORLD_WIDE_AUTHORITY) URI(DISCOVERY_TEMPLATE.expand(host: host, endpoint: authorize_endpoint)) end
ruby
{ "resource": "" }
q16460
ADAL.Authority.validated_dynamically?
train
def validated_dynamically? logger.verbose("Attempting instance discovery at: #{discovery_uri}.") http_response = Net::HTTP.get(discovery_uri) if http_response.nil? logger.error('Dynamic validation received no response from endpoint.') return false end parse_dynamic_validation(JSON.parse(http_response)) end
ruby
{ "resource": "" }
q16461
ADAL.WSTrustResponse.grant_type
train
def grant_type case @token_type when TokenType::V1 TokenRequest::GrantType::SAML1 when TokenType::V2 TokenRequest::GrantType::SAML2 end end
ruby
{ "resource": "" }
q16462
ADAL.SelfSignedJwtFactory.create_and_sign_jwt
train
def create_and_sign_jwt(certificate, private_key) JWT.encode(payload, private_key, RS256, header(certificate)) end
ruby
{ "resource": "" }
q16463
ADAL.SelfSignedJwtFactory.header
train
def header(certificate) x5t = thumbprint(certificate) logger.verbose("Creating self signed JWT header with thumbprint: #{x5t}.") { TYPE => TYPE_JWT, ALGORITHM => RS256, THUMBPRINT => x5t } end
ruby
{ "resource": "" }
q16464
ADAL.SelfSignedJwtFactory.payload
train
def payload now = Time.now - 1 expires = now + 60 * SELF_SIGNED_JWT_LIFETIME logger.verbose("Creating self signed JWT payload. Expires: #{expires}. " \ "NotBefore: #{now}.") { AUDIENCE => @token_endpoint, ISSUER => @client_id, SUBJECT => @client_id, NOT_BEFORE => now.to_i, EXPIRES_ON => expires.to_i, JWT_ID => SecureRandom.uuid } end
ruby
{ "resource": "" }
q16465
ADAL.TokenRequest.get_for_client
train
def get_for_client(resource) logger.verbose("TokenRequest getting token for client for #{resource}.") request(GRANT_TYPE => GrantType::CLIENT_CREDENTIALS, RESOURCE => resource) end
ruby
{ "resource": "" }
q16466
ADAL.TokenRequest.get_with_authorization_code
train
def get_with_authorization_code(auth_code, redirect_uri, resource = nil) logger.verbose('TokenRequest getting token with authorization code ' \ "#{auth_code}, redirect_uri #{redirect_uri} and " \ "resource #{resource}.") request(CODE => auth_code, GRANT_TYPE => GrantType::AUTHORIZATION_CODE, REDIRECT_URI => URI.parse(redirect_uri.to_s), RESOURCE => resource) end
ruby
{ "resource": "" }
q16467
ADAL.TokenRequest.get_with_refresh_token
train
def get_with_refresh_token(refresh_token, resource = nil) logger.verbose('TokenRequest getting token with refresh token digest ' \ "#{Digest::SHA256.hexdigest refresh_token} and resource " \ "#{resource}.") request_no_cache(GRANT_TYPE => GrantType::REFRESH_TOKEN, REFRESH_TOKEN => refresh_token, RESOURCE => resource) end
ruby
{ "resource": "" }
q16468
ADAL.TokenRequest.get_with_user_credential
train
def get_with_user_credential(user_cred, resource = nil) logger.verbose('TokenRequest getting token with user credential ' \ "#{user_cred} and resource #{resource}.") oauth = if user_cred.is_a? UserIdentifier lambda do fail UserCredentialError, 'UserIdentifier can only be used once there is a ' \ 'matching token in the cache.' end end || -> {} request(user_cred.request_params.merge(RESOURCE => resource), &oauth) end
ruby
{ "resource": "" }
q16469
ADAL.TokenRequest.request
train
def request(params, &block) cached_token = check_cache(request_params(params)) return cached_token if cached_token cache_response(request_no_cache(request_params(params), &block)) end
ruby
{ "resource": "" }
q16470
ADAL.CacheDriver.add
train
def add(token_response) return unless token_response.instance_of? SuccessResponse logger.verbose('Adding successful TokenResponse to cache.') entry = CachedTokenResponse.new(@client, @authority, token_response) update_refresh_tokens(entry) if entry.mrrt? @token_cache.add(entry) end
ruby
{ "resource": "" }
q16471
ADAL.CacheDriver.find
train
def find(query = {}) query = query.map { |k, v| [FIELDS[k], v] if FIELDS[k] }.compact.to_h resource = query.delete(RESOURCE) matches = validate( find_all_cached_entries( query.reverse_merge( authority: @authority, client_id: @client.client_id)) ) resource_specific(matches, resource) || refresh_mrrt(matches, resource) end
ruby
{ "resource": "" }
q16472
ADAL.CacheDriver.find_all_cached_entries
train
def find_all_cached_entries(query) logger.verbose("Searching cache for tokens by keys: #{query.keys}.") @token_cache.find do |entry| query.map do |k, v| (entry.respond_to? k.to_sym) && (v == entry.send(k.to_sym)) end.reduce(:&) end end
ruby
{ "resource": "" }
q16473
ADAL.CacheDriver.refresh_mrrt
train
def refresh_mrrt(responses, resource) logger.verbose("Attempting to obtain access token for #{resource} by " \ "refreshing 1 of #{responses.count(&:mrrt?)} matching " \ 'MRRTs.') responses.each do |response| if response.mrrt? refresh_response = response.refresh(resource) return refresh_response if add(refresh_response) end end nil end
ruby
{ "resource": "" }
q16474
ADAL.CacheDriver.resource_specific
train
def resource_specific(responses, resource) logger.verbose("Looking through #{responses.size} matching cache " \ "entries for resource #{resource}.") responses.select { |response| response.resource == resource } .map(&:token_response).first end
ruby
{ "resource": "" }
q16475
ADAL.CacheDriver.update_refresh_tokens
train
def update_refresh_tokens(mrrt) fail ArgumentError, 'Token must contain an MRRT.' unless mrrt.mrrt? @token_cache.find.each do |entry| entry.refresh_token = mrrt.refresh_token if mrrt.can_refresh?(entry) end end
ruby
{ "resource": "" }
q16476
ADAL.CacheDriver.validate
train
def validate(entries) logger.verbose("Validating #{entries.size} possible cache matches.") valid_entries = entries.group_by(&:validate) @token_cache.remove(valid_entries[false] || []) valid_entries[true] || [] end
ruby
{ "resource": "" }
q16477
ADAL.CachedTokenResponse.to_json
train
def to_json(_ = nil) JSON.unparse(authority: [authority.host, authority.tenant], client_id: client_id, token_response: token_response) end
ruby
{ "resource": "" }
q16478
ADAL.CachedTokenResponse.can_refresh?
train
def can_refresh?(other) mrrt? && (authority == other.authority) && (user_info == other.user_info) && (client_id == other.client_id) end
ruby
{ "resource": "" }
q16479
ADAL.CachedTokenResponse.validate
train
def validate(expiration_buffer_sec = 0) return true if (Time.now + expiration_buffer_sec).to_i < expires_on unless refresh_token logger.verbose('Cached token is almost expired but no refresh token ' \ 'is available.') return false end logger.verbose('Cached token is almost expired, attempting to refresh ' \ ' with refresh token.') refresh_response = refresh if refresh_response.instance_of? SuccessResponse logger.verbose('Successfully refreshed token in cache.') @token_response = refresh_response true else logger.warn('Failed to refresh token in cache with refresh token.') false end end
ruby
{ "resource": "" }
q16480
ADAL.CachedTokenResponse.refresh
train
def refresh(new_resource = resource) token_response = TokenRequest .new(authority, @client) .get_with_refresh_token(refresh_token, new_resource) if token_response.instance_of? SuccessResponse token_response.parse_id_token(id_token) end token_response end
ruby
{ "resource": "" }
q16481
ADAL.Util.string_hash
train
def string_hash(hash) hash.map { |k, v| [k.to_s, v.to_s] }.to_h end
ruby
{ "resource": "" }
q16482
ADAL.MemoryCache.add
train
def add(entries) entries = Array(entries) # If entries is an array, this is a no-op. old_size = @entries.size @entries |= entries logger.verbose("Added #{entries.size - old_size} new entries to cache.") end
ruby
{ "resource": "" }
q16483
ADAL.OAuthRequest.execute
train
def execute request = Net::HTTP::Post.new(@endpoint_uri.path) add_headers(request) request.body = URI.encode_www_form(string_hash(params)) TokenResponse.parse(http(@endpoint_uri).request(request).body) end
ruby
{ "resource": "" }
q16484
ADAL.OAuthRequest.add_headers
train
def add_headers(request) return if Logging.correlation_id.nil? request.add_field(CLIENT_REQUEST_ID.to_s, Logging.correlation_id) request.add_field(CLIENT_RETURN_CLIENT_REQUEST_ID.to_s, true) end
ruby
{ "resource": "" }
q16485
U2F.U2F.authenticate!
train
def authenticate!(challenge, response, registration_public_key, registration_counter) # TODO: check that it's the correct key_handle as well raise NoMatchingRequestError unless challenge == response.client_data.challenge raise ClientDataTypeError unless response.client_data.authentication? pem = U2F.public_key_pem(registration_public_key) raise AuthenticationFailedError unless response.verify(app_id, pem) raise UserNotPresentError unless response.user_present? unless response.counter > registration_counter raise CounterTooLowError unless response.counter.zero? && registration_counter.zero? end end
ruby
{ "resource": "" }
q16486
U2F.U2F.register!
train
def register!(challenges, response) challenges = [challenges] unless challenges.is_a? Array challenge = challenges.detect do |chg| chg == response.client_data.challenge end raise UnmatchedChallengeError unless challenge raise ClientDataTypeError unless response.client_data.registration? # Validate public key U2F.public_key_pem(response.public_key_raw) raise AttestationSignatureError unless response.verify(app_id) Registration.new( response.key_handle, response.public_key, response.certificate ) end
ruby
{ "resource": "" }
q16487
U2F.SignResponse.verify
train
def verify(app_id, public_key_pem) data = [ ::U2F::DIGEST.digest(app_id), signature_data.byteslice(0, 5), ::U2F::DIGEST.digest(client_data_json) ].join public_key = OpenSSL::PKey.read(public_key_pem) begin public_key.verify(::U2F::DIGEST.new, signature, data) rescue OpenSSL::PKey::PKeyError false end end
ruby
{ "resource": "" }
q16488
U2F.RegisterResponse.verify
train
def verify(app_id) # Chapter 4.3 in # http://fidoalliance.org/specs/fido-u2f-raw-message-formats-v1.0-rd-20141008.pdf data = [ "\x00", ::U2F::DIGEST.digest(app_id), ::U2F::DIGEST.digest(client_data_json), key_handle_raw, public_key_raw ].join begin parsed_certificate.public_key.verify(::U2F::DIGEST.new, signature, data) rescue OpenSSL::PKey::PKeyError false end end
ruby
{ "resource": "" }
q16489
U2F.FakeU2F.register_response
train
def register_response(challenge, error = false) if error JSON.dump(errorCode: 4) else client_data_json = client_data(::U2F::ClientData::REGISTRATION_TYP, challenge) JSON.dump( registrationData: reg_registration_data(client_data_json), clientData: ::U2F.urlsafe_encode64(client_data_json) ) end end
ruby
{ "resource": "" }
q16490
U2F.FakeU2F.sign_response
train
def sign_response(challenge) client_data_json = client_data(::U2F::ClientData::AUTHENTICATION_TYP, challenge) JSON.dump( clientData: ::U2F.urlsafe_encode64(client_data_json), keyHandle: ::U2F.urlsafe_encode64(key_handle_raw), signatureData: auth_signature_data(client_data_json) ) end
ruby
{ "resource": "" }
q16491
U2F.FakeU2F.reg_registration_data
train
def reg_registration_data(client_data_json) ::U2F.urlsafe_encode64( [ 5, origin_public_key_raw, key_handle_raw.bytesize, key_handle_raw, cert_raw, reg_signature(client_data_json) ].pack("CA65CA#{key_handle_raw.bytesize}A#{cert_raw.bytesize}A*") ) end
ruby
{ "resource": "" }
q16492
U2F.FakeU2F.reg_signature
train
def reg_signature(client_data_json) payload = [ "\x00", ::U2F::DIGEST.digest(app_id), ::U2F::DIGEST.digest(client_data_json), key_handle_raw, origin_public_key_raw ].join cert_key.sign(::U2F::DIGEST.new, payload) end
ruby
{ "resource": "" }
q16493
U2F.FakeU2F.auth_signature
train
def auth_signature(client_data_json) data = [ ::U2F::DIGEST.digest(app_id), 1, # User present counter, ::U2F::DIGEST.digest(client_data_json) ].pack('A32CNA32') origin_key.sign(::U2F::DIGEST.new, data) end
ruby
{ "resource": "" }
q16494
U2F.FakeU2F.client_data
train
def client_data(typ, challenge) JSON.dump( challenge: challenge, origin: app_id, typ: typ ) end
ruby
{ "resource": "" }
q16495
U2F.FakeU2F.cert
train
def cert @cert ||= OpenSSL::X509::Certificate.new.tap do |c| c.subject = c.issuer = OpenSSL::X509::Name.parse(cert_subject) c.not_before = Time.now c.not_after = Time.now + 365 * 24 * 60 * 60 c.public_key = cert_key c.serial = 0x1 c.version = 0x0 c.sign cert_key, ::U2F::DIGEST.new end end
ruby
{ "resource": "" }
q16496
Fast.Rewriter.replace_on
train
def replace_on(*types) types.map do |type| self.class.send :define_method, "on_#{type}" do |node| if captures = match?(node) # rubocop:disable Lint/AssignmentInCondition @match_index += 1 execute_replacement(node, captures) end super(node) end end end
ruby
{ "resource": "" }
q16497
Fast.Matcher.captures?
train
def captures?(fast = @fast) case fast when Capture then true when Array then fast.any?(&method(:captures?)) when Find then captures?(fast.token) end end
ruby
{ "resource": "" }
q16498
Fast.Matcher.find_captures
train
def find_captures(fast = @fast) return true if fast == @fast && !captures?(fast) case fast when Capture then fast.captures when Array then fast.flat_map(&method(:find_captures)).compact when Find then find_captures(fast.token) end end
ruby
{ "resource": "" }
q16499
Fast.Matcher.prepare_arguments
train
def prepare_arguments(expression, arguments) case expression when Array expression.each do |item| prepare_arguments(item, arguments) end when Fast::FindFromArgument expression.arguments = arguments when Fast::Find prepare_arguments expression.token, arguments end end
ruby
{ "resource": "" }