{"repo": "travis-ci/travis.rb", "path": "lib/travis/cli.rb", "func_name": "Travis.CLI.preparse", "original_string": "def preparse(unparsed, args = [], opts = {})\n case unparsed\n when Hash then opts.merge! unparsed\n when Array then unparsed.each { |e| preparse(e, args, opts) }\n else args << unparsed.to_s\n end\n [args, opts]\n end", "language": "ruby", "code": "def preparse(unparsed, args = [], opts = {})\n case unparsed\n when Hash then opts.merge! unparsed\n when Array then unparsed.each { |e| preparse(e, args, opts) }\n else args << unparsed.to_s\n end\n [args, opts]\n end", "code_tokens": ["def", "preparse", "(", "unparsed", ",", "args", "=", "[", "]", ",", "opts", "=", "{", "}", ")", "case", "unparsed", "when", "Hash", "then", "opts", ".", "merge!", "unparsed", "when", "Array", "then", "unparsed", ".", "each", "{", "|", "e", "|", "preparse", "(", "e", ",", "args", ",", "opts", ")", "}", "else", "args", "<<", "unparsed", ".", "to_s", "end", "[", "args", ",", "opts", "]", "end"], "docstring": "can't use flatten as it will flatten hashes", "docstring_tokens": ["can", "t", "use", "flatten", "as", "it", "will", "flatten", "hashes"], "sha": "6547e3ad1393f508c679236a4b0e5403d2732043", "url": "https://github.com/travis-ci/travis.rb/blob/6547e3ad1393f508c679236a4b0e5403d2732043/lib/travis/cli.rb#L117-L124", "partition": "valid"}
{"repo": "github/scientist", "path": "lib/scientist/experiment.rb", "func_name": "Scientist::Experiment.MismatchError.to_s", "original_string": "def to_s\n super + \":\\n\" +\n format_observation(result.control) + \"\\n\" +\n result.candidates.map { |candidate| format_observation(candidate) }.join(\"\\n\") +\n \"\\n\"\n end", "language": "ruby", "code": "def to_s\n super + \":\\n\" +\n format_observation(result.control) + \"\\n\" +\n result.candidates.map { |candidate| format_observation(candidate) }.join(\"\\n\") +\n \"\\n\"\n end", "code_tokens": ["def", "to_s", "super", "+", "\":\\n\"", "+", "format_observation", "(", "result", ".", "control", ")", "+", "\"\\n\"", "+", "result", ".", "candidates", ".", "map", "{", "|", "candidate", "|", "format_observation", "(", "candidate", ")", "}", ".", "join", "(", "\"\\n\"", ")", "+", "\"\\n\"", "end"], "docstring": "The default formatting is nearly unreadable, so make it useful.\n\n The assumption here is that errors raised in a test environment are\n printed out as strings, rather than using #inspect.", "docstring_tokens": ["The", "default", "formatting", "is", "nearly", "unreadable", "so", "make", "it", "useful", "."], "sha": "25a22f733d4be523404b22ad818e520d20b57619", "url": "https://github.com/github/scientist/blob/25a22f733d4be523404b22ad818e520d20b57619/lib/scientist/experiment.rb#L34-L39", "partition": "valid"}
{"repo": "rest-client/rest-client", "path": "lib/restclient/request.rb", "func_name": "RestClient.Request.process_url_params", "original_string": "def process_url_params(url, headers)\n url_params = nil\n\n # find and extract/remove \"params\" key if the value is a Hash/ParamsArray\n headers.delete_if do |key, value|\n if key.to_s.downcase == 'params' &&\n (value.is_a?(Hash) || value.is_a?(RestClient::ParamsArray))\n if url_params\n raise ArgumentError.new(\"Multiple 'params' options passed\")\n end\n url_params = value\n true\n else\n false\n end\n end\n\n # build resulting URL with query string\n if url_params && !url_params.empty?\n query_string = RestClient::Utils.encode_query_string(url_params)\n\n if url.include?('?')\n url + '&' + query_string\n else\n url + '?' + query_string\n end\n else\n url\n end\n end", "language": "ruby", "code": "def process_url_params(url, headers)\n url_params = nil\n\n # find and extract/remove \"params\" key if the value is a Hash/ParamsArray\n headers.delete_if do |key, value|\n if key.to_s.downcase == 'params' &&\n (value.is_a?(Hash) || value.is_a?(RestClient::ParamsArray))\n if url_params\n raise ArgumentError.new(\"Multiple 'params' options passed\")\n end\n url_params = value\n true\n else\n false\n end\n end\n\n # build resulting URL with query string\n if url_params && !url_params.empty?\n query_string = RestClient::Utils.encode_query_string(url_params)\n\n if url.include?('?')\n url + '&' + query_string\n else\n url + '?' + query_string\n end\n else\n url\n end\n end", "code_tokens": ["def", "process_url_params", "(", "url", ",", "headers", ")", "url_params", "=", "nil", "headers", ".", "delete_if", "do", "|", "key", ",", "value", "|", "if", "key", ".", "to_s", ".", "downcase", "==", "'params'", "&&", "(", "value", ".", "is_a?", "(", "Hash", ")", "||", "value", ".", "is_a?", "(", "RestClient", "::", "ParamsArray", ")", ")", "if", "url_params", "raise", "ArgumentError", ".", "new", "(", "\"Multiple 'params' options passed\"", ")", "end", "url_params", "=", "value", "true", "else", "false", "end", "end", "if", "url_params", "&&", "!", "url_params", ".", "empty?", "query_string", "=", "RestClient", "::", "Utils", ".", "encode_query_string", "(", "url_params", ")", "if", "url", ".", "include?", "(", "'?'", ")", "url", "+", "'&'", "+", "query_string", "else", "url", "+", "'?'", "+", "query_string", "end", "else", "url", "end", "end"], "docstring": "Extract the query parameters and append them to the url\n\n Look through the headers hash for a :params option (case-insensitive,\n may be string or symbol). If present and the value is a Hash or\n RestClient::ParamsArray, *delete* the key/value pair from the headers\n hash and encode the value into a query string. Append this query string\n to the URL and return the resulting URL.\n\n @param [String] url\n @param [Hash] headers An options/headers hash to process. Mutation\n warning: the params key may be removed if present!\n\n @return [String] resulting url with query string", "docstring_tokens": ["Extract", "the", "query", "parameters", "and", "append", "them", "to", "the", "url"], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/request.rb#L195-L224", "partition": "valid"}
{"repo": "rest-client/rest-client", "path": "lib/restclient/request.rb", "func_name": "RestClient.Request.stringify_headers", "original_string": "def stringify_headers headers\n headers.inject({}) do |result, (key, value)|\n if key.is_a? Symbol\n key = key.to_s.split(/_/).map(&:capitalize).join('-')\n end\n if 'CONTENT-TYPE' == key.upcase\n result[key] = maybe_convert_extension(value.to_s)\n elsif 'ACCEPT' == key.upcase\n # Accept can be composed of several comma-separated values\n if value.is_a? Array\n target_values = value\n else\n target_values = value.to_s.split ','\n end\n result[key] = target_values.map { |ext|\n maybe_convert_extension(ext.to_s.strip)\n }.join(', ')\n else\n result[key] = value.to_s\n end\n result\n end\n end", "language": "ruby", "code": "def stringify_headers headers\n headers.inject({}) do |result, (key, value)|\n if key.is_a? Symbol\n key = key.to_s.split(/_/).map(&:capitalize).join('-')\n end\n if 'CONTENT-TYPE' == key.upcase\n result[key] = maybe_convert_extension(value.to_s)\n elsif 'ACCEPT' == key.upcase\n # Accept can be composed of several comma-separated values\n if value.is_a? Array\n target_values = value\n else\n target_values = value.to_s.split ','\n end\n result[key] = target_values.map { |ext|\n maybe_convert_extension(ext.to_s.strip)\n }.join(', ')\n else\n result[key] = value.to_s\n end\n result\n end\n end", "code_tokens": ["def", "stringify_headers", "headers", "headers", ".", "inject", "(", "{", "}", ")", "do", "|", "result", ",", "(", "key", ",", "value", ")", "|", "if", "key", ".", "is_a?", "Symbol", "key", "=", "key", ".", "to_s", ".", "split", "(", "/", "/", ")", ".", "map", "(", "&", ":capitalize", ")", ".", "join", "(", "'-'", ")", "end", "if", "'CONTENT-TYPE'", "==", "key", ".", "upcase", "result", "[", "key", "]", "=", "maybe_convert_extension", "(", "value", ".", "to_s", ")", "elsif", "'ACCEPT'", "==", "key", ".", "upcase", "if", "value", ".", "is_a?", "Array", "target_values", "=", "value", "else", "target_values", "=", "value", ".", "to_s", ".", "split", "','", "end", "result", "[", "key", "]", "=", "target_values", ".", "map", "{", "|", "ext", "|", "maybe_convert_extension", "(", "ext", ".", "to_s", ".", "strip", ")", "}", ".", "join", "(", "', '", ")", "else", "result", "[", "key", "]", "=", "value", ".", "to_s", "end", "result", "end", "end"], "docstring": "Return a hash of headers whose keys are capitalized strings\n\n BUG: stringify_headers does not fix the capitalization of headers that\n are already Strings. Leaving this behavior as is for now for\n backwards compatibility.\n https://github.com/rest-client/rest-client/issues/599", "docstring_tokens": ["Return", "a", "hash", "of", "headers", "whose", "keys", "are", "capitalized", "strings"], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/request.rb#L553-L575", "partition": "valid"}
{"repo": "rest-client/rest-client", "path": "lib/restclient/request.rb", "func_name": "RestClient.Request.maybe_convert_extension", "original_string": "def maybe_convert_extension(ext)\n unless ext =~ /\\A[a-zA-Z0-9_@-]+\\z/\n # Don't look up strings unless they look like they could be a file\n # extension known to mime-types.\n #\n # There currently isn't any API public way to look up extensions\n # directly out of MIME::Types, but the type_for() method only strips\n # off after a period anyway.\n return ext\n end\n\n types = MIME::Types.type_for(ext)\n if types.empty?\n ext\n else\n types.first.content_type\n end\n end", "language": "ruby", "code": "def maybe_convert_extension(ext)\n unless ext =~ /\\A[a-zA-Z0-9_@-]+\\z/\n # Don't look up strings unless they look like they could be a file\n # extension known to mime-types.\n #\n # There currently isn't any API public way to look up extensions\n # directly out of MIME::Types, but the type_for() method only strips\n # off after a period anyway.\n return ext\n end\n\n types = MIME::Types.type_for(ext)\n if types.empty?\n ext\n else\n types.first.content_type\n end\n end", "code_tokens": ["def", "maybe_convert_extension", "(", "ext", ")", "unless", "ext", "=~", "/", "\\A", "\\z", "/", "return", "ext", "end", "types", "=", "MIME", "::", "Types", ".", "type_for", "(", "ext", ")", "if", "types", ".", "empty?", "ext", "else", "types", ".", "first", ".", "content_type", "end", "end"], "docstring": "Given a MIME type or file extension, return either a MIME type or, if\n none is found, the input unchanged.\n\n >> maybe_convert_extension('json')\n => 'application/json'\n\n >> maybe_convert_extension('unknown')\n => 'unknown'\n\n >> maybe_convert_extension('application/xml')\n => 'application/xml'\n\n @param ext [String]\n\n @return [String]", "docstring_tokens": ["Given", "a", "MIME", "type", "or", "file", "extension", "return", "either", "a", "MIME", "type", "or", "if", "none", "is", "found", "the", "input", "unchanged", "."], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/request.rb#L856-L873", "partition": "valid"}
{"repo": "rest-client/rest-client", "path": "lib/restclient/resource.rb", "func_name": "RestClient.Resource.[]", "original_string": "def [](suburl, &new_block)\n case\n when block_given? then self.class.new(concat_urls(url, suburl), options, &new_block)\n when block then self.class.new(concat_urls(url, suburl), options, &block)\n else self.class.new(concat_urls(url, suburl), options)\n end\n end", "language": "ruby", "code": "def [](suburl, &new_block)\n case\n when block_given? then self.class.new(concat_urls(url, suburl), options, &new_block)\n when block then self.class.new(concat_urls(url, suburl), options, &block)\n else self.class.new(concat_urls(url, suburl), options)\n end\n end", "code_tokens": ["def", "[]", "(", "suburl", ",", "&", "new_block", ")", "case", "when", "block_given?", "then", "self", ".", "class", ".", "new", "(", "concat_urls", "(", "url", ",", "suburl", ")", ",", "options", ",", "&", "new_block", ")", "when", "block", "then", "self", ".", "class", ".", "new", "(", "concat_urls", "(", "url", ",", "suburl", ")", ",", "options", ",", "&", "block", ")", "else", "self", ".", "class", ".", "new", "(", "concat_urls", "(", "url", ",", "suburl", ")", ",", "options", ")", "end", "end"], "docstring": "Construct a subresource, preserving authentication.\n\n Example:\n\n site = RestClient::Resource.new('http://example.com', 'adam', 'mypasswd')\n site['posts/1/comments'].post 'Good article.', :content_type => 'text/plain'\n\n This is especially useful if you wish to define your site in one place and\n call it in multiple locations:\n\n def orders\n RestClient::Resource.new('http://example.com/orders', 'admin', 'mypasswd')\n end\n\n orders.get # GET http://example.com/orders\n orders['1'].get # GET http://example.com/orders/1\n orders['1/items'].delete # DELETE http://example.com/orders/1/items\n\n Nest resources as far as you want:\n\n site = RestClient::Resource.new('http://example.com')\n posts = site['posts']\n first_post = posts['1']\n comments = first_post['comments']\n comments.post 'Hello', :content_type => 'text/plain'", "docstring_tokens": ["Construct", "a", "subresource", "preserving", "authentication", "."], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/resource.rb#L160-L166", "partition": "valid"}
{"repo": "rest-client/rest-client", "path": "lib/restclient/abstract_response.rb", "func_name": "RestClient.AbstractResponse.cookies", "original_string": "def cookies\n hash = {}\n\n cookie_jar.cookies(@request.uri).each do |cookie|\n hash[cookie.name] = cookie.value\n end\n\n hash\n end", "language": "ruby", "code": "def cookies\n hash = {}\n\n cookie_jar.cookies(@request.uri).each do |cookie|\n hash[cookie.name] = cookie.value\n end\n\n hash\n end", "code_tokens": ["def", "cookies", "hash", "=", "{", "}", "cookie_jar", ".", "cookies", "(", "@request", ".", "uri", ")", ".", "each", "do", "|", "cookie", "|", "hash", "[", "cookie", ".", "name", "]", "=", "cookie", ".", "value", "end", "hash", "end"], "docstring": "Hash of cookies extracted from response headers.\n\n NB: This will return only cookies whose domain matches this request, and\n may not even return all of those cookies if there are duplicate names.\n Use the full cookie_jar for more nuanced access.\n\n @see #cookie_jar\n\n @return [Hash]", "docstring_tokens": ["Hash", "of", "cookies", "extracted", "from", "response", "headers", "."], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/abstract_response.rb#L78-L86", "partition": "valid"}
{"repo": "rest-client/rest-client", "path": "lib/restclient/abstract_response.rb", "func_name": "RestClient.AbstractResponse.cookie_jar", "original_string": "def cookie_jar\n return @cookie_jar if defined?(@cookie_jar) && @cookie_jar\n\n jar = @request.cookie_jar.dup\n headers.fetch(:set_cookie, []).each do |cookie|\n jar.parse(cookie, @request.uri)\n end\n\n @cookie_jar = jar\n end", "language": "ruby", "code": "def cookie_jar\n return @cookie_jar if defined?(@cookie_jar) && @cookie_jar\n\n jar = @request.cookie_jar.dup\n headers.fetch(:set_cookie, []).each do |cookie|\n jar.parse(cookie, @request.uri)\n end\n\n @cookie_jar = jar\n end", "code_tokens": ["def", "cookie_jar", "return", "@cookie_jar", "if", "defined?", "(", "@cookie_jar", ")", "&&", "@cookie_jar", "jar", "=", "@request", ".", "cookie_jar", ".", "dup", "headers", ".", "fetch", "(", ":set_cookie", ",", "[", "]", ")", ".", "each", "do", "|", "cookie", "|", "jar", ".", "parse", "(", "cookie", ",", "@request", ".", "uri", ")", "end", "@cookie_jar", "=", "jar", "end"], "docstring": "Cookie jar extracted from response headers.\n\n @return [HTTP::CookieJar]", "docstring_tokens": ["Cookie", "jar", "extracted", "from", "response", "headers", "."], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/abstract_response.rb#L92-L101", "partition": "valid"}
{"repo": "rest-client/rest-client", "path": "lib/restclient/abstract_response.rb", "func_name": "RestClient.AbstractResponse.follow_get_redirection", "original_string": "def follow_get_redirection(&block)\n new_args = request.args.dup\n new_args[:method] = :get\n new_args.delete(:payload)\n\n _follow_redirection(new_args, &block)\n end", "language": "ruby", "code": "def follow_get_redirection(&block)\n new_args = request.args.dup\n new_args[:method] = :get\n new_args.delete(:payload)\n\n _follow_redirection(new_args, &block)\n end", "code_tokens": ["def", "follow_get_redirection", "(", "&", "block", ")", "new_args", "=", "request", ".", "args", ".", "dup", "new_args", "[", ":method", "]", "=", ":get", "new_args", ".", "delete", "(", ":payload", ")", "_follow_redirection", "(", "new_args", ",", "&", "block", ")", "end"], "docstring": "Follow a redirection response, but change the HTTP method to GET and drop\n the payload from the original request.", "docstring_tokens": ["Follow", "a", "redirection", "response", "but", "change", "the", "HTTP", "method", "to", "GET", "and", "drop", "the", "payload", "from", "the", "original", "request", "."], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/abstract_response.rb#L150-L156", "partition": "valid"}
{"repo": "rest-client/rest-client", "path": "lib/restclient/abstract_response.rb", "func_name": "RestClient.AbstractResponse._follow_redirection", "original_string": "def _follow_redirection(new_args, &block)\n\n # parse location header and merge into existing URL\n url = headers[:location]\n\n # cannot follow redirection if there is no location header\n unless url\n raise exception_with_response\n end\n\n # handle relative redirects\n unless url.start_with?('http')\n url = URI.parse(request.url).merge(url).to_s\n end\n new_args[:url] = url\n\n new_args[:password] = request.password\n new_args[:user] = request.user\n new_args[:headers] = request.headers\n new_args[:max_redirects] = request.max_redirects - 1\n\n # pass through our new cookie jar\n new_args[:cookies] = cookie_jar\n\n # prepare new request\n new_req = Request.new(new_args)\n\n # append self to redirection history\n new_req.redirection_history = history + [self]\n\n # execute redirected request\n new_req.execute(&block)\n end", "language": "ruby", "code": "def _follow_redirection(new_args, &block)\n\n # parse location header and merge into existing URL\n url = headers[:location]\n\n # cannot follow redirection if there is no location header\n unless url\n raise exception_with_response\n end\n\n # handle relative redirects\n unless url.start_with?('http')\n url = URI.parse(request.url).merge(url).to_s\n end\n new_args[:url] = url\n\n new_args[:password] = request.password\n new_args[:user] = request.user\n new_args[:headers] = request.headers\n new_args[:max_redirects] = request.max_redirects - 1\n\n # pass through our new cookie jar\n new_args[:cookies] = cookie_jar\n\n # prepare new request\n new_req = Request.new(new_args)\n\n # append self to redirection history\n new_req.redirection_history = history + [self]\n\n # execute redirected request\n new_req.execute(&block)\n end", "code_tokens": ["def", "_follow_redirection", "(", "new_args", ",", "&", "block", ")", "url", "=", "headers", "[", ":location", "]", "unless", "url", "raise", "exception_with_response", "end", "unless", "url", ".", "start_with?", "(", "'http'", ")", "url", "=", "URI", ".", "parse", "(", "request", ".", "url", ")", ".", "merge", "(", "url", ")", ".", "to_s", "end", "new_args", "[", ":url", "]", "=", "url", "new_args", "[", ":password", "]", "=", "request", ".", "password", "new_args", "[", ":user", "]", "=", "request", ".", "user", "new_args", "[", ":headers", "]", "=", "request", ".", "headers", "new_args", "[", ":max_redirects", "]", "=", "request", ".", "max_redirects", "-", "1", "new_args", "[", ":cookies", "]", "=", "cookie_jar", "new_req", "=", "Request", ".", "new", "(", "new_args", ")", "new_req", ".", "redirection_history", "=", "history", "+", "[", "self", "]", "new_req", ".", "execute", "(", "&", "block", ")", "end"], "docstring": "Follow a redirection\n\n @param new_args [Hash] Start with this hash of arguments for the\n redirection request. The hash will be mutated, so be sure to dup any\n existing hash that should not be modified.", "docstring_tokens": ["Follow", "a", "redirection"], "sha": "f450a0f086f1cd1049abbef2a2c66166a1a9ba71", "url": "https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/abstract_response.rb#L202-L234", "partition": "valid"}
{"repo": "omniauth/omniauth", "path": "lib/omniauth/strategy.rb", "func_name": "OmniAuth.Strategy.call!", "original_string": "def call!(env) # rubocop:disable CyclomaticComplexity, PerceivedComplexity\n unless env['rack.session']\n error = OmniAuth::NoSessionError.new('You must provide a session to use OmniAuth.')\n raise(error)\n end\n\n @env = env\n @env['omniauth.strategy'] = self if on_auth_path?\n\n return mock_call!(env) if OmniAuth.config.test_mode\n return options_call if on_auth_path? && options_request?\n return request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym)\n return callback_call if on_callback_path?\n return other_phase if respond_to?(:other_phase)\n\n @app.call(env)\n end", "language": "ruby", "code": "def call!(env) # rubocop:disable CyclomaticComplexity, PerceivedComplexity\n unless env['rack.session']\n error = OmniAuth::NoSessionError.new('You must provide a session to use OmniAuth.')\n raise(error)\n end\n\n @env = env\n @env['omniauth.strategy'] = self if on_auth_path?\n\n return mock_call!(env) if OmniAuth.config.test_mode\n return options_call if on_auth_path? && options_request?\n return request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym)\n return callback_call if on_callback_path?\n return other_phase if respond_to?(:other_phase)\n\n @app.call(env)\n end", "code_tokens": ["def", "call!", "(", "env", ")", "unless", "env", "[", "'rack.session'", "]", "error", "=", "OmniAuth", "::", "NoSessionError", ".", "new", "(", "'You must provide a session to use OmniAuth.'", ")", "raise", "(", "error", ")", "end", "@env", "=", "env", "@env", "[", "'omniauth.strategy'", "]", "=", "self", "if", "on_auth_path?", "return", "mock_call!", "(", "env", ")", "if", "OmniAuth", ".", "config", ".", "test_mode", "return", "options_call", "if", "on_auth_path?", "&&", "options_request?", "return", "request_call", "if", "on_request_path?", "&&", "OmniAuth", ".", "config", ".", "allowed_request_methods", ".", "include?", "(", "request", ".", "request_method", ".", "downcase", ".", "to_sym", ")", "return", "callback_call", "if", "on_callback_path?", "return", "other_phase", "if", "respond_to?", "(", ":other_phase", ")", "@app", ".", "call", "(", "env", ")", "end"], "docstring": "The logic for dispatching any additional actions that need\n to be taken. For instance, calling the request phase if\n the request path is recognized.\n\n @param env [Hash] The Rack environment.", "docstring_tokens": ["The", "logic", "for", "dispatching", "any", "additional", "actions", "that", "need", "to", "be", "taken", ".", "For", "instance", "calling", "the", "request", "phase", "if", "the", "request", "path", "is", "recognized", "."], "sha": "cc0f5522621b4a372f4dff0aa608822aa082cb60", "url": "https://github.com/omniauth/omniauth/blob/cc0f5522621b4a372f4dff0aa608822aa082cb60/lib/omniauth/strategy.rb#L177-L193", "partition": "valid"}
{"repo": "omniauth/omniauth", "path": "lib/omniauth/strategy.rb", "func_name": "OmniAuth.Strategy.options_call", "original_string": "def options_call\n OmniAuth.config.before_options_phase.call(env) if OmniAuth.config.before_options_phase\n verbs = OmniAuth.config.allowed_request_methods.collect(&:to_s).collect(&:upcase).join(', ')\n [200, {'Allow' => verbs}, []]\n end", "language": "ruby", "code": "def options_call\n OmniAuth.config.before_options_phase.call(env) if OmniAuth.config.before_options_phase\n verbs = OmniAuth.config.allowed_request_methods.collect(&:to_s).collect(&:upcase).join(', ')\n [200, {'Allow' => verbs}, []]\n end", "code_tokens": ["def", "options_call", "OmniAuth", ".", "config", ".", "before_options_phase", ".", "call", "(", "env", ")", "if", "OmniAuth", ".", "config", ".", "before_options_phase", "verbs", "=", "OmniAuth", ".", "config", ".", "allowed_request_methods", ".", "collect", "(", "&", ":to_s", ")", ".", "collect", "(", "&", ":upcase", ")", ".", "join", "(", "', '", ")", "[", "200", ",", "{", "'Allow'", "=>", "verbs", "}", ",", "[", "]", "]", "end"], "docstring": "Responds to an OPTIONS request.", "docstring_tokens": ["Responds", "to", "an", "OPTIONS", "request", "."], "sha": "cc0f5522621b4a372f4dff0aa608822aa082cb60", "url": "https://github.com/omniauth/omniauth/blob/cc0f5522621b4a372f4dff0aa608822aa082cb60/lib/omniauth/strategy.rb#L196-L200", "partition": "valid"}
{"repo": "omniauth/omniauth", "path": "lib/omniauth/strategy.rb", "func_name": "OmniAuth.Strategy.callback_call", "original_string": "def callback_call\n setup_phase\n log :info, 'Callback phase initiated.'\n @env['omniauth.origin'] = session.delete('omniauth.origin')\n @env['omniauth.origin'] = nil if env['omniauth.origin'] == ''\n @env['omniauth.params'] = session.delete('omniauth.params') || {}\n OmniAuth.config.before_callback_phase.call(@env) if OmniAuth.config.before_callback_phase\n callback_phase\n end", "language": "ruby", "code": "def callback_call\n setup_phase\n log :info, 'Callback phase initiated.'\n @env['omniauth.origin'] = session.delete('omniauth.origin')\n @env['omniauth.origin'] = nil if env['omniauth.origin'] == ''\n @env['omniauth.params'] = session.delete('omniauth.params') || {}\n OmniAuth.config.before_callback_phase.call(@env) if OmniAuth.config.before_callback_phase\n callback_phase\n end", "code_tokens": ["def", "callback_call", "setup_phase", "log", ":info", ",", "'Callback phase initiated.'", "@env", "[", "'omniauth.origin'", "]", "=", "session", ".", "delete", "(", "'omniauth.origin'", ")", "@env", "[", "'omniauth.origin'", "]", "=", "nil", "if", "env", "[", "'omniauth.origin'", "]", "==", "''", "@env", "[", "'omniauth.params'", "]", "=", "session", ".", "delete", "(", "'omniauth.params'", ")", "||", "{", "}", "OmniAuth", ".", "config", ".", "before_callback_phase", ".", "call", "(", "@env", ")", "if", "OmniAuth", ".", "config", ".", "before_callback_phase", "callback_phase", "end"], "docstring": "Performs the steps necessary to run the callback phase of a strategy.", "docstring_tokens": ["Performs", "the", "steps", "necessary", "to", "run", "the", "callback", "phase", "of", "a", "strategy", "."], "sha": "cc0f5522621b4a372f4dff0aa608822aa082cb60", "url": "https://github.com/omniauth/omniauth/blob/cc0f5522621b4a372f4dff0aa608822aa082cb60/lib/omniauth/strategy.rb#L231-L239", "partition": "valid"}
{"repo": "omniauth/omniauth", "path": "lib/omniauth/strategy.rb", "func_name": "OmniAuth.Strategy.mock_call!", "original_string": "def mock_call!(*)\n return mock_request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym)\n return mock_callback_call if on_callback_path?\n\n call_app!\n end", "language": "ruby", "code": "def mock_call!(*)\n return mock_request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym)\n return mock_callback_call if on_callback_path?\n\n call_app!\n end", "code_tokens": ["def", "mock_call!", "(", "*", ")", "return", "mock_request_call", "if", "on_request_path?", "&&", "OmniAuth", ".", "config", ".", "allowed_request_methods", ".", "include?", "(", "request", ".", "request_method", ".", "downcase", ".", "to_sym", ")", "return", "mock_callback_call", "if", "on_callback_path?", "call_app!", "end"], "docstring": "This is called in lieu of the normal request process\n in the event that OmniAuth has been configured to be\n in test mode.", "docstring_tokens": ["This", "is", "called", "in", "lieu", "of", "the", "normal", "request", "process", "in", "the", "event", "that", "OmniAuth", "has", "been", "configured", "to", "be", "in", "test", "mode", "."], "sha": "cc0f5522621b4a372f4dff0aa608822aa082cb60", "url": "https://github.com/omniauth/omniauth/blob/cc0f5522621b4a372f4dff0aa608822aa082cb60/lib/omniauth/strategy.rb#L270-L275", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_savon/lib/ads_savon/model.rb", "func_name": "GoogleAdsSavon.Model.instance_action_module", "original_string": "def instance_action_module\n @instance_action_module ||= Module.new do\n\n # Returns the GoogleAdsSavon::Client from the class instance.\n def client(&block)\n self.class.client(&block)\n end\n\n end.tap { |mod| include(mod) }\n end", "language": "ruby", "code": "def instance_action_module\n @instance_action_module ||= Module.new do\n\n # Returns the GoogleAdsSavon::Client from the class instance.\n def client(&block)\n self.class.client(&block)\n end\n\n end.tap { |mod| include(mod) }\n end", "code_tokens": ["def", "instance_action_module", "@instance_action_module", "||=", "Module", ".", "new", "do", "def", "client", "(", "&", "block", ")", "self", ".", "class", ".", "client", "(", "&", "block", ")", "end", "end", ".", "tap", "{", "|", "mod", "|", "include", "(", "mod", ")", "}", "end"], "docstring": "Instance methods.", "docstring_tokens": ["Instance", "methods", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_savon/lib/ads_savon/model.rb#L90-L99", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api.rb", "func_name": "AdwordsApi.Api.soap_header_handler", "original_string": "def soap_header_handler(auth_handler, version, header_ns, default_ns)\n auth_method = @config.read('authentication.method', :OAUTH2)\n handler_class = case auth_method\n when :OAUTH2, :OAUTH2_SERVICE_ACCOUNT\n AdsCommon::SavonHeaders::OAuthHeaderHandler\n else\n raise AdsCommon::Errors::AuthError,\n \"Unknown auth method: %s\" % auth_method\n end\n return handler_class.new(@credential_handler, auth_handler, header_ns,\n default_ns, version)\n end", "language": "ruby", "code": "def soap_header_handler(auth_handler, version, header_ns, default_ns)\n auth_method = @config.read('authentication.method', :OAUTH2)\n handler_class = case auth_method\n when :OAUTH2, :OAUTH2_SERVICE_ACCOUNT\n AdsCommon::SavonHeaders::OAuthHeaderHandler\n else\n raise AdsCommon::Errors::AuthError,\n \"Unknown auth method: %s\" % auth_method\n end\n return handler_class.new(@credential_handler, auth_handler, header_ns,\n default_ns, version)\n end", "code_tokens": ["def", "soap_header_handler", "(", "auth_handler", ",", "version", ",", "header_ns", ",", "default_ns", ")", "auth_method", "=", "@config", ".", "read", "(", "'authentication.method'", ",", ":OAUTH2", ")", "handler_class", "=", "case", "auth_method", "when", ":OAUTH2", ",", ":OAUTH2_SERVICE_ACCOUNT", "AdsCommon", "::", "SavonHeaders", "::", "OAuthHeaderHandler", "else", "raise", "AdsCommon", "::", "Errors", "::", "AuthError", ",", "\"Unknown auth method: %s\"", "%", "auth_method", "end", "return", "handler_class", ".", "new", "(", "@credential_handler", ",", "auth_handler", ",", "header_ns", ",", "default_ns", ",", "version", ")", "end"], "docstring": "Retrieve correct soap_header_handler.\n\n Args:\n - auth_handler: instance of an AdsCommon::Auth::BaseHandler subclass to\n handle authentication\n - version: intended API version\n - header_ns: header namespace\n - default_ns: default namespace\n\n Returns:\n - SOAP header handler", "docstring_tokens": ["Retrieve", "correct", "soap_header_handler", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api.rb#L66-L77", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api.rb", "func_name": "AdwordsApi.Api.report_utils", "original_string": "def report_utils(version = nil)\n version = api_config.default_version if version.nil?\n # Check if version exists.\n if !api_config.versions.include?(version)\n raise AdsCommon::Errors::Error, \"Unknown version '%s'\" % version\n end\n return AdwordsApi::ReportUtils.new(self, version)\n end", "language": "ruby", "code": "def report_utils(version = nil)\n version = api_config.default_version if version.nil?\n # Check if version exists.\n if !api_config.versions.include?(version)\n raise AdsCommon::Errors::Error, \"Unknown version '%s'\" % version\n end\n return AdwordsApi::ReportUtils.new(self, version)\n end", "code_tokens": ["def", "report_utils", "(", "version", "=", "nil", ")", "version", "=", "api_config", ".", "default_version", "if", "version", ".", "nil?", "if", "!", "api_config", ".", "versions", ".", "include?", "(", "version", ")", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Unknown version '%s'\"", "%", "version", "end", "return", "AdwordsApi", "::", "ReportUtils", ".", "new", "(", "self", ",", "version", ")", "end"], "docstring": "Returns an instance of ReportUtils object with all utilities relevant to\n the reporting.\n\n Args:\n - version: version of the API to use (optional).", "docstring_tokens": ["Returns", "an", "instance", "of", "ReportUtils", "object", "with", "all", "utilities", "relevant", "to", "the", "reporting", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api.rb#L187-L194", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api.rb", "func_name": "AdwordsApi.Api.batch_job_utils", "original_string": "def batch_job_utils(version = nil)\n version = api_config.default_version if version.nil?\n # Check if version exists.\n if !api_config.versions.include?(version)\n raise AdsCommon::Errors::Error, \"Unknown version '%s'\" % version\n end\n return AdwordsApi::BatchJobUtils.new(self, version)\n end", "language": "ruby", "code": "def batch_job_utils(version = nil)\n version = api_config.default_version if version.nil?\n # Check if version exists.\n if !api_config.versions.include?(version)\n raise AdsCommon::Errors::Error, \"Unknown version '%s'\" % version\n end\n return AdwordsApi::BatchJobUtils.new(self, version)\n end", "code_tokens": ["def", "batch_job_utils", "(", "version", "=", "nil", ")", "version", "=", "api_config", ".", "default_version", "if", "version", ".", "nil?", "if", "!", "api_config", ".", "versions", ".", "include?", "(", "version", ")", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Unknown version '%s'\"", "%", "version", "end", "return", "AdwordsApi", "::", "BatchJobUtils", ".", "new", "(", "self", ",", "version", ")", "end"], "docstring": "Returns an instance of BatchJobUtils object with all utilities relevant\n to running batch jobs.\n\n Args:\n - version: version of the API to use (optional).", "docstring_tokens": ["Returns", "an", "instance", "of", "BatchJobUtils", "object", "with", "all", "utilities", "relevant", "to", "running", "batch", "jobs", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api.rb#L202-L209", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api.rb", "func_name": "AdwordsApi.Api.run_with_temporary_flag", "original_string": "def run_with_temporary_flag(flag_name, flag_value, block)\n previous = @credential_handler.instance_variable_get(flag_name)\n @credential_handler.instance_variable_set(flag_name, flag_value)\n begin\n return block.call\n ensure\n @credential_handler.instance_variable_set(flag_name, previous)\n end\n end", "language": "ruby", "code": "def run_with_temporary_flag(flag_name, flag_value, block)\n previous = @credential_handler.instance_variable_get(flag_name)\n @credential_handler.instance_variable_set(flag_name, flag_value)\n begin\n return block.call\n ensure\n @credential_handler.instance_variable_set(flag_name, previous)\n end\n end", "code_tokens": ["def", "run_with_temporary_flag", "(", "flag_name", ",", "flag_value", ",", "block", ")", "previous", "=", "@credential_handler", ".", "instance_variable_get", "(", "flag_name", ")", "@credential_handler", ".", "instance_variable_set", "(", "flag_name", ",", "flag_value", ")", "begin", "return", "block", ".", "call", "ensure", "@credential_handler", ".", "instance_variable_set", "(", "flag_name", ",", "previous", ")", "end", "end"], "docstring": "Executes block with a temporary flag set to a given value. Returns block\n result.", "docstring_tokens": ["Executes", "block", "with", "a", "temporary", "flag", "set", "to", "a", "given", "value", ".", "Returns", "block", "result", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api.rb#L227-L235", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.validate_arguments", "original_string": "def validate_arguments(args_hash, fields_list, type_ns = nil)\n check_extra_fields(args_hash, array_from_named_list(fields_list))\n add_order_key(args_hash, fields_list)\n fields_list.each do |field|\n key = field[:name]\n item = args_hash[key]\n check_required_argument_present(item, field)\n unless item.nil?\n original_name = field[:original_name]\n if original_name\n key = handle_name_override(args_hash, key, original_name)\n end\n\n item_type = get_full_type_signature(field[:type])\n item_ns = field[:ns] || type_ns\n key = handle_namespace_override(args_hash, key, item_ns) if item_ns\n\n # Separate validation for choice types as we need to inject nodes into\n # the tree. Validate as usual if not a choice type.\n unless validate_choice_argument(item, args_hash, key, item_type)\n validate_arg(item, args_hash, key, item_type)\n end\n end\n end\n return args_hash\n end", "language": "ruby", "code": "def validate_arguments(args_hash, fields_list, type_ns = nil)\n check_extra_fields(args_hash, array_from_named_list(fields_list))\n add_order_key(args_hash, fields_list)\n fields_list.each do |field|\n key = field[:name]\n item = args_hash[key]\n check_required_argument_present(item, field)\n unless item.nil?\n original_name = field[:original_name]\n if original_name\n key = handle_name_override(args_hash, key, original_name)\n end\n\n item_type = get_full_type_signature(field[:type])\n item_ns = field[:ns] || type_ns\n key = handle_namespace_override(args_hash, key, item_ns) if item_ns\n\n # Separate validation for choice types as we need to inject nodes into\n # the tree. Validate as usual if not a choice type.\n unless validate_choice_argument(item, args_hash, key, item_type)\n validate_arg(item, args_hash, key, item_type)\n end\n end\n end\n return args_hash\n end", "code_tokens": ["def", "validate_arguments", "(", "args_hash", ",", "fields_list", ",", "type_ns", "=", "nil", ")", "check_extra_fields", "(", "args_hash", ",", "array_from_named_list", "(", "fields_list", ")", ")", "add_order_key", "(", "args_hash", ",", "fields_list", ")", "fields_list", ".", "each", "do", "|", "field", "|", "key", "=", "field", "[", ":name", "]", "item", "=", "args_hash", "[", "key", "]", "check_required_argument_present", "(", "item", ",", "field", ")", "unless", "item", ".", "nil?", "original_name", "=", "field", "[", ":original_name", "]", "if", "original_name", "key", "=", "handle_name_override", "(", "args_hash", ",", "key", ",", "original_name", ")", "end", "item_type", "=", "get_full_type_signature", "(", "field", "[", ":type", "]", ")", "item_ns", "=", "field", "[", ":ns", "]", "||", "type_ns", "key", "=", "handle_namespace_override", "(", "args_hash", ",", "key", ",", "item_ns", ")", "if", "item_ns", "unless", "validate_choice_argument", "(", "item", ",", "args_hash", ",", "key", ",", "item_type", ")", "validate_arg", "(", "item", ",", "args_hash", ",", "key", ",", "item_type", ")", "end", "end", "end", "return", "args_hash", "end"], "docstring": "Validates given arguments based on provided fields list.", "docstring_tokens": ["Validates", "given", "arguments", "based", "on", "provided", "fields", "list", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L58-L83", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.validate_choice_argument", "original_string": "def validate_choice_argument(item, parent, key, item_type)\n result = false\n if item_type.kind_of?(Hash) && item_type.include?(:choices)\n # If we have an array of choices, we need to go over them individually.\n # We drop original array and replace it with the generated one that's\n # nested one level more.\n if item.kind_of?(Array)\n parent[key] = []\n item.each do |sub_item|\n unless validate_choice_argument(sub_item, parent, key, item_type)\n validate_arg(sub_item, parent, key, item_type)\n end\n end\n return true\n end\n # New root needed for extra nesting we have (choice field).\n new_root = {}\n choice_items = arrayize(item)\n choice_items.each do |choice_item|\n choice_type = choice_item.delete(:xsi_type)\n choice_item_type =\n find_choice_by_xsi_type(choice_type, item_type[:choices])\n if choice_type.nil? || choice_item_type.nil?\n raise AdsCommon::Errors::TypeMismatchError.new(\n 'choice subtype', choice_type, choice_item.to_s())\n end\n choice_item[:xsi_type] = choice_type\n # Note we use original name that produces a string like\n # \"BasicUserList\". That's needed as the name is generated out of\n # standard naming (\"basicUserList\") which would otherwise be produced.\n choice_key = choice_item_type[:original_name]\n new_root[choice_key] = choice_item\n type_signature = get_full_type_signature(choice_type)\n validate_arg(choice_item, new_root, choice_key, type_signature)\n end\n if parent[key].kind_of?(Array)\n parent[key] << new_root\n else\n parent[key] = new_root\n end\n result = true\n end\n return result\n end", "language": "ruby", "code": "def validate_choice_argument(item, parent, key, item_type)\n result = false\n if item_type.kind_of?(Hash) && item_type.include?(:choices)\n # If we have an array of choices, we need to go over them individually.\n # We drop original array and replace it with the generated one that's\n # nested one level more.\n if item.kind_of?(Array)\n parent[key] = []\n item.each do |sub_item|\n unless validate_choice_argument(sub_item, parent, key, item_type)\n validate_arg(sub_item, parent, key, item_type)\n end\n end\n return true\n end\n # New root needed for extra nesting we have (choice field).\n new_root = {}\n choice_items = arrayize(item)\n choice_items.each do |choice_item|\n choice_type = choice_item.delete(:xsi_type)\n choice_item_type =\n find_choice_by_xsi_type(choice_type, item_type[:choices])\n if choice_type.nil? || choice_item_type.nil?\n raise AdsCommon::Errors::TypeMismatchError.new(\n 'choice subtype', choice_type, choice_item.to_s())\n end\n choice_item[:xsi_type] = choice_type\n # Note we use original name that produces a string like\n # \"BasicUserList\". That's needed as the name is generated out of\n # standard naming (\"basicUserList\") which would otherwise be produced.\n choice_key = choice_item_type[:original_name]\n new_root[choice_key] = choice_item\n type_signature = get_full_type_signature(choice_type)\n validate_arg(choice_item, new_root, choice_key, type_signature)\n end\n if parent[key].kind_of?(Array)\n parent[key] << new_root\n else\n parent[key] = new_root\n end\n result = true\n end\n return result\n end", "code_tokens": ["def", "validate_choice_argument", "(", "item", ",", "parent", ",", "key", ",", "item_type", ")", "result", "=", "false", "if", "item_type", ".", "kind_of?", "(", "Hash", ")", "&&", "item_type", ".", "include?", "(", ":choices", ")", "if", "item", ".", "kind_of?", "(", "Array", ")", "parent", "[", "key", "]", "=", "[", "]", "item", ".", "each", "do", "|", "sub_item", "|", "unless", "validate_choice_argument", "(", "sub_item", ",", "parent", ",", "key", ",", "item_type", ")", "validate_arg", "(", "sub_item", ",", "parent", ",", "key", ",", "item_type", ")", "end", "end", "return", "true", "end", "new_root", "=", "{", "}", "choice_items", "=", "arrayize", "(", "item", ")", "choice_items", ".", "each", "do", "|", "choice_item", "|", "choice_type", "=", "choice_item", ".", "delete", "(", ":xsi_type", ")", "choice_item_type", "=", "find_choice_by_xsi_type", "(", "choice_type", ",", "item_type", "[", ":choices", "]", ")", "if", "choice_type", ".", "nil?", "||", "choice_item_type", ".", "nil?", "raise", "AdsCommon", "::", "Errors", "::", "TypeMismatchError", ".", "new", "(", "'choice subtype'", ",", "choice_type", ",", "choice_item", ".", "to_s", "(", ")", ")", "end", "choice_item", "[", ":xsi_type", "]", "=", "choice_type", "choice_key", "=", "choice_item_type", "[", ":original_name", "]", "new_root", "[", "choice_key", "]", "=", "choice_item", "type_signature", "=", "get_full_type_signature", "(", "choice_type", ")", "validate_arg", "(", "choice_item", ",", "new_root", ",", "choice_key", ",", "type_signature", ")", "end", "if", "parent", "[", "key", "]", ".", "kind_of?", "(", "Array", ")", "parent", "[", "key", "]", "<<", "new_root", "else", "parent", "[", "key", "]", "=", "new_root", "end", "result", "=", "true", "end", "return", "result", "end"], "docstring": "Special handling for choice types. Goes over each item, checks xsi_type\n is set and correct and injects new node for it into the tree. After that,\n recurces with the correct item type.", "docstring_tokens": ["Special", "handling", "for", "choice", "types", ".", "Goes", "over", "each", "item", "checks", "xsi_type", "is", "set", "and", "correct", "and", "injects", "new", "node", "for", "it", "into", "the", "tree", ".", "After", "that", "recurces", "with", "the", "correct", "item", "type", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L88-L131", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.check_extra_fields", "original_string": "def check_extra_fields(args_hash, known_fields)\n extra_fields = args_hash.keys - known_fields - IGNORED_HASH_KEYS\n unless extra_fields.empty?\n raise AdsCommon::Errors::UnexpectedParametersError.new(extra_fields)\n end\n end", "language": "ruby", "code": "def check_extra_fields(args_hash, known_fields)\n extra_fields = args_hash.keys - known_fields - IGNORED_HASH_KEYS\n unless extra_fields.empty?\n raise AdsCommon::Errors::UnexpectedParametersError.new(extra_fields)\n end\n end", "code_tokens": ["def", "check_extra_fields", "(", "args_hash", ",", "known_fields", ")", "extra_fields", "=", "args_hash", ".", "keys", "-", "known_fields", "-", "IGNORED_HASH_KEYS", "unless", "extra_fields", ".", "empty?", "raise", "AdsCommon", "::", "Errors", "::", "UnexpectedParametersError", ".", "new", "(", "extra_fields", ")", "end", "end"], "docstring": "Checks if no extra fields provided outside of known ones.", "docstring_tokens": ["Checks", "if", "no", "extra", "fields", "provided", "outside", "of", "known", "ones", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L153-L158", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.check_required_argument_present", "original_string": "def check_required_argument_present(arg, field)\n # At least one item required, none passed.\n if field[:min_occurs] > 0 and arg.nil?\n raise AdsCommon::Errors::MissingPropertyError.new(\n field[:name], field[:type])\n end\n # An object passed when an array is expected.\n if (field[:max_occurs] == :unbounded) and\n !(arg.nil? or arg.kind_of?(Array))\n raise AdsCommon::Errors::TypeMismatchError.new(\n Array, arg.class, field[:name])\n end\n # An array passed when an object is expected.\n if (field[:max_occurs] == 1) and arg.kind_of?(Array)\n raise AdsCommon::Errors::TypeMismatchError.new(\n field[:type], Array, field[:name])\n end\n end", "language": "ruby", "code": "def check_required_argument_present(arg, field)\n # At least one item required, none passed.\n if field[:min_occurs] > 0 and arg.nil?\n raise AdsCommon::Errors::MissingPropertyError.new(\n field[:name], field[:type])\n end\n # An object passed when an array is expected.\n if (field[:max_occurs] == :unbounded) and\n !(arg.nil? or arg.kind_of?(Array))\n raise AdsCommon::Errors::TypeMismatchError.new(\n Array, arg.class, field[:name])\n end\n # An array passed when an object is expected.\n if (field[:max_occurs] == 1) and arg.kind_of?(Array)\n raise AdsCommon::Errors::TypeMismatchError.new(\n field[:type], Array, field[:name])\n end\n end", "code_tokens": ["def", "check_required_argument_present", "(", "arg", ",", "field", ")", "if", "field", "[", ":min_occurs", "]", ">", "0", "and", "arg", ".", "nil?", "raise", "AdsCommon", "::", "Errors", "::", "MissingPropertyError", ".", "new", "(", "field", "[", ":name", "]", ",", "field", "[", ":type", "]", ")", "end", "if", "(", "field", "[", ":max_occurs", "]", "==", ":unbounded", ")", "and", "!", "(", "arg", ".", "nil?", "or", "arg", ".", "kind_of?", "(", "Array", ")", ")", "raise", "AdsCommon", "::", "Errors", "::", "TypeMismatchError", ".", "new", "(", "Array", ",", "arg", ".", "class", ",", "field", "[", ":name", "]", ")", "end", "if", "(", "field", "[", ":max_occurs", "]", "==", "1", ")", "and", "arg", ".", "kind_of?", "(", "Array", ")", "raise", "AdsCommon", "::", "Errors", "::", "TypeMismatchError", ".", "new", "(", "field", "[", ":type", "]", ",", "Array", ",", "field", "[", ":name", "]", ")", "end", "end"], "docstring": "Checks the provided data structure matches wsdl definition.", "docstring_tokens": ["Checks", "the", "provided", "data", "structure", "matches", "wsdl", "definition", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L169-L186", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.handle_name_override", "original_string": "def handle_name_override(args, key, original_name)\n rename_hash_key(args, key, original_name)\n replace_array_item(args[:order!], key, original_name)\n return original_name\n end", "language": "ruby", "code": "def handle_name_override(args, key, original_name)\n rename_hash_key(args, key, original_name)\n replace_array_item(args[:order!], key, original_name)\n return original_name\n end", "code_tokens": ["def", "handle_name_override", "(", "args", ",", "key", ",", "original_name", ")", "rename_hash_key", "(", "args", ",", "key", ",", "original_name", ")", "replace_array_item", "(", "args", "[", ":order!", "]", ",", "key", ",", "original_name", ")", "return", "original_name", "end"], "docstring": "Overrides non-standard name conversion.", "docstring_tokens": ["Overrides", "non", "-", "standard", "name", "conversion", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L189-L193", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.handle_namespace_override", "original_string": "def handle_namespace_override(args, key, ns)\n add_extra_namespace(ns)\n new_key = prefix_key_with_namespace(key.to_s.lower_camelcase, ns)\n rename_hash_key(args, key, new_key)\n replace_array_item(args[:order!], key, new_key)\n return new_key\n end", "language": "ruby", "code": "def handle_namespace_override(args, key, ns)\n add_extra_namespace(ns)\n new_key = prefix_key_with_namespace(key.to_s.lower_camelcase, ns)\n rename_hash_key(args, key, new_key)\n replace_array_item(args[:order!], key, new_key)\n return new_key\n end", "code_tokens": ["def", "handle_namespace_override", "(", "args", ",", "key", ",", "ns", ")", "add_extra_namespace", "(", "ns", ")", "new_key", "=", "prefix_key_with_namespace", "(", "key", ".", "to_s", ".", "lower_camelcase", ",", "ns", ")", "rename_hash_key", "(", "args", ",", "key", ",", "new_key", ")", "replace_array_item", "(", "args", "[", ":order!", "]", ",", "key", ",", "new_key", ")", "return", "new_key", "end"], "docstring": "Overrides non-default namespace if requested.", "docstring_tokens": ["Overrides", "non", "-", "default", "namespace", "if", "requested", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L196-L202", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.validate_arg", "original_string": "def validate_arg(arg, parent, key, arg_type)\n result = case arg\n when Array\n validate_array_arg(arg, parent, key, arg_type)\n when Hash\n validate_hash_arg(arg, parent, key, arg_type)\n when Time\n arg = validate_time_arg(arg, parent, key)\n validate_hash_arg(arg, parent, key, arg_type)\n else\n arg\n end\n return result\n end", "language": "ruby", "code": "def validate_arg(arg, parent, key, arg_type)\n result = case arg\n when Array\n validate_array_arg(arg, parent, key, arg_type)\n when Hash\n validate_hash_arg(arg, parent, key, arg_type)\n when Time\n arg = validate_time_arg(arg, parent, key)\n validate_hash_arg(arg, parent, key, arg_type)\n else\n arg\n end\n return result\n end", "code_tokens": ["def", "validate_arg", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "result", "=", "case", "arg", "when", "Array", "validate_array_arg", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "when", "Hash", "validate_hash_arg", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "when", "Time", "arg", "=", "validate_time_arg", "(", "arg", ",", "parent", ",", "key", ")", "validate_hash_arg", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "else", "arg", "end", "return", "result", "end"], "docstring": "Validates single argument.", "docstring_tokens": ["Validates", "single", "argument", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L205-L218", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.validate_array_arg", "original_string": "def validate_array_arg(arg, parent, key, arg_type)\n result = arg.map do |item|\n validate_arg(item, parent, key, arg_type)\n end\n return result\n end", "language": "ruby", "code": "def validate_array_arg(arg, parent, key, arg_type)\n result = arg.map do |item|\n validate_arg(item, parent, key, arg_type)\n end\n return result\n end", "code_tokens": ["def", "validate_array_arg", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "result", "=", "arg", ".", "map", "do", "|", "item", "|", "validate_arg", "(", "item", ",", "parent", ",", "key", ",", "arg_type", ")", "end", "return", "result", "end"], "docstring": "Validates Array argument.", "docstring_tokens": ["Validates", "Array", "argument", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L221-L226", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.validate_hash_arg", "original_string": "def validate_hash_arg(arg, parent, key, arg_type)\n arg_type = handle_xsi_type(arg, parent, key, arg_type)\n validate_arguments(arg, arg_type[:fields], arg_type[:ns])\n end", "language": "ruby", "code": "def validate_hash_arg(arg, parent, key, arg_type)\n arg_type = handle_xsi_type(arg, parent, key, arg_type)\n validate_arguments(arg, arg_type[:fields], arg_type[:ns])\n end", "code_tokens": ["def", "validate_hash_arg", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "arg_type", "=", "handle_xsi_type", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "validate_arguments", "(", "arg", ",", "arg_type", "[", ":fields", "]", ",", "arg_type", "[", ":ns", "]", ")", "end"], "docstring": "Validates Hash argument.", "docstring_tokens": ["Validates", "Hash", "argument", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L229-L232", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.validate_time_arg", "original_string": "def validate_time_arg(arg, parent, key)\n xml_value = time_to_xml_hash(arg)\n parent[key] = xml_value\n return xml_value\n end", "language": "ruby", "code": "def validate_time_arg(arg, parent, key)\n xml_value = time_to_xml_hash(arg)\n parent[key] = xml_value\n return xml_value\n end", "code_tokens": ["def", "validate_time_arg", "(", "arg", ",", "parent", ",", "key", ")", "xml_value", "=", "time_to_xml_hash", "(", "arg", ")", "parent", "[", "key", "]", "=", "xml_value", "return", "xml_value", "end"], "docstring": "Validates Time argument.", "docstring_tokens": ["Validates", "Time", "argument", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L235-L239", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.add_attribute", "original_string": "def add_attribute(node, key, name, value)\n node[:attributes!] ||= {}\n node[:attributes!][key] ||= {}\n if node[:attributes!][key].include?(name)\n node[:attributes!][key][name] = arrayize(node[:attributes!][key][name])\n node[:attributes!][key][name] << value\n else\n node[:attributes!][key][name] = value\n end\n end", "language": "ruby", "code": "def add_attribute(node, key, name, value)\n node[:attributes!] ||= {}\n node[:attributes!][key] ||= {}\n if node[:attributes!][key].include?(name)\n node[:attributes!][key][name] = arrayize(node[:attributes!][key][name])\n node[:attributes!][key][name] << value\n else\n node[:attributes!][key][name] = value\n end\n end", "code_tokens": ["def", "add_attribute", "(", "node", ",", "key", ",", "name", ",", "value", ")", "node", "[", ":attributes!", "]", "||=", "{", "}", "node", "[", ":attributes!", "]", "[", "key", "]", "||=", "{", "}", "if", "node", "[", ":attributes!", "]", "[", "key", "]", ".", "include?", "(", "name", ")", "node", "[", ":attributes!", "]", "[", "key", "]", "[", "name", "]", "=", "arrayize", "(", "node", "[", ":attributes!", "]", "[", "key", "]", "[", "name", "]", ")", "node", "[", ":attributes!", "]", "[", "key", "]", "[", "name", "]", "<<", "value", "else", "node", "[", ":attributes!", "]", "[", "key", "]", "[", "name", "]", "=", "value", "end", "end"], "docstring": "Adds Savon attribute for given node, key, name and value.", "docstring_tokens": ["Adds", "Savon", "attribute", "for", "given", "node", "key", "name", "and", "value", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L279-L288", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.prefix_key_with_namespace", "original_string": "def prefix_key_with_namespace(key, ns_index = nil)\n namespace = (ns_index.nil?) ? DEFAULT_NAMESPACE : (\"ns%d\" % ns_index)\n return prefix_key(key, namespace)\n end", "language": "ruby", "code": "def prefix_key_with_namespace(key, ns_index = nil)\n namespace = (ns_index.nil?) ? DEFAULT_NAMESPACE : (\"ns%d\" % ns_index)\n return prefix_key(key, namespace)\n end", "code_tokens": ["def", "prefix_key_with_namespace", "(", "key", ",", "ns_index", "=", "nil", ")", "namespace", "=", "(", "ns_index", ".", "nil?", ")", "?", "DEFAULT_NAMESPACE", ":", "(", "\"ns%d\"", "%", "ns_index", ")", "return", "prefix_key", "(", "key", ",", "namespace", ")", "end"], "docstring": "Prefixes a key with a given namespace index or default namespace.", "docstring_tokens": ["Prefixes", "a", "key", "with", "a", "given", "namespace", "index", "or", "default", "namespace", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L291-L294", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.get_full_type_signature", "original_string": "def get_full_type_signature(type_name)\n result = (type_name.nil?) ? nil : @registry.get_type_signature(type_name)\n result[:fields] = implode_parent(result) if result and result[:base]\n return result\n end", "language": "ruby", "code": "def get_full_type_signature(type_name)\n result = (type_name.nil?) ? nil : @registry.get_type_signature(type_name)\n result[:fields] = implode_parent(result) if result and result[:base]\n return result\n end", "code_tokens": ["def", "get_full_type_signature", "(", "type_name", ")", "result", "=", "(", "type_name", ".", "nil?", ")", "?", "nil", ":", "@registry", ".", "get_type_signature", "(", "type_name", ")", "result", "[", ":fields", "]", "=", "implode_parent", "(", "result", ")", "if", "result", "and", "result", "[", ":base", "]", "return", "result", "end"], "docstring": "Returns type signature with all inherited fields.", "docstring_tokens": ["Returns", "type", "signature", "with", "all", "inherited", "fields", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L312-L316", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.implode_parent", "original_string": "def implode_parent(data_type)\n result = []\n if data_type[:base]\n parent_type = @registry.get_type_signature(data_type[:base])\n result += implode_parent(parent_type)\n end\n data_type[:fields].each do |field|\n # If the parent type includes a field with the same name, overwrite it.\n result.reject! {|parent_field| parent_field[:name].eql?(field[:name])}\n # Storing field's namespace.\n field[:ns] = data_type[:ns] if data_type[:ns]\n result << field\n end\n return result\n end", "language": "ruby", "code": "def implode_parent(data_type)\n result = []\n if data_type[:base]\n parent_type = @registry.get_type_signature(data_type[:base])\n result += implode_parent(parent_type)\n end\n data_type[:fields].each do |field|\n # If the parent type includes a field with the same name, overwrite it.\n result.reject! {|parent_field| parent_field[:name].eql?(field[:name])}\n # Storing field's namespace.\n field[:ns] = data_type[:ns] if data_type[:ns]\n result << field\n end\n return result\n end", "code_tokens": ["def", "implode_parent", "(", "data_type", ")", "result", "=", "[", "]", "if", "data_type", "[", ":base", "]", "parent_type", "=", "@registry", ".", "get_type_signature", "(", "data_type", "[", ":base", "]", ")", "result", "+=", "implode_parent", "(", "parent_type", ")", "end", "data_type", "[", ":fields", "]", ".", "each", "do", "|", "field", "|", "result", ".", "reject!", "{", "|", "parent_field", "|", "parent_field", "[", ":name", "]", ".", "eql?", "(", "field", "[", ":name", "]", ")", "}", "field", "[", ":ns", "]", "=", "data_type", "[", ":ns", "]", "if", "data_type", "[", ":ns", "]", "result", "<<", "field", "end", "return", "result", "end"], "docstring": "Returns all inherited fields of superclasses for given type.", "docstring_tokens": ["Returns", "all", "inherited", "fields", "of", "superclasses", "for", "given", "type", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L319-L333", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/parameters_validator.rb", "func_name": "AdsCommon.ParametersValidator.time_to_xml_hash", "original_string": "def time_to_xml_hash(time)\n return {\n :hour => time.hour, :minute => time.min, :second => time.sec,\n :date => {:year => time.year, :month => time.month, :day => time.day}\n }\n end", "language": "ruby", "code": "def time_to_xml_hash(time)\n return {\n :hour => time.hour, :minute => time.min, :second => time.sec,\n :date => {:year => time.year, :month => time.month, :day => time.day}\n }\n end", "code_tokens": ["def", "time_to_xml_hash", "(", "time", ")", "return", "{", ":hour", "=>", "time", ".", "hour", ",", ":minute", "=>", "time", ".", "min", ",", ":second", "=>", "time", ".", "sec", ",", ":date", "=>", "{", ":year", "=>", "time", ".", "year", ",", ":month", "=>", "time", ".", "month", ",", ":day", "=>", "time", ".", "day", "}", "}", "end"], "docstring": "Converts Time to a hash for XML marshalling.", "docstring_tokens": ["Converts", "Time", "to", "a", "hash", "for", "XML", "marshalling", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L349-L354", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/config.rb", "func_name": "AdsCommon.Config.load", "original_string": "def load(filename)\n begin\n new_config = YAML::load_file(filename)\n if new_config.kind_of?(Hash)\n @config = new_config\n else\n raise AdsCommon::Errors::Error,\n \"Incorrect configuration file: '%s'\" % filename\n end\n rescue TypeError => e\n raise AdsCommon::Errors::Error,\n \"Error parsing configuration file: '%s' (%s)\" % [filename, e]\n end\n return nil\n end", "language": "ruby", "code": "def load(filename)\n begin\n new_config = YAML::load_file(filename)\n if new_config.kind_of?(Hash)\n @config = new_config\n else\n raise AdsCommon::Errors::Error,\n \"Incorrect configuration file: '%s'\" % filename\n end\n rescue TypeError => e\n raise AdsCommon::Errors::Error,\n \"Error parsing configuration file: '%s' (%s)\" % [filename, e]\n end\n return nil\n end", "code_tokens": ["def", "load", "(", "filename", ")", "begin", "new_config", "=", "YAML", "::", "load_file", "(", "filename", ")", "if", "new_config", ".", "kind_of?", "(", "Hash", ")", "@config", "=", "new_config", "else", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Incorrect configuration file: '%s'\"", "%", "filename", "end", "rescue", "TypeError", "=>", "e", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Error parsing configuration file: '%s' (%s)\"", "%", "[", "filename", ",", "e", "]", "end", "return", "nil", "end"], "docstring": "Reads a configuration file into instance variable as a Ruby structure with\n the complete set of keys and values.\n\n Args:\n - filename: config file to be read (*String*)\n\n Raises:\n - Errno::ENOENT if the file does not exist.", "docstring_tokens": ["Reads", "a", "configuration", "file", "into", "instance", "variable", "as", "a", "Ruby", "structure", "with", "the", "complete", "set", "of", "keys", "and", "values", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/config.rb#L79-L93", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/config.rb", "func_name": "AdsCommon.Config.process_hash_keys", "original_string": "def process_hash_keys(hash)\n return hash.inject({}) do |result, pair|\n key, value = pair\n result[key.to_sym] = value.is_a?(Hash) ?\n process_hash_keys(value) : value\n result\n end\n end", "language": "ruby", "code": "def process_hash_keys(hash)\n return hash.inject({}) do |result, pair|\n key, value = pair\n result[key.to_sym] = value.is_a?(Hash) ?\n process_hash_keys(value) : value\n result\n end\n end", "code_tokens": ["def", "process_hash_keys", "(", "hash", ")", "return", "hash", ".", "inject", "(", "{", "}", ")", "do", "|", "result", ",", "pair", "|", "key", ",", "value", "=", "pair", "result", "[", "key", ".", "to_sym", "]", "=", "value", ".", "is_a?", "(", "Hash", ")", "?", "process_hash_keys", "(", "value", ")", ":", "value", "result", "end", "end"], "docstring": "Auxiliary method to recurse through a hash and convert all the keys to\n symbols.", "docstring_tokens": ["Auxiliary", "method", "to", "recurse", "through", "a", "hash", "and", "convert", "all", "the", "keys", "to", "symbols", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/config.rb#L99-L106", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/config.rb", "func_name": "AdsCommon.Config.find_value", "original_string": "def find_value(data, path)\n return (path.nil? or data.nil?) ? nil :\n path.split('.').inject(data) do |node, section|\n break if node.nil?\n key = section.to_sym\n (node.is_a?(Hash) and node.include?(key)) ? node[key] : nil\n end\n end", "language": "ruby", "code": "def find_value(data, path)\n return (path.nil? or data.nil?) ? nil :\n path.split('.').inject(data) do |node, section|\n break if node.nil?\n key = section.to_sym\n (node.is_a?(Hash) and node.include?(key)) ? node[key] : nil\n end\n end", "code_tokens": ["def", "find_value", "(", "data", ",", "path", ")", "return", "(", "path", ".", "nil?", "or", "data", ".", "nil?", ")", "?", "nil", ":", "path", ".", "split", "(", "'.'", ")", ".", "inject", "(", "data", ")", "do", "|", "node", ",", "section", "|", "break", "if", "node", ".", "nil?", "key", "=", "section", ".", "to_sym", "(", "node", ".", "is_a?", "(", "Hash", ")", "and", "node", ".", "include?", "(", "key", ")", ")", "?", "node", "[", "key", "]", ":", "nil", "end", "end"], "docstring": "Finds a value for string of format 'level1.level2.name' in a given hash.", "docstring_tokens": ["Finds", "a", "value", "for", "string", "of", "format", "level1", ".", "level2", ".", "name", "in", "a", "given", "hash", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/config.rb#L109-L116", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/batch_job_utils.rb", "func_name": "AdwordsApi.BatchJobUtils.initialize_url", "original_string": "def initialize_url(batch_job_url)\n headers = DEFAULT_HEADERS\n headers['Content-Length'] = 0\n headers['x-goog-resumable'] = 'start'\n\n response = AdsCommon::Http.post_response(\n batch_job_url, '', @api.config, headers)\n\n return response.headers['Location']\n end", "language": "ruby", "code": "def initialize_url(batch_job_url)\n headers = DEFAULT_HEADERS\n headers['Content-Length'] = 0\n headers['x-goog-resumable'] = 'start'\n\n response = AdsCommon::Http.post_response(\n batch_job_url, '', @api.config, headers)\n\n return response.headers['Location']\n end", "code_tokens": ["def", "initialize_url", "(", "batch_job_url", ")", "headers", "=", "DEFAULT_HEADERS", "headers", "[", "'Content-Length'", "]", "=", "0", "headers", "[", "'x-goog-resumable'", "]", "=", "'start'", "response", "=", "AdsCommon", "::", "Http", ".", "post_response", "(", "batch_job_url", ",", "''", ",", "@api", ".", "config", ",", "headers", ")", "return", "response", ".", "headers", "[", "'Location'", "]", "end"], "docstring": "Initializes an upload URL to get the actual URL to which to upload\n operations.\n\n Args:\n - batch_job_url: The UploadURL provided by BatchJobService\n\n Returns:\n - The URL that should actually be used to upload operations.", "docstring_tokens": ["Initializes", "an", "upload", "URL", "to", "get", "the", "actual", "URL", "to", "which", "to", "upload", "operations", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/batch_job_utils.rb#L85-L94", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/batch_job_utils.rb", "func_name": "AdwordsApi.BatchJobUtils.put_incremental_operations", "original_string": "def put_incremental_operations(\n operations, batch_job_url, total_content_length = 0,\n is_last_request = false)\n @api.utils_reporter.batch_job_utils_used()\n headers = DEFAULT_HEADERS\n soap_operations = generate_soap_operations(operations)\n request_body = soap_operations.join\n is_first_request = (total_content_length == 0)\n\n if is_first_request\n request_body = (UPLOAD_XML_PREFIX % [@version]) + request_body\n end\n if is_last_request\n request_body += UPLOAD_XML_SUFFIX\n end\n\n request_body = add_padding(request_body)\n content_length = request_body.bytesize\n\n headers['Content-Length'] = content_length\n\n lower_bound = total_content_length\n upper_bound = total_content_length + content_length - 1\n total_bytes = is_last_request ? upper_bound + 1 : '*'\n content_range =\n \"bytes %d-%d/%s\" % [lower_bound, upper_bound, total_bytes]\n\n headers['Content-Range'] = content_range\n\n log_request(batch_job_url, headers, request_body)\n\n # The HTTPI library fails to handle the response when uploading\n # incremental requests. We're not interested in the response, so just\n # ignore the error.\n begin\n AdsCommon::Http.put_response(\n batch_job_url, request_body, @api.config, headers)\n rescue ArgumentError\n end\n\n total_content_length += content_length\n return total_content_length\n end", "language": "ruby", "code": "def put_incremental_operations(\n operations, batch_job_url, total_content_length = 0,\n is_last_request = false)\n @api.utils_reporter.batch_job_utils_used()\n headers = DEFAULT_HEADERS\n soap_operations = generate_soap_operations(operations)\n request_body = soap_operations.join\n is_first_request = (total_content_length == 0)\n\n if is_first_request\n request_body = (UPLOAD_XML_PREFIX % [@version]) + request_body\n end\n if is_last_request\n request_body += UPLOAD_XML_SUFFIX\n end\n\n request_body = add_padding(request_body)\n content_length = request_body.bytesize\n\n headers['Content-Length'] = content_length\n\n lower_bound = total_content_length\n upper_bound = total_content_length + content_length - 1\n total_bytes = is_last_request ? upper_bound + 1 : '*'\n content_range =\n \"bytes %d-%d/%s\" % [lower_bound, upper_bound, total_bytes]\n\n headers['Content-Range'] = content_range\n\n log_request(batch_job_url, headers, request_body)\n\n # The HTTPI library fails to handle the response when uploading\n # incremental requests. We're not interested in the response, so just\n # ignore the error.\n begin\n AdsCommon::Http.put_response(\n batch_job_url, request_body, @api.config, headers)\n rescue ArgumentError\n end\n\n total_content_length += content_length\n return total_content_length\n end", "code_tokens": ["def", "put_incremental_operations", "(", "operations", ",", "batch_job_url", ",", "total_content_length", "=", "0", ",", "is_last_request", "=", "false", ")", "@api", ".", "utils_reporter", ".", "batch_job_utils_used", "(", ")", "headers", "=", "DEFAULT_HEADERS", "soap_operations", "=", "generate_soap_operations", "(", "operations", ")", "request_body", "=", "soap_operations", ".", "join", "is_first_request", "=", "(", "total_content_length", "==", "0", ")", "if", "is_first_request", "request_body", "=", "(", "UPLOAD_XML_PREFIX", "%", "[", "@version", "]", ")", "+", "request_body", "end", "if", "is_last_request", "request_body", "+=", "UPLOAD_XML_SUFFIX", "end", "request_body", "=", "add_padding", "(", "request_body", ")", "content_length", "=", "request_body", ".", "bytesize", "headers", "[", "'Content-Length'", "]", "=", "content_length", "lower_bound", "=", "total_content_length", "upper_bound", "=", "total_content_length", "+", "content_length", "-", "1", "total_bytes", "=", "is_last_request", "?", "upper_bound", "+", "1", ":", "'*'", "content_range", "=", "\"bytes %d-%d/%s\"", "%", "[", "lower_bound", ",", "upper_bound", ",", "total_bytes", "]", "headers", "[", "'Content-Range'", "]", "=", "content_range", "log_request", "(", "batch_job_url", ",", "headers", ",", "request_body", ")", "begin", "AdsCommon", "::", "Http", ".", "put_response", "(", "batch_job_url", ",", "request_body", ",", "@api", ".", "config", ",", "headers", ")", "rescue", "ArgumentError", "end", "total_content_length", "+=", "content_length", "return", "total_content_length", "end"], "docstring": "Puts the provided operations to the provided URL, allowing\n for incremental followup puts.\n\n Args:\n - soap_operations: An array including SOAP operations provided by\n generate_soap_operations\n - batch_job_url: The UploadURL provided by BatchJobService\n - total_content_length: The total number of bytes already uploaded\n incrementally. Set this to 0 the first time you call the method.\n - is_last_request: Whether or not this set of uploads will conclude the\n full request.\n\n Returns:\n - total content length, including what was just uploaded. Pass this back\n into this method on subsequent calls.", "docstring_tokens": ["Puts", "the", "provided", "operations", "to", "the", "provided", "URL", "allowing", "for", "incremental", "followup", "puts", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/batch_job_utils.rb#L111-L153", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/batch_job_utils.rb", "func_name": "AdwordsApi.BatchJobUtils.get_job_results", "original_string": "def get_job_results(batch_job_url)\n @api.utils_reporter.batch_job_utils_used()\n xml_response = AdsCommon::Http.get_response(batch_job_url, @api.config)\n begin\n return sanitize_result(\n get_nori().parse(xml_response.body)[:mutate_response][:rval])\n rescue\n return nil\n end\n end", "language": "ruby", "code": "def get_job_results(batch_job_url)\n @api.utils_reporter.batch_job_utils_used()\n xml_response = AdsCommon::Http.get_response(batch_job_url, @api.config)\n begin\n return sanitize_result(\n get_nori().parse(xml_response.body)[:mutate_response][:rval])\n rescue\n return nil\n end\n end", "code_tokens": ["def", "get_job_results", "(", "batch_job_url", ")", "@api", ".", "utils_reporter", ".", "batch_job_utils_used", "(", ")", "xml_response", "=", "AdsCommon", "::", "Http", ".", "get_response", "(", "batch_job_url", ",", "@api", ".", "config", ")", "begin", "return", "sanitize_result", "(", "get_nori", "(", ")", ".", "parse", "(", "xml_response", ".", "body", ")", "[", ":mutate_response", "]", "[", ":rval", "]", ")", "rescue", "return", "nil", "end", "end"], "docstring": "Downloads the results of a batch job from the specified URL.\n\n Args:\n - batch_job_url: The URL provided by BatchJobService to fetch the results\n from\n\n Returns:\n - the results of the batch job, as a ruby hash, or nil if none yet exist", "docstring_tokens": ["Downloads", "the", "results", "of", "a", "batch", "job", "from", "the", "specified", "URL", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/batch_job_utils.rb#L164-L173", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/batch_job_utils.rb", "func_name": "AdwordsApi.BatchJobUtils.extract_soap_operations", "original_string": "def extract_soap_operations(full_soap_xml)\n doc = Nokogiri::XML(full_soap_xml)\n operations = doc.css('wsdl|operations')\n operations.attr('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')\n operations.each do |element|\n check_xsi_type(element)\n end\n return operations.to_s\n end", "language": "ruby", "code": "def extract_soap_operations(full_soap_xml)\n doc = Nokogiri::XML(full_soap_xml)\n operations = doc.css('wsdl|operations')\n operations.attr('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')\n operations.each do |element|\n check_xsi_type(element)\n end\n return operations.to_s\n end", "code_tokens": ["def", "extract_soap_operations", "(", "full_soap_xml", ")", "doc", "=", "Nokogiri", "::", "XML", "(", "full_soap_xml", ")", "operations", "=", "doc", ".", "css", "(", "'wsdl|operations'", ")", "operations", ".", "attr", "(", "'xmlns:xsi'", ",", "'http://www.w3.org/2001/XMLSchema-instance'", ")", "operations", ".", "each", "do", "|", "element", "|", "check_xsi_type", "(", "element", ")", "end", "return", "operations", ".", "to_s", "end"], "docstring": "Given a full SOAP xml string, extract just the operations element\n from the SOAP body as a string.", "docstring_tokens": ["Given", "a", "full", "SOAP", "xml", "string", "extract", "just", "the", "operations", "element", "from", "the", "SOAP", "body", "as", "a", "string", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/batch_job_utils.rb#L257-L265", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/batch_job_utils.rb", "func_name": "AdwordsApi.BatchJobUtils.sanitize_result", "original_string": "def sanitize_result(results)\n if results.is_a?(Array)\n ret = []\n results.each do |result|\n ret << sanitize_result(result)\n end\n return ret\n end\n\n if results.is_a?(Hash)\n ret = {}\n results.each do |k, v|\n v = sanitize_result(v) if v.is_a?(Hash)\n ret[k] = v unless k.to_s.start_with?('@')\n end\n return ret\n end\n\n return results\n end", "language": "ruby", "code": "def sanitize_result(results)\n if results.is_a?(Array)\n ret = []\n results.each do |result|\n ret << sanitize_result(result)\n end\n return ret\n end\n\n if results.is_a?(Hash)\n ret = {}\n results.each do |k, v|\n v = sanitize_result(v) if v.is_a?(Hash)\n ret[k] = v unless k.to_s.start_with?('@')\n end\n return ret\n end\n\n return results\n end", "code_tokens": ["def", "sanitize_result", "(", "results", ")", "if", "results", ".", "is_a?", "(", "Array", ")", "ret", "=", "[", "]", "results", ".", "each", "do", "|", "result", "|", "ret", "<<", "sanitize_result", "(", "result", ")", "end", "return", "ret", "end", "if", "results", ".", "is_a?", "(", "Hash", ")", "ret", "=", "{", "}", "results", ".", "each", "do", "|", "k", ",", "v", "|", "v", "=", "sanitize_result", "(", "v", ")", "if", "v", ".", "is_a?", "(", "Hash", ")", "ret", "[", "k", "]", "=", "v", "unless", "k", ".", "to_s", ".", "start_with?", "(", "'@'", ")", "end", "return", "ret", "end", "return", "results", "end"], "docstring": "Removes extraneous XML information from return hash.", "docstring_tokens": ["Removes", "extraneous", "XML", "information", "from", "return", "hash", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/batch_job_utils.rb#L290-L309", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/query_utils/service_query.rb", "func_name": "AdwordsApi.ServiceQuery.has_next_landscape_page", "original_string": "def has_next_landscape_page(page)\n raise ArgumentError,\n 'Cannot page through query with no LIMIT clause.' if @start_index.nil?\n return false unless page[:entries]\n total_landscape_points_in_page = 0\n page[:entries].each do |landscape|\n total_landscape_points_in_page += landscape[:landscape_points].size\n end\n return total_landscape_points_in_page >= @page_size\n end", "language": "ruby", "code": "def has_next_landscape_page(page)\n raise ArgumentError,\n 'Cannot page through query with no LIMIT clause.' if @start_index.nil?\n return false unless page[:entries]\n total_landscape_points_in_page = 0\n page[:entries].each do |landscape|\n total_landscape_points_in_page += landscape[:landscape_points].size\n end\n return total_landscape_points_in_page >= @page_size\n end", "code_tokens": ["def", "has_next_landscape_page", "(", "page", ")", "raise", "ArgumentError", ",", "'Cannot page through query with no LIMIT clause.'", "if", "@start_index", ".", "nil?", "return", "false", "unless", "page", "[", ":entries", "]", "total_landscape_points_in_page", "=", "0", "page", "[", ":entries", "]", ".", "each", "do", "|", "landscape", "|", "total_landscape_points_in_page", "+=", "landscape", "[", ":landscape_points", "]", ".", "size", "end", "return", "total_landscape_points_in_page", ">=", "@page_size", "end"], "docstring": "Determining whether another page exists when dealing with bid landscapes\n is different from other types of queries. Use this method for those cases.", "docstring_tokens": ["Determining", "whether", "another", "page", "exists", "when", "dealing", "with", "bid", "landscapes", "is", "different", "from", "other", "types", "of", "queries", ".", "Use", "this", "method", "for", "those", "cases", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/query_utils/service_query.rb#L36-L45", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api_config.rb", "func_name": "AdsCommon.ApiConfig.version_has_service", "original_string": "def version_has_service(version, service)\n return service_config.include?(version) &&\n service_config[version].include?(service)\n end", "language": "ruby", "code": "def version_has_service(version, service)\n return service_config.include?(version) &&\n service_config[version].include?(service)\n end", "code_tokens": ["def", "version_has_service", "(", "version", ",", "service", ")", "return", "service_config", ".", "include?", "(", "version", ")", "&&", "service_config", "[", "version", "]", ".", "include?", "(", "service", ")", "end"], "docstring": "Does the given version exist and contain the given service?\n\n Returns:\n Boolean indicating whether the given version exists and contains the\n given service", "docstring_tokens": ["Does", "the", "given", "version", "exist", "and", "contain", "the", "given", "service?"], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api_config.rb#L60-L63", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api_config.rb", "func_name": "AdsCommon.ApiConfig.endpoint", "original_string": "def endpoint(version, service)\n base = get_wsdl_base(version)\n if !subdir_config().nil?\n base = base.to_s + subdir_config()[[version, service]].to_s\n end\n return base.to_s + version.to_s + '/' + service.to_s\n end", "language": "ruby", "code": "def endpoint(version, service)\n base = get_wsdl_base(version)\n if !subdir_config().nil?\n base = base.to_s + subdir_config()[[version, service]].to_s\n end\n return base.to_s + version.to_s + '/' + service.to_s\n end", "code_tokens": ["def", "endpoint", "(", "version", ",", "service", ")", "base", "=", "get_wsdl_base", "(", "version", ")", "if", "!", "subdir_config", "(", ")", ".", "nil?", "base", "=", "base", ".", "to_s", "+", "subdir_config", "(", ")", "[", "[", "version", ",", "service", "]", "]", ".", "to_s", "end", "return", "base", ".", "to_s", "+", "version", ".", "to_s", "+", "'/'", "+", "service", ".", "to_s", "end"], "docstring": "Get the endpoint for a service on a given API version.\n\n Args:\n - version: the API version\n - service: the name of the API service\n\n Returns:\n The endpoint URL", "docstring_tokens": ["Get", "the", "endpoint", "for", "a", "service", "on", "a", "given", "API", "version", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api_config.rb#L110-L116", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api_config.rb", "func_name": "AdsCommon.ApiConfig.do_require", "original_string": "def do_require(version, service)\n filename = [api_path, version.to_s, service.to_s.snakecase].join('/')\n require filename\n return filename\n end", "language": "ruby", "code": "def do_require(version, service)\n filename = [api_path, version.to_s, service.to_s.snakecase].join('/')\n require filename\n return filename\n end", "code_tokens": ["def", "do_require", "(", "version", ",", "service", ")", "filename", "=", "[", "api_path", ",", "version", ".", "to_s", ",", "service", ".", "to_s", ".", "snakecase", "]", ".", "join", "(", "'/'", ")", "require", "filename", "return", "filename", "end"], "docstring": "Perform the loading of the necessary source files for a version.\n\n Args:\n - version: the API version\n - service: service name\n\n Returns:\n The filename that was loaded", "docstring_tokens": ["Perform", "the", "loading", "of", "the", "necessary", "source", "files", "for", "a", "version", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api_config.rb#L141-L145", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api_config.rb", "func_name": "AdsCommon.ApiConfig.module_name", "original_string": "def module_name(version, service)\n return [api_name, version.to_s.upcase, service.to_s].join('::')\n end", "language": "ruby", "code": "def module_name(version, service)\n return [api_name, version.to_s.upcase, service.to_s].join('::')\n end", "code_tokens": ["def", "module_name", "(", "version", ",", "service", ")", "return", "[", "api_name", ",", "version", ".", "to_s", ".", "upcase", ",", "service", ".", "to_s", "]", ".", "join", "(", "'::'", ")", "end"], "docstring": "Returns the full module name for a given service.\n\n Args:\n - version: the API version\n - service: the service name\n\n Returns:\n The full module name for the given service", "docstring_tokens": ["Returns", "the", "full", "module", "name", "for", "a", "given", "service", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api_config.rb#L156-L158", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api_config.rb", "func_name": "AdsCommon.ApiConfig.get_wsdls", "original_string": "def get_wsdls(version)\n res = {}\n wsdl_base = get_wsdl_base(version)\n postfix = wsdl_base.start_with?('http') ? '?wsdl' : '.wsdl'\n services(version).each do |service|\n path = wsdl_base\n if (!subdir_config().nil?)\n subdir_name = subdir(version, service);\n path = path + subdir_name if subdir_name and !subdir_name.empty?\n end\n path = path + version.to_s + '/' + service.to_s + postfix\n res[service.to_s] = path\n end\n return res\n end", "language": "ruby", "code": "def get_wsdls(version)\n res = {}\n wsdl_base = get_wsdl_base(version)\n postfix = wsdl_base.start_with?('http') ? '?wsdl' : '.wsdl'\n services(version).each do |service|\n path = wsdl_base\n if (!subdir_config().nil?)\n subdir_name = subdir(version, service);\n path = path + subdir_name if subdir_name and !subdir_name.empty?\n end\n path = path + version.to_s + '/' + service.to_s + postfix\n res[service.to_s] = path\n end\n return res\n end", "code_tokens": ["def", "get_wsdls", "(", "version", ")", "res", "=", "{", "}", "wsdl_base", "=", "get_wsdl_base", "(", "version", ")", "postfix", "=", "wsdl_base", ".", "start_with?", "(", "'http'", ")", "?", "'?wsdl'", ":", "'.wsdl'", "services", "(", "version", ")", ".", "each", "do", "|", "service", "|", "path", "=", "wsdl_base", "if", "(", "!", "subdir_config", "(", ")", ".", "nil?", ")", "subdir_name", "=", "subdir", "(", "version", ",", "service", ")", ";", "path", "=", "path", "+", "subdir_name", "if", "subdir_name", "and", "!", "subdir_name", ".", "empty?", "end", "path", "=", "path", "+", "version", ".", "to_s", "+", "'/'", "+", "service", ".", "to_s", "+", "postfix", "res", "[", "service", ".", "to_s", "]", "=", "path", "end", "return", "res", "end"], "docstring": "Generates an array of WSDL URLs based on defined Services and version\n supplied. This method is used by generators to determine what service\n wrappers to generate.\n\n Args:\n - version: the API version.\n\n Returns\n hash of pairs Service => WSDL URL", "docstring_tokens": ["Generates", "an", "array", "of", "WSDL", "URLs", "based", "on", "defined", "Services", "and", "version", "supplied", ".", "This", "method", "is", "used", "by", "generators", "to", "determine", "what", "service", "wrappers", "to", "generate", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api_config.rb#L183-L197", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_savon/lib/ads_savon/client.rb", "func_name": "GoogleAdsSavon.Client.process", "original_string": "def process(offset = 0, instance = self, &block)\n block.arity > 0 ? yield_objects(offset, instance, &block) : evaluate(instance, &block)\n end", "language": "ruby", "code": "def process(offset = 0, instance = self, &block)\n block.arity > 0 ? yield_objects(offset, instance, &block) : evaluate(instance, &block)\n end", "code_tokens": ["def", "process", "(", "offset", "=", "0", ",", "instance", "=", "self", ",", "&", "block", ")", "block", ".", "arity", ">", "0", "?", "yield_objects", "(", "offset", ",", "instance", ",", "&", "block", ")", ":", "evaluate", "(", "instance", ",", "&", "block", ")", "end"], "docstring": "Processes a given +block+. Yields objects if the block expects any arguments.\n Otherwise evaluates the block in the context of +instance+.", "docstring_tokens": ["Processes", "a", "given", "+", "block", "+", ".", "Yields", "objects", "if", "the", "block", "expects", "any", "arguments", ".", "Otherwise", "evaluates", "the", "block", "in", "the", "context", "of", "+", "instance", "+", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_savon/lib/ads_savon/client.rb#L121-L123", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_savon/lib/ads_savon/client.rb", "func_name": "GoogleAdsSavon.Client.yield_objects", "original_string": "def yield_objects(offset, instance, &block)\n to_yield = [:soap, :wsdl, :http, :wsse]\n yield *(to_yield[offset, block.arity].map { |obj_name| instance.send(obj_name) })\n end", "language": "ruby", "code": "def yield_objects(offset, instance, &block)\n to_yield = [:soap, :wsdl, :http, :wsse]\n yield *(to_yield[offset, block.arity].map { |obj_name| instance.send(obj_name) })\n end", "code_tokens": ["def", "yield_objects", "(", "offset", ",", "instance", ",", "&", "block", ")", "to_yield", "=", "[", ":soap", ",", ":wsdl", ",", ":http", ",", ":wsse", "]", "yield", "*", "(", "to_yield", "[", "offset", ",", "block", ".", "arity", "]", ".", "map", "{", "|", "obj_name", "|", "instance", ".", "send", "(", "obj_name", ")", "}", ")", "end"], "docstring": "Yields a number of objects to a given +block+ depending on how many arguments\n the block is expecting.", "docstring_tokens": ["Yields", "a", "number", "of", "objects", "to", "a", "given", "+", "block", "+", "depending", "on", "how", "many", "arguments", "the", "block", "is", "expecting", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_savon/lib/ads_savon/client.rb#L127-L130", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_savon/lib/ads_savon/client.rb", "func_name": "GoogleAdsSavon.Client.evaluate", "original_string": "def evaluate(instance, &block)\n original_self = eval \"self\", block.binding\n\n # A proxy that attemps to make method calls on +instance+. If a NoMethodError is\n # raised, the call will be made on +original_self+.\n proxy = Object.new\n proxy.instance_eval do\n class << self\n attr_accessor :original_self, :instance\n end\n\n def method_missing(method, *args, &block)\n instance.send(method, *args, &block)\n rescue NoMethodError\n original_self.send(method, *args, &block)\n end\n end\n\n proxy.instance = instance\n proxy.original_self = original_self\n\n proxy.instance_eval &block\n end", "language": "ruby", "code": "def evaluate(instance, &block)\n original_self = eval \"self\", block.binding\n\n # A proxy that attemps to make method calls on +instance+. If a NoMethodError is\n # raised, the call will be made on +original_self+.\n proxy = Object.new\n proxy.instance_eval do\n class << self\n attr_accessor :original_self, :instance\n end\n\n def method_missing(method, *args, &block)\n instance.send(method, *args, &block)\n rescue NoMethodError\n original_self.send(method, *args, &block)\n end\n end\n\n proxy.instance = instance\n proxy.original_self = original_self\n\n proxy.instance_eval &block\n end", "code_tokens": ["def", "evaluate", "(", "instance", ",", "&", "block", ")", "original_self", "=", "eval", "\"self\"", ",", "block", ".", "binding", "proxy", "=", "Object", ".", "new", "proxy", ".", "instance_eval", "do", "class", "<<", "self", "attr_accessor", ":original_self", ",", ":instance", "end", "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "instance", ".", "send", "(", "method", ",", "*", "args", ",", "&", "block", ")", "rescue", "NoMethodError", "original_self", ".", "send", "(", "method", ",", "*", "args", ",", "&", "block", ")", "end", "end", "proxy", ".", "instance", "=", "instance", "proxy", ".", "original_self", "=", "original_self", "proxy", ".", "instance_eval", "&", "block", "end"], "docstring": "Evaluates a given +block+ inside +instance+. Stores the original block binding.", "docstring_tokens": ["Evaluates", "a", "given", "+", "block", "+", "inside", "+", "instance", "+", ".", "Stores", "the", "original", "block", "binding", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_savon/lib/ads_savon/client.rb#L133-L155", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_savon/lib/ads_savon/client.rb", "func_name": "GoogleAdsSavon.Client.remove_blank_values", "original_string": "def remove_blank_values(hash)\n hash.delete_if { |_, value| value.respond_to?(:empty?) ? value.empty? : !value }\n end", "language": "ruby", "code": "def remove_blank_values(hash)\n hash.delete_if { |_, value| value.respond_to?(:empty?) ? value.empty? : !value }\n end", "code_tokens": ["def", "remove_blank_values", "(", "hash", ")", "hash", ".", "delete_if", "{", "|", "_", ",", "value", "|", "value", ".", "respond_to?", "(", ":empty?", ")", "?", "value", ".", "empty?", ":", "!", "value", "}", "end"], "docstring": "Removes all blank values from a given +hash+.", "docstring_tokens": ["Removes", "all", "blank", "values", "from", "a", "given", "+", "hash", "+", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_savon/lib/ads_savon/client.rb#L158-L160", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb", "func_name": "AdManagerApi.PQLValues.values", "original_string": "def values()\n # values_array is an Ad-Manager-compliant list of values of the following\n # form: [:key => ..., :value => {:xsi_type => ..., :value => ...}]\n values_array = @values.map do |key, value|\n raise 'Missing value in StatementBuilder.' if value.nil?\n raise 'Misconfigured value in StatementBuilder.' unless value.is_a? Hash\n raise 'Value cannot be nil on StatementBuilder.' if value[:value].nil?\n raise 'Missing value type for %s.' % key if value[:xsi_type].nil?\n unless VALUE_TYPES.values.include?(value[:xsi_type])\n raise 'Unknown value type for %s.' % key\n end\n if value[:xsi_type] == 'SetValue'\n if value[:value].map {|v| v.class}.to_set.size > 1\n raise 'Cannot pass more than one type in set variable, %s.' % key\n end\n end\n if value[:xsi_type] == 'DateTimeValue'\n unless value[:value][:time_zone_id]\n raise 'Missing timezone on DateTimeValue variable, %s.' %key\n end\n end\n {:key => key.to_s(), :value => value}\n end\n return values_array\n end", "language": "ruby", "code": "def values()\n # values_array is an Ad-Manager-compliant list of values of the following\n # form: [:key => ..., :value => {:xsi_type => ..., :value => ...}]\n values_array = @values.map do |key, value|\n raise 'Missing value in StatementBuilder.' if value.nil?\n raise 'Misconfigured value in StatementBuilder.' unless value.is_a? Hash\n raise 'Value cannot be nil on StatementBuilder.' if value[:value].nil?\n raise 'Missing value type for %s.' % key if value[:xsi_type].nil?\n unless VALUE_TYPES.values.include?(value[:xsi_type])\n raise 'Unknown value type for %s.' % key\n end\n if value[:xsi_type] == 'SetValue'\n if value[:value].map {|v| v.class}.to_set.size > 1\n raise 'Cannot pass more than one type in set variable, %s.' % key\n end\n end\n if value[:xsi_type] == 'DateTimeValue'\n unless value[:value][:time_zone_id]\n raise 'Missing timezone on DateTimeValue variable, %s.' %key\n end\n end\n {:key => key.to_s(), :value => value}\n end\n return values_array\n end", "code_tokens": ["def", "values", "(", ")", "values_array", "=", "@values", ".", "map", "do", "|", "key", ",", "value", "|", "raise", "'Missing value in StatementBuilder.'", "if", "value", ".", "nil?", "raise", "'Misconfigured value in StatementBuilder.'", "unless", "value", ".", "is_a?", "Hash", "raise", "'Value cannot be nil on StatementBuilder.'", "if", "value", "[", ":value", "]", ".", "nil?", "raise", "'Missing value type for %s.'", "%", "key", "if", "value", "[", ":xsi_type", "]", ".", "nil?", "unless", "VALUE_TYPES", ".", "values", ".", "include?", "(", "value", "[", ":xsi_type", "]", ")", "raise", "'Unknown value type for %s.'", "%", "key", "end", "if", "value", "[", ":xsi_type", "]", "==", "'SetValue'", "if", "value", "[", ":value", "]", ".", "map", "{", "|", "v", "|", "v", ".", "class", "}", ".", "to_set", ".", "size", ">", "1", "raise", "'Cannot pass more than one type in set variable, %s.'", "%", "key", "end", "end", "if", "value", "[", ":xsi_type", "]", "==", "'DateTimeValue'", "unless", "value", "[", ":value", "]", "[", ":time_zone_id", "]", "raise", "'Missing timezone on DateTimeValue variable, %s.'", "%", "key", "end", "end", "{", ":key", "=>", "key", ".", "to_s", "(", ")", ",", ":value", "=>", "value", "}", "end", "return", "values_array", "end"], "docstring": "Get values as an array, the format the Ad Manager API expects.", "docstring_tokens": ["Get", "values", "as", "an", "array", "the", "format", "the", "Ad", "Manager", "API", "expects", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb#L65-L89", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb", "func_name": "AdManagerApi.PQLValues.generate_value_object", "original_string": "def generate_value_object(value)\n typeKeyValue = VALUE_TYPES.find {|key, val| value.is_a? key}\n dateTypes = [AdManagerApi::AdManagerDate, AdManagerApi::AdManagerDateTime]\n if dateTypes.include?(value.class)\n value = value.to_h\n end\n return value if typeKeyValue.nil?\n return {:xsi_type => typeKeyValue.last, :value => value}\n end", "language": "ruby", "code": "def generate_value_object(value)\n typeKeyValue = VALUE_TYPES.find {|key, val| value.is_a? key}\n dateTypes = [AdManagerApi::AdManagerDate, AdManagerApi::AdManagerDateTime]\n if dateTypes.include?(value.class)\n value = value.to_h\n end\n return value if typeKeyValue.nil?\n return {:xsi_type => typeKeyValue.last, :value => value}\n end", "code_tokens": ["def", "generate_value_object", "(", "value", ")", "typeKeyValue", "=", "VALUE_TYPES", ".", "find", "{", "|", "key", ",", "val", "|", "value", ".", "is_a?", "key", "}", "dateTypes", "=", "[", "AdManagerApi", "::", "AdManagerDate", ",", "AdManagerApi", "::", "AdManagerDateTime", "]", "if", "dateTypes", ".", "include?", "(", "value", ".", "class", ")", "value", "=", "value", ".", "to_h", "end", "return", "value", "if", "typeKeyValue", ".", "nil?", "return", "{", ":xsi_type", "=>", "typeKeyValue", ".", "last", ",", ":value", "=>", "value", "}", "end"], "docstring": "Create an individual value object by inferring the xsi_type. If the value\n type isn't recognized, return the original value parameter.", "docstring_tokens": ["Create", "an", "individual", "value", "object", "by", "inferring", "the", "xsi_type", ".", "If", "the", "value", "type", "isn", "t", "recognized", "return", "the", "original", "value", "parameter", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb#L93-L101", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb", "func_name": "AdManagerApi.StatementBuilder.validate", "original_string": "def validate()\n if !@select.to_s.strip.empty? and @from.to_s.strip.empty?\n raise 'FROM clause is required with SELECT'\n end\n if !@from.to_s.strip.empty? and @select.to_s.strip.empty?\n raise 'SELECT clause is required with FROM'\n end\n if !@offset.nil? and @limit.nil?\n raise 'LIMIT clause is required with OFFSET'\n end\n unless @limit.is_a? Integer or @limit.nil?\n raise 'LIMIT must be an integer'\n end\n unless @offset.is_a? Integer or @offset.nil?\n raise 'OFFSET must be an integer'\n end\n end", "language": "ruby", "code": "def validate()\n if !@select.to_s.strip.empty? and @from.to_s.strip.empty?\n raise 'FROM clause is required with SELECT'\n end\n if !@from.to_s.strip.empty? and @select.to_s.strip.empty?\n raise 'SELECT clause is required with FROM'\n end\n if !@offset.nil? and @limit.nil?\n raise 'LIMIT clause is required with OFFSET'\n end\n unless @limit.is_a? Integer or @limit.nil?\n raise 'LIMIT must be an integer'\n end\n unless @offset.is_a? Integer or @offset.nil?\n raise 'OFFSET must be an integer'\n end\n end", "code_tokens": ["def", "validate", "(", ")", "if", "!", "@select", ".", "to_s", ".", "strip", ".", "empty?", "and", "@from", ".", "to_s", ".", "strip", ".", "empty?", "raise", "'FROM clause is required with SELECT'", "end", "if", "!", "@from", ".", "to_s", ".", "strip", ".", "empty?", "and", "@select", ".", "to_s", ".", "strip", ".", "empty?", "raise", "'SELECT clause is required with FROM'", "end", "if", "!", "@offset", ".", "nil?", "and", "@limit", ".", "nil?", "raise", "'LIMIT clause is required with OFFSET'", "end", "unless", "@limit", ".", "is_a?", "Integer", "or", "@limit", ".", "nil?", "raise", "'LIMIT must be an integer'", "end", "unless", "@offset", ".", "is_a?", "Integer", "or", "@offset", ".", "nil?", "raise", "'OFFSET must be an integer'", "end", "end"], "docstring": "Return a list of validation errors.", "docstring_tokens": ["Return", "a", "list", "of", "validation", "errors", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb#L160-L176", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb", "func_name": "AdManagerApi.StatementBuilder.to_statement", "original_string": "def to_statement()\n @api.utils_reporter.statement_builder_used()\n validate()\n ordering = @ascending ? 'ASC' : 'DESC'\n pql_query = PQLQuery.new\n pql_query << SELECT % @select unless @select.to_s.empty?\n pql_query << FROM % @from unless @from.to_s.empty?\n pql_query << WHERE % @where unless @where.to_s.empty?\n pql_query << ORDER % [@order_by, ordering] unless @order_by.to_s.empty?\n pql_query << LIMIT % @limit unless @limit.nil?\n pql_query << OFFSET % @offset unless @offset.nil?\n return {:query => pql_query.to_s(), :values => @pql_values.values}\n end", "language": "ruby", "code": "def to_statement()\n @api.utils_reporter.statement_builder_used()\n validate()\n ordering = @ascending ? 'ASC' : 'DESC'\n pql_query = PQLQuery.new\n pql_query << SELECT % @select unless @select.to_s.empty?\n pql_query << FROM % @from unless @from.to_s.empty?\n pql_query << WHERE % @where unless @where.to_s.empty?\n pql_query << ORDER % [@order_by, ordering] unless @order_by.to_s.empty?\n pql_query << LIMIT % @limit unless @limit.nil?\n pql_query << OFFSET % @offset unless @offset.nil?\n return {:query => pql_query.to_s(), :values => @pql_values.values}\n end", "code_tokens": ["def", "to_statement", "(", ")", "@api", ".", "utils_reporter", ".", "statement_builder_used", "(", ")", "validate", "(", ")", "ordering", "=", "@ascending", "?", "'ASC'", ":", "'DESC'", "pql_query", "=", "PQLQuery", ".", "new", "pql_query", "<<", "SELECT", "%", "@select", "unless", "@select", ".", "to_s", ".", "empty?", "pql_query", "<<", "FROM", "%", "@from", "unless", "@from", ".", "to_s", ".", "empty?", "pql_query", "<<", "WHERE", "%", "@where", "unless", "@where", ".", "to_s", ".", "empty?", "pql_query", "<<", "ORDER", "%", "[", "@order_by", ",", "ordering", "]", "unless", "@order_by", ".", "to_s", ".", "empty?", "pql_query", "<<", "LIMIT", "%", "@limit", "unless", "@limit", ".", "nil?", "pql_query", "<<", "OFFSET", "%", "@offset", "unless", "@offset", ".", "nil?", "return", "{", ":query", "=>", "pql_query", ".", "to_s", "(", ")", ",", ":values", "=>", "@pql_values", ".", "values", "}", "end"], "docstring": "Create a statement object that can be sent in a Ad Manager API request.", "docstring_tokens": ["Create", "a", "statement", "object", "that", "can", "be", "sent", "in", "a", "Ad", "Manager", "API", "request", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ad_manager_api/lib/ad_manager_api/pql_statement_utils.rb#L179-L191", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ad_manager_api/lib/ad_manager_api/ad_manager_api_datetime.rb", "func_name": "AdManagerApi.AdManagerDate.method_missing", "original_string": "def method_missing(name, *args, &block)\n result = @date.send(name, *args, &block)\n return self.class.new(@api, result) if result.is_a? Date\n return result\n end", "language": "ruby", "code": "def method_missing(name, *args, &block)\n result = @date.send(name, *args, &block)\n return self.class.new(@api, result) if result.is_a? Date\n return result\n end", "code_tokens": ["def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "result", "=", "@date", ".", "send", "(", "name", ",", "*", "args", ",", "&", "block", ")", "return", "self", ".", "class", ".", "new", "(", "@api", ",", "result", ")", "if", "result", ".", "is_a?", "Date", "return", "result", "end"], "docstring": "When an unrecognized method is applied to AdManagerDate, pass it through\n to the internal ruby Date.", "docstring_tokens": ["When", "an", "unrecognized", "method", "is", "applied", "to", "AdManagerDate", "pass", "it", "through", "to", "the", "internal", "ruby", "Date", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ad_manager_api/lib/ad_manager_api/ad_manager_api_datetime.rb#L62-L66", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ad_manager_api/lib/ad_manager_api/ad_manager_api_datetime.rb", "func_name": "AdManagerApi.AdManagerDateTime.to_h", "original_string": "def to_h\n {\n :date => AdManagerApi::AdManagerDate.new(\n @api, @time.year, @time.month, @time.day\n ).to_h,\n :hour => @time.hour,\n :minute => @time.min,\n :second => @time.sec,\n :time_zone_id => @timezone.identifier\n }\n end", "language": "ruby", "code": "def to_h\n {\n :date => AdManagerApi::AdManagerDate.new(\n @api, @time.year, @time.month, @time.day\n ).to_h,\n :hour => @time.hour,\n :minute => @time.min,\n :second => @time.sec,\n :time_zone_id => @timezone.identifier\n }\n end", "code_tokens": ["def", "to_h", "{", ":date", "=>", "AdManagerApi", "::", "AdManagerDate", ".", "new", "(", "@api", ",", "@time", ".", "year", ",", "@time", ".", "month", ",", "@time", ".", "day", ")", ".", "to_h", ",", ":hour", "=>", "@time", ".", "hour", ",", ":minute", "=>", "@time", ".", "min", ",", ":second", "=>", "@time", ".", "sec", ",", ":time_zone_id", "=>", "@timezone", ".", "identifier", "}", "end"], "docstring": "Convert AdManagerDateTime into a hash representation which can be consumed\n by the Ad Manager API. E.g., a hash that can be passed as PQL DateTime\n variables.\n\n Returns:\n - ad_manager_datetime_hash: a hash representation of an\n AdManagerDateTime", "docstring_tokens": ["Convert", "AdManagerDateTime", "into", "a", "hash", "representation", "which", "can", "be", "consumed", "by", "the", "Ad", "Manager", "API", ".", "E", ".", "g", ".", "a", "hash", "that", "can", "be", "passed", "as", "PQL", "DateTime", "variables", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ad_manager_api/lib/ad_manager_api/ad_manager_api_datetime.rb#L158-L168", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ad_manager_api/lib/ad_manager_api/ad_manager_api_datetime.rb", "func_name": "AdManagerApi.AdManagerDateTime.method_missing", "original_string": "def method_missing(name, *args, &block)\n # Restrict time zone related functions from being passed to internal ruby\n # Time attribute, since AdManagerDateTime handles timezones its own way.\n restricted_functions = [:dst?, :getgm, :getlocal, :getutc, :gmt,\n :gmtime, :gmtoff, :isdst, :localtime, :utc]\n if restricted_functions.include? name\n raise NoMethodError, 'undefined method %s for %s' % [name, self]\n end\n result = @time.send(name, *args, &block)\n if result.is_a? Time\n return self.class.new(@api, result, @timezone.identifier)\n else\n return result\n end\n end", "language": "ruby", "code": "def method_missing(name, *args, &block)\n # Restrict time zone related functions from being passed to internal ruby\n # Time attribute, since AdManagerDateTime handles timezones its own way.\n restricted_functions = [:dst?, :getgm, :getlocal, :getutc, :gmt,\n :gmtime, :gmtoff, :isdst, :localtime, :utc]\n if restricted_functions.include? name\n raise NoMethodError, 'undefined method %s for %s' % [name, self]\n end\n result = @time.send(name, *args, &block)\n if result.is_a? Time\n return self.class.new(@api, result, @timezone.identifier)\n else\n return result\n end\n end", "code_tokens": ["def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "restricted_functions", "=", "[", ":dst?", ",", ":getgm", ",", ":getlocal", ",", ":getutc", ",", ":gmt", ",", ":gmtime", ",", ":gmtoff", ",", ":isdst", ",", ":localtime", ",", ":utc", "]", "if", "restricted_functions", ".", "include?", "name", "raise", "NoMethodError", ",", "'undefined method %s for %s'", "%", "[", "name", ",", "self", "]", "end", "result", "=", "@time", ".", "send", "(", "name", ",", "*", "args", ",", "&", "block", ")", "if", "result", ".", "is_a?", "Time", "return", "self", ".", "class", ".", "new", "(", "@api", ",", "result", ",", "@timezone", ".", "identifier", ")", "else", "return", "result", "end", "end"], "docstring": "When an unrecognized method is applied to AdManagerDateTime, pass it\n through to the internal ruby Time.", "docstring_tokens": ["When", "an", "unrecognized", "method", "is", "applied", "to", "AdManagerDateTime", "pass", "it", "through", "to", "the", "internal", "ruby", "Time", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ad_manager_api/lib/ad_manager_api/ad_manager_api_datetime.rb#L172-L186", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.create_savon_client", "original_string": "def create_savon_client(endpoint, namespace)\n client = GoogleAdsSavon::Client.new do |wsdl, httpi|\n wsdl.endpoint = endpoint\n wsdl.namespace = namespace\n AdsCommon::Http.configure_httpi(@config, httpi)\n end\n client.config.raise_errors = false\n client.config.logger.subject = NoopLogger.new\n return client\n end", "language": "ruby", "code": "def create_savon_client(endpoint, namespace)\n client = GoogleAdsSavon::Client.new do |wsdl, httpi|\n wsdl.endpoint = endpoint\n wsdl.namespace = namespace\n AdsCommon::Http.configure_httpi(@config, httpi)\n end\n client.config.raise_errors = false\n client.config.logger.subject = NoopLogger.new\n return client\n end", "code_tokens": ["def", "create_savon_client", "(", "endpoint", ",", "namespace", ")", "client", "=", "GoogleAdsSavon", "::", "Client", ".", "new", "do", "|", "wsdl", ",", "httpi", "|", "wsdl", ".", "endpoint", "=", "endpoint", "wsdl", ".", "namespace", "=", "namespace", "AdsCommon", "::", "Http", ".", "configure_httpi", "(", "@config", ",", "httpi", ")", "end", "client", ".", "config", ".", "raise_errors", "=", "false", "client", ".", "config", ".", "logger", ".", "subject", "=", "NoopLogger", ".", "new", "return", "client", "end"], "docstring": "Creates and sets up Savon client.", "docstring_tokens": ["Creates", "and", "sets", "up", "Savon", "client", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L66-L75", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.get_soap_xml", "original_string": "def get_soap_xml(action_name, args)\n registry = get_service_registry()\n validator = ParametersValidator.new(registry)\n args = validator.validate_args(action_name, args)\n return handle_soap_request(\n action_name.to_sym, true, args, validator.extra_namespaces)\n end", "language": "ruby", "code": "def get_soap_xml(action_name, args)\n registry = get_service_registry()\n validator = ParametersValidator.new(registry)\n args = validator.validate_args(action_name, args)\n return handle_soap_request(\n action_name.to_sym, true, args, validator.extra_namespaces)\n end", "code_tokens": ["def", "get_soap_xml", "(", "action_name", ",", "args", ")", "registry", "=", "get_service_registry", "(", ")", "validator", "=", "ParametersValidator", ".", "new", "(", "registry", ")", "args", "=", "validator", ".", "validate_args", "(", "action_name", ",", "args", ")", "return", "handle_soap_request", "(", "action_name", ".", "to_sym", ",", "true", ",", "args", ",", "validator", ".", "extra_namespaces", ")", "end"], "docstring": "Generates and returns SOAP XML for the specified action and args.", "docstring_tokens": ["Generates", "and", "returns", "SOAP", "XML", "for", "the", "specified", "action", "and", "args", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L78-L84", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.execute_action", "original_string": "def execute_action(action_name, args, &block)\n registry = get_service_registry()\n validator = ParametersValidator.new(registry)\n args = validator.validate_args(action_name, args)\n request_info, response = handle_soap_request(\n action_name.to_sym, false, args, validator.extra_namespaces)\n do_logging(action_name, request_info, response)\n handle_errors(response)\n extractor = ResultsExtractor.new(registry)\n result = extractor.extract_result(response, action_name, &block)\n run_user_block(extractor, response, result, &block) if block_given?\n return result\n end", "language": "ruby", "code": "def execute_action(action_name, args, &block)\n registry = get_service_registry()\n validator = ParametersValidator.new(registry)\n args = validator.validate_args(action_name, args)\n request_info, response = handle_soap_request(\n action_name.to_sym, false, args, validator.extra_namespaces)\n do_logging(action_name, request_info, response)\n handle_errors(response)\n extractor = ResultsExtractor.new(registry)\n result = extractor.extract_result(response, action_name, &block)\n run_user_block(extractor, response, result, &block) if block_given?\n return result\n end", "code_tokens": ["def", "execute_action", "(", "action_name", ",", "args", ",", "&", "block", ")", "registry", "=", "get_service_registry", "(", ")", "validator", "=", "ParametersValidator", ".", "new", "(", "registry", ")", "args", "=", "validator", ".", "validate_args", "(", "action_name", ",", "args", ")", "request_info", ",", "response", "=", "handle_soap_request", "(", "action_name", ".", "to_sym", ",", "false", ",", "args", ",", "validator", ".", "extra_namespaces", ")", "do_logging", "(", "action_name", ",", "request_info", ",", "response", ")", "handle_errors", "(", "response", ")", "extractor", "=", "ResultsExtractor", ".", "new", "(", "registry", ")", "result", "=", "extractor", ".", "extract_result", "(", "response", ",", "action_name", ",", "&", "block", ")", "run_user_block", "(", "extractor", ",", "response", ",", "result", ",", "&", "block", ")", "if", "block_given?", "return", "result", "end"], "docstring": "Executes SOAP action specified as a string with given arguments.", "docstring_tokens": ["Executes", "SOAP", "action", "specified", "as", "a", "string", "with", "given", "arguments", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L87-L99", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.handle_soap_request", "original_string": "def handle_soap_request(action, xml_only, args, extra_namespaces)\n original_action_name =\n get_service_registry.get_method_signature(action)[:original_name]\n original_action_name = action if original_action_name.nil?\n request_info = nil\n response = @client.request(original_action_name) do |soap, wsdl, http|\n soap.body = args\n @header_handler.prepare_request(http, soap)\n soap.namespaces.merge!(extra_namespaces) unless extra_namespaces.nil?\n return soap.to_xml if xml_only\n request_info = RequestInfo.new(soap.to_xml, http.headers, http.url)\n end\n return request_info, response\n end", "language": "ruby", "code": "def handle_soap_request(action, xml_only, args, extra_namespaces)\n original_action_name =\n get_service_registry.get_method_signature(action)[:original_name]\n original_action_name = action if original_action_name.nil?\n request_info = nil\n response = @client.request(original_action_name) do |soap, wsdl, http|\n soap.body = args\n @header_handler.prepare_request(http, soap)\n soap.namespaces.merge!(extra_namespaces) unless extra_namespaces.nil?\n return soap.to_xml if xml_only\n request_info = RequestInfo.new(soap.to_xml, http.headers, http.url)\n end\n return request_info, response\n end", "code_tokens": ["def", "handle_soap_request", "(", "action", ",", "xml_only", ",", "args", ",", "extra_namespaces", ")", "original_action_name", "=", "get_service_registry", ".", "get_method_signature", "(", "action", ")", "[", ":original_name", "]", "original_action_name", "=", "action", "if", "original_action_name", ".", "nil?", "request_info", "=", "nil", "response", "=", "@client", ".", "request", "(", "original_action_name", ")", "do", "|", "soap", ",", "wsdl", ",", "http", "|", "soap", ".", "body", "=", "args", "@header_handler", ".", "prepare_request", "(", "http", ",", "soap", ")", "soap", ".", "namespaces", ".", "merge!", "(", "extra_namespaces", ")", "unless", "extra_namespaces", ".", "nil?", "return", "soap", ".", "to_xml", "if", "xml_only", "request_info", "=", "RequestInfo", ".", "new", "(", "soap", ".", "to_xml", ",", "http", ".", "headers", ",", "http", ".", "url", ")", "end", "return", "request_info", ",", "response", "end"], "docstring": "Executes the SOAP request with original SOAP name.", "docstring_tokens": ["Executes", "the", "SOAP", "request", "with", "original", "SOAP", "name", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L102-L115", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.handle_errors", "original_string": "def handle_errors(response)\n if response.soap_fault?\n exception = exception_for_soap_fault(response)\n raise exception\n end\n if response.http_error?\n raise AdsCommon::Errors::HttpError,\n \"HTTP Error occurred: %s\" % response.http_error\n end\n end", "language": "ruby", "code": "def handle_errors(response)\n if response.soap_fault?\n exception = exception_for_soap_fault(response)\n raise exception\n end\n if response.http_error?\n raise AdsCommon::Errors::HttpError,\n \"HTTP Error occurred: %s\" % response.http_error\n end\n end", "code_tokens": ["def", "handle_errors", "(", "response", ")", "if", "response", ".", "soap_fault?", "exception", "=", "exception_for_soap_fault", "(", "response", ")", "raise", "exception", "end", "if", "response", ".", "http_error?", "raise", "AdsCommon", "::", "Errors", "::", "HttpError", ",", "\"HTTP Error occurred: %s\"", "%", "response", ".", "http_error", "end", "end"], "docstring": "Checks for errors in response and raises appropriate exception.", "docstring_tokens": ["Checks", "for", "errors", "in", "response", "and", "raises", "appropriate", "exception", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L118-L127", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.exception_for_soap_fault", "original_string": "def exception_for_soap_fault(response)\n begin\n fault = response[:fault]\n if fault[:detail] and fault[:detail][:api_exception_fault]\n exception_fault = fault[:detail][:api_exception_fault]\n exception_name = (\n exception_fault[:application_exception_type] ||\n FALLBACK_API_ERROR_EXCEPTION)\n exception_class = get_module().const_get(exception_name)\n return exception_class.new(exception_fault)\n elsif fault[:faultstring]\n fault_message = fault[:faultstring]\n return AdsCommon::Errors::ApiException.new(\n \"Unknown exception with error: %s\" % fault_message)\n else\n raise ArgumentError.new(fault.to_s)\n end\n rescue Exception => e\n return AdsCommon::Errors::ApiException.new(\n \"Failed to resolve exception (%s), SOAP fault: %s\" %\n [e.message, response.soap_fault])\n end\n end", "language": "ruby", "code": "def exception_for_soap_fault(response)\n begin\n fault = response[:fault]\n if fault[:detail] and fault[:detail][:api_exception_fault]\n exception_fault = fault[:detail][:api_exception_fault]\n exception_name = (\n exception_fault[:application_exception_type] ||\n FALLBACK_API_ERROR_EXCEPTION)\n exception_class = get_module().const_get(exception_name)\n return exception_class.new(exception_fault)\n elsif fault[:faultstring]\n fault_message = fault[:faultstring]\n return AdsCommon::Errors::ApiException.new(\n \"Unknown exception with error: %s\" % fault_message)\n else\n raise ArgumentError.new(fault.to_s)\n end\n rescue Exception => e\n return AdsCommon::Errors::ApiException.new(\n \"Failed to resolve exception (%s), SOAP fault: %s\" %\n [e.message, response.soap_fault])\n end\n end", "code_tokens": ["def", "exception_for_soap_fault", "(", "response", ")", "begin", "fault", "=", "response", "[", ":fault", "]", "if", "fault", "[", ":detail", "]", "and", "fault", "[", ":detail", "]", "[", ":api_exception_fault", "]", "exception_fault", "=", "fault", "[", ":detail", "]", "[", ":api_exception_fault", "]", "exception_name", "=", "(", "exception_fault", "[", ":application_exception_type", "]", "||", "FALLBACK_API_ERROR_EXCEPTION", ")", "exception_class", "=", "get_module", "(", ")", ".", "const_get", "(", "exception_name", ")", "return", "exception_class", ".", "new", "(", "exception_fault", ")", "elsif", "fault", "[", ":faultstring", "]", "fault_message", "=", "fault", "[", ":faultstring", "]", "return", "AdsCommon", "::", "Errors", "::", "ApiException", ".", "new", "(", "\"Unknown exception with error: %s\"", "%", "fault_message", ")", "else", "raise", "ArgumentError", ".", "new", "(", "fault", ".", "to_s", ")", "end", "rescue", "Exception", "=>", "e", "return", "AdsCommon", "::", "Errors", "::", "ApiException", ".", "new", "(", "\"Failed to resolve exception (%s), SOAP fault: %s\"", "%", "[", "e", ".", "message", ",", "response", ".", "soap_fault", "]", ")", "end", "end"], "docstring": "Finds an exception object for a given response.", "docstring_tokens": ["Finds", "an", "exception", "object", "for", "a", "given", "response", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L130-L152", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.run_user_block", "original_string": "def run_user_block(extractor, response, body, &block)\n header = extractor.extract_header_data(response)\n case block.arity\n when 1 then yield(header)\n when 2 then yield(header, body)\n else\n raise AdsCommon::Errors::ApiException,\n \"Wrong number of block parameters: %d\" % block.arity\n end\n return nil\n end", "language": "ruby", "code": "def run_user_block(extractor, response, body, &block)\n header = extractor.extract_header_data(response)\n case block.arity\n when 1 then yield(header)\n when 2 then yield(header, body)\n else\n raise AdsCommon::Errors::ApiException,\n \"Wrong number of block parameters: %d\" % block.arity\n end\n return nil\n end", "code_tokens": ["def", "run_user_block", "(", "extractor", ",", "response", ",", "body", ",", "&", "block", ")", "header", "=", "extractor", ".", "extract_header_data", "(", "response", ")", "case", "block", ".", "arity", "when", "1", "then", "yield", "(", "header", ")", "when", "2", "then", "yield", "(", "header", ",", "body", ")", "else", "raise", "AdsCommon", "::", "Errors", "::", "ApiException", ",", "\"Wrong number of block parameters: %d\"", "%", "block", ".", "arity", "end", "return", "nil", "end"], "docstring": "Yields to user-specified block with additional information such as\n headers.", "docstring_tokens": ["Yields", "to", "user", "-", "specified", "block", "with", "additional", "information", "such", "as", "headers", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L156-L166", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.do_logging", "original_string": "def do_logging(action, request, response)\n logger = get_logger()\n return unless should_log_summary(logger.level, response.soap_fault?)\n\n response_hash = response.hash\n\n soap_headers = {}\n begin\n soap_headers = response_hash[:envelope][:header][:response_header]\n rescue NoMethodError\n # If there are no headers, just ignore. We'll log what we know.\n end\n\n summary_message = ('ID: %s, URL: %s, Service: %s, Action: %s, Response ' +\n 'time: %sms, Request ID: %s') % [@header_handler.identifier,\n request.url, self.class.to_s.split(\"::\").last, action,\n soap_headers[:response_time], soap_headers[:request_id]]\n if soap_headers[:operations]\n summary_message += ', Operations: %s' % soap_headers[:operations]\n end\n summary_message += ', Is fault: %s' % response.soap_fault?\n\n request_message = nil\n response_message = nil\n\n if should_log_payloads(logger.level, response.soap_fault?)\n request_message = 'Outgoing request: %s %s' %\n [format_headers(request.headers), sanitize_request(request.body)]\n response_message = 'Incoming response: %s %s' %\n [format_headers(response.http.headers), response.http.body]\n end\n\n if response.soap_fault?\n summary_message += ', Fault message: %s' % format_fault(\n response_hash[:envelope][:body][:fault][:faultstring])\n logger.warn(summary_message)\n logger.info(request_message) unless request_message.nil?\n logger.info(response_message) unless response_message.nil?\n else\n logger.info(summary_message)\n logger.debug(request_message) unless request_message.nil?\n logger.debug(response_message) unless response_message.nil?\n end\n end", "language": "ruby", "code": "def do_logging(action, request, response)\n logger = get_logger()\n return unless should_log_summary(logger.level, response.soap_fault?)\n\n response_hash = response.hash\n\n soap_headers = {}\n begin\n soap_headers = response_hash[:envelope][:header][:response_header]\n rescue NoMethodError\n # If there are no headers, just ignore. We'll log what we know.\n end\n\n summary_message = ('ID: %s, URL: %s, Service: %s, Action: %s, Response ' +\n 'time: %sms, Request ID: %s') % [@header_handler.identifier,\n request.url, self.class.to_s.split(\"::\").last, action,\n soap_headers[:response_time], soap_headers[:request_id]]\n if soap_headers[:operations]\n summary_message += ', Operations: %s' % soap_headers[:operations]\n end\n summary_message += ', Is fault: %s' % response.soap_fault?\n\n request_message = nil\n response_message = nil\n\n if should_log_payloads(logger.level, response.soap_fault?)\n request_message = 'Outgoing request: %s %s' %\n [format_headers(request.headers), sanitize_request(request.body)]\n response_message = 'Incoming response: %s %s' %\n [format_headers(response.http.headers), response.http.body]\n end\n\n if response.soap_fault?\n summary_message += ', Fault message: %s' % format_fault(\n response_hash[:envelope][:body][:fault][:faultstring])\n logger.warn(summary_message)\n logger.info(request_message) unless request_message.nil?\n logger.info(response_message) unless response_message.nil?\n else\n logger.info(summary_message)\n logger.debug(request_message) unless request_message.nil?\n logger.debug(response_message) unless response_message.nil?\n end\n end", "code_tokens": ["def", "do_logging", "(", "action", ",", "request", ",", "response", ")", "logger", "=", "get_logger", "(", ")", "return", "unless", "should_log_summary", "(", "logger", ".", "level", ",", "response", ".", "soap_fault?", ")", "response_hash", "=", "response", ".", "hash", "soap_headers", "=", "{", "}", "begin", "soap_headers", "=", "response_hash", "[", ":envelope", "]", "[", ":header", "]", "[", ":response_header", "]", "rescue", "NoMethodError", "end", "summary_message", "=", "(", "'ID: %s, URL: %s, Service: %s, Action: %s, Response '", "+", "'time: %sms, Request ID: %s'", ")", "%", "[", "@header_handler", ".", "identifier", ",", "request", ".", "url", ",", "self", ".", "class", ".", "to_s", ".", "split", "(", "\"::\"", ")", ".", "last", ",", "action", ",", "soap_headers", "[", ":response_time", "]", ",", "soap_headers", "[", ":request_id", "]", "]", "if", "soap_headers", "[", ":operations", "]", "summary_message", "+=", "', Operations: %s'", "%", "soap_headers", "[", ":operations", "]", "end", "summary_message", "+=", "', Is fault: %s'", "%", "response", ".", "soap_fault?", "request_message", "=", "nil", "response_message", "=", "nil", "if", "should_log_payloads", "(", "logger", ".", "level", ",", "response", ".", "soap_fault?", ")", "request_message", "=", "'Outgoing request: %s %s'", "%", "[", "format_headers", "(", "request", ".", "headers", ")", ",", "sanitize_request", "(", "request", ".", "body", ")", "]", "response_message", "=", "'Incoming response: %s %s'", "%", "[", "format_headers", "(", "response", ".", "http", ".", "headers", ")", ",", "response", ".", "http", ".", "body", "]", "end", "if", "response", ".", "soap_fault?", "summary_message", "+=", "', Fault message: %s'", "%", "format_fault", "(", "response_hash", "[", ":envelope", "]", "[", ":body", "]", "[", ":fault", "]", "[", ":faultstring", "]", ")", "logger", ".", "warn", "(", "summary_message", ")", "logger", ".", "info", "(", "request_message", ")", "unless", "request_message", ".", "nil?", "logger", ".", "info", "(", "response_message", ")", "unless", "response_message", ".", "nil?", "else", "logger", ".", "info", "(", "summary_message", ")", "logger", ".", "debug", "(", "request_message", ")", "unless", "request_message", ".", "nil?", "logger", ".", "debug", "(", "response_message", ")", "unless", "response_message", ".", "nil?", "end", "end"], "docstring": "Log the request, response, and summary lines.", "docstring_tokens": ["Log", "the", "request", "response", "and", "summary", "lines", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L169-L212", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.format_headers", "original_string": "def format_headers(headers)\n return headers.map do |k, v|\n v = REDACTED_STR if k == 'Authorization'\n [k, v].join(': ')\n end.join(', ')\n end", "language": "ruby", "code": "def format_headers(headers)\n return headers.map do |k, v|\n v = REDACTED_STR if k == 'Authorization'\n [k, v].join(': ')\n end.join(', ')\n end", "code_tokens": ["def", "format_headers", "(", "headers", ")", "return", "headers", ".", "map", "do", "|", "k", ",", "v", "|", "v", "=", "REDACTED_STR", "if", "k", "==", "'Authorization'", "[", "k", ",", "v", "]", ".", "join", "(", "': '", ")", "end", ".", "join", "(", "', '", ")", "end"], "docstring": "Format headers, redacting sensitive information.", "docstring_tokens": ["Format", "headers", "redacting", "sensitive", "information", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L215-L220", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.format_fault", "original_string": "def format_fault(message)\n if message.length > MAX_FAULT_LOG_LENGTH\n message = message[0, MAX_FAULT_LOG_LENGTH]\n end\n return message.gsub(\"\\n\", ' ')\n end", "language": "ruby", "code": "def format_fault(message)\n if message.length > MAX_FAULT_LOG_LENGTH\n message = message[0, MAX_FAULT_LOG_LENGTH]\n end\n return message.gsub(\"\\n\", ' ')\n end", "code_tokens": ["def", "format_fault", "(", "message", ")", "if", "message", ".", "length", ">", "MAX_FAULT_LOG_LENGTH", "message", "=", "message", "[", "0", ",", "MAX_FAULT_LOG_LENGTH", "]", "end", "return", "message", ".", "gsub", "(", "\"\\n\"", ",", "' '", ")", "end"], "docstring": "Format the fault message by capping length and removing newlines.", "docstring_tokens": ["Format", "the", "fault", "message", "by", "capping", "length", "and", "removing", "newlines", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L229-L234", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.should_log_summary", "original_string": "def should_log_summary(level, is_fault)\n # Fault summaries log at WARN.\n return level <= Logger::WARN if is_fault\n # Success summaries log at INFO.\n return level <= Logger::INFO\n end", "language": "ruby", "code": "def should_log_summary(level, is_fault)\n # Fault summaries log at WARN.\n return level <= Logger::WARN if is_fault\n # Success summaries log at INFO.\n return level <= Logger::INFO\n end", "code_tokens": ["def", "should_log_summary", "(", "level", ",", "is_fault", ")", "return", "level", "<=", "Logger", "::", "WARN", "if", "is_fault", "return", "level", "<=", "Logger", "::", "INFO", "end"], "docstring": "Check whether or not to log request summaries based on log level.", "docstring_tokens": ["Check", "whether", "or", "not", "to", "log", "request", "summaries", "based", "on", "log", "level", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L237-L242", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/savon_service.rb", "func_name": "AdsCommon.SavonService.should_log_payloads", "original_string": "def should_log_payloads(level, is_fault)\n # Fault payloads log at INFO.\n return level <= Logger::INFO if is_fault\n # Success payloads log at DEBUG.\n return level <= Logger::DEBUG\n end", "language": "ruby", "code": "def should_log_payloads(level, is_fault)\n # Fault payloads log at INFO.\n return level <= Logger::INFO if is_fault\n # Success payloads log at DEBUG.\n return level <= Logger::DEBUG\n end", "code_tokens": ["def", "should_log_payloads", "(", "level", ",", "is_fault", ")", "return", "level", "<=", "Logger", "::", "INFO", "if", "is_fault", "return", "level", "<=", "Logger", "::", "DEBUG", "end"], "docstring": "Check whether or not to log payloads based on log level.", "docstring_tokens": ["Check", "whether", "or", "not", "to", "log", "payloads", "based", "on", "log", "level", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/savon_service.rb#L245-L250", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.download_report_as_file", "original_string": "def download_report_as_file(report_definition, path, cid = nil)\n report_body = download_report(report_definition, cid)\n save_to_file(report_body, path)\n return nil\n end", "language": "ruby", "code": "def download_report_as_file(report_definition, path, cid = nil)\n report_body = download_report(report_definition, cid)\n save_to_file(report_body, path)\n return nil\n end", "code_tokens": ["def", "download_report_as_file", "(", "report_definition", ",", "path", ",", "cid", "=", "nil", ")", "report_body", "=", "download_report", "(", "report_definition", ",", "cid", ")", "save_to_file", "(", "report_body", ",", "path", ")", "return", "nil", "end"], "docstring": "Downloads a report and saves it to a file.\n\n Args:\n - report_definition: definition of the report in XML text or hash\n - path: path to save report to\n - cid: optional customer ID to run against\n\n Returns:\n - nil\n\n Raises:\n - AdwordsApi::Errors::InvalidReportDefinitionError if the report\n definition is invalid\n - AdwordsApi::Errors::ReportError if server-side error occurred", "docstring_tokens": ["Downloads", "a", "report", "and", "saves", "it", "to", "a", "file", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L74-L78", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.download_report_as_file_with_awql", "original_string": "def download_report_as_file_with_awql(report_query, format, path, cid = nil)\n report_body = download_report_with_awql(report_query, format, cid)\n save_to_file(report_body, path)\n return nil\n end", "language": "ruby", "code": "def download_report_as_file_with_awql(report_query, format, path, cid = nil)\n report_body = download_report_with_awql(report_query, format, cid)\n save_to_file(report_body, path)\n return nil\n end", "code_tokens": ["def", "download_report_as_file_with_awql", "(", "report_query", ",", "format", ",", "path", ",", "cid", "=", "nil", ")", "report_body", "=", "download_report_with_awql", "(", "report_query", ",", "format", ",", "cid", ")", "save_to_file", "(", "report_body", ",", "path", ")", "return", "nil", "end"], "docstring": "Downloads a report with AWQL and saves it to a file.\n\n Args:\n - report_query: query for the report as string\n - format: format for the report as string\n - path: path to save report to\n - cid: optional customer ID to run report against\n\n Returns:\n - nil\n\n Raises:\n - AdwordsApi::Errors::ReportError if server-side error occurred", "docstring_tokens": ["Downloads", "a", "report", "with", "AWQL", "and", "saves", "it", "to", "a", "file", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L150-L154", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.download_report_as_stream_with_awql", "original_string": "def download_report_as_stream_with_awql(\n report_query, format, cid = nil, &block)\n return get_report_response_with_awql(report_query, format, cid, &block)\n end", "language": "ruby", "code": "def download_report_as_stream_with_awql(\n report_query, format, cid = nil, &block)\n return get_report_response_with_awql(report_query, format, cid, &block)\n end", "code_tokens": ["def", "download_report_as_stream_with_awql", "(", "report_query", ",", "format", ",", "cid", "=", "nil", ",", "&", "block", ")", "return", "get_report_response_with_awql", "(", "report_query", ",", "format", ",", "cid", ",", "&", "block", ")", "end"], "docstring": "Streams a report with AWQL as a string to the given block. This method\n will not do error checking on returned values.\n\n Args:\n - report_query: query for the report as string\n - format: format for the report as string\n - cid: optional customer ID to run report against\n\n Returns:\n - nil", "docstring_tokens": ["Streams", "a", "report", "with", "AWQL", "as", "a", "string", "to", "the", "given", "block", ".", "This", "method", "will", "not", "do", "error", "checking", "on", "returned", "values", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L167-L170", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.get_stream_helper_with_awql", "original_string": "def get_stream_helper_with_awql(report_query, format, cid = nil)\n return AdwordsApi::ReportStream.set_up_with_awql(\n self, report_query, format, cid)\n end", "language": "ruby", "code": "def get_stream_helper_with_awql(report_query, format, cid = nil)\n return AdwordsApi::ReportStream.set_up_with_awql(\n self, report_query, format, cid)\n end", "code_tokens": ["def", "get_stream_helper_with_awql", "(", "report_query", ",", "format", ",", "cid", "=", "nil", ")", "return", "AdwordsApi", "::", "ReportStream", ".", "set_up_with_awql", "(", "self", ",", "report_query", ",", "format", ",", "cid", ")", "end"], "docstring": "Returns a helper object that can manage breaking the streamed report\n results into individual lines.\n\n Args:\n - report_query: query for the report as string\n - format: format for the report as string\n - cid: optional customer ID to run report against\n\n Returns:\n - ReportStream object initialized to begin streaming.", "docstring_tokens": ["Returns", "a", "helper", "object", "that", "can", "manage", "breaking", "the", "streamed", "report", "results", "into", "individual", "lines", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L183-L186", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.get_report_response", "original_string": "def get_report_response(report_definition, cid, &block)\n definition_text = get_report_definition_text(report_definition)\n data = '__rdxml=%s' % CGI.escape(definition_text)\n return make_adhoc_request(data, cid, &block)\n end", "language": "ruby", "code": "def get_report_response(report_definition, cid, &block)\n definition_text = get_report_definition_text(report_definition)\n data = '__rdxml=%s' % CGI.escape(definition_text)\n return make_adhoc_request(data, cid, &block)\n end", "code_tokens": ["def", "get_report_response", "(", "report_definition", ",", "cid", ",", "&", "block", ")", "definition_text", "=", "get_report_definition_text", "(", "report_definition", ")", "data", "=", "'__rdxml=%s'", "%", "CGI", ".", "escape", "(", "definition_text", ")", "return", "make_adhoc_request", "(", "data", ",", "cid", ",", "&", "block", ")", "end"], "docstring": "Send POST request for a report and returns Response object.", "docstring_tokens": ["Send", "POST", "request", "for", "a", "report", "and", "returns", "Response", "object", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L206-L210", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.get_report_response_with_awql", "original_string": "def get_report_response_with_awql(report_query, format, cid, &block)\n data = '__rdquery=%s&__fmt=%s' %\n [CGI.escape(report_query), CGI.escape(format)]\n return make_adhoc_request(data, cid, &block)\n end", "language": "ruby", "code": "def get_report_response_with_awql(report_query, format, cid, &block)\n data = '__rdquery=%s&__fmt=%s' %\n [CGI.escape(report_query), CGI.escape(format)]\n return make_adhoc_request(data, cid, &block)\n end", "code_tokens": ["def", "get_report_response_with_awql", "(", "report_query", ",", "format", ",", "cid", ",", "&", "block", ")", "data", "=", "'__rdquery=%s&__fmt=%s'", "%", "[", "CGI", ".", "escape", "(", "report_query", ")", ",", "CGI", ".", "escape", "(", "format", ")", "]", "return", "make_adhoc_request", "(", "data", ",", "cid", ",", "&", "block", ")", "end"], "docstring": "Send POST request for a report with AWQL and returns Response object.", "docstring_tokens": ["Send", "POST", "request", "for", "a", "report", "with", "AWQL", "and", "returns", "Response", "object", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L213-L217", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.make_adhoc_request", "original_string": "def make_adhoc_request(data, cid, &block)\n @api.utils_reporter.report_utils_used()\n url = @api.api_config.adhoc_report_download_url(@version)\n headers = get_report_request_headers(url, cid)\n log_request(url, headers, data)\n # A given block indicates that we should make a stream request and yield\n # the results, rather than return a full response.\n if block_given?\n AdsCommon::Http.post_stream(url, data, @api.config, headers, &block)\n return nil\n else\n response = AdsCommon::Http.post_response(\n url, data, @api.config, headers)\n log_headers(response.headers)\n check_for_errors(response)\n return response\n end\n end", "language": "ruby", "code": "def make_adhoc_request(data, cid, &block)\n @api.utils_reporter.report_utils_used()\n url = @api.api_config.adhoc_report_download_url(@version)\n headers = get_report_request_headers(url, cid)\n log_request(url, headers, data)\n # A given block indicates that we should make a stream request and yield\n # the results, rather than return a full response.\n if block_given?\n AdsCommon::Http.post_stream(url, data, @api.config, headers, &block)\n return nil\n else\n response = AdsCommon::Http.post_response(\n url, data, @api.config, headers)\n log_headers(response.headers)\n check_for_errors(response)\n return response\n end\n end", "code_tokens": ["def", "make_adhoc_request", "(", "data", ",", "cid", ",", "&", "block", ")", "@api", ".", "utils_reporter", ".", "report_utils_used", "(", ")", "url", "=", "@api", ".", "api_config", ".", "adhoc_report_download_url", "(", "@version", ")", "headers", "=", "get_report_request_headers", "(", "url", ",", "cid", ")", "log_request", "(", "url", ",", "headers", ",", "data", ")", "if", "block_given?", "AdsCommon", "::", "Http", ".", "post_stream", "(", "url", ",", "data", ",", "@api", ".", "config", ",", "headers", ",", "&", "block", ")", "return", "nil", "else", "response", "=", "AdsCommon", "::", "Http", ".", "post_response", "(", "url", ",", "data", ",", "@api", ".", "config", ",", "headers", ")", "log_headers", "(", "response", ".", "headers", ")", "check_for_errors", "(", "response", ")", "return", "response", "end", "end"], "docstring": "Makes request and AdHoc service and returns response.", "docstring_tokens": ["Makes", "request", "and", "AdHoc", "service", "and", "returns", "response", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L220-L237", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.get_report_request_headers", "original_string": "def get_report_request_headers(url, cid)\n @header_handler ||= AdwordsApi::ReportHeaderHandler.new(\n @api.credential_handler, @api.get_auth_handler(), @api.config)\n return @header_handler.headers(url, cid)\n end", "language": "ruby", "code": "def get_report_request_headers(url, cid)\n @header_handler ||= AdwordsApi::ReportHeaderHandler.new(\n @api.credential_handler, @api.get_auth_handler(), @api.config)\n return @header_handler.headers(url, cid)\n end", "code_tokens": ["def", "get_report_request_headers", "(", "url", ",", "cid", ")", "@header_handler", "||=", "AdwordsApi", "::", "ReportHeaderHandler", ".", "new", "(", "@api", ".", "credential_handler", ",", "@api", ".", "get_auth_handler", "(", ")", ",", "@api", ".", "config", ")", "return", "@header_handler", ".", "headers", "(", "url", ",", "cid", ")", "end"], "docstring": "Prepares headers for report request.", "docstring_tokens": ["Prepares", "headers", "for", "report", "request", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L253-L257", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.save_to_file", "original_string": "def save_to_file(data, path)\n open(path, 'wb') { |file| file.write(data) } if path\n end", "language": "ruby", "code": "def save_to_file(data, path)\n open(path, 'wb') { |file| file.write(data) } if path\n end", "code_tokens": ["def", "save_to_file", "(", "data", ",", "path", ")", "open", "(", "path", ",", "'wb'", ")", "{", "|", "file", "|", "file", ".", "write", "(", "data", ")", "}", "if", "path", "end"], "docstring": "Saves raw data to a file.", "docstring_tokens": ["Saves", "raw", "data", "to", "a", "file", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L260-L262", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.log_headers", "original_string": "def log_headers(headers)\n @api.logger.debug('HTTP headers: [%s]' %\n (headers.map { |k, v| [k, v].join(': ') }.join(', ')))\n end", "language": "ruby", "code": "def log_headers(headers)\n @api.logger.debug('HTTP headers: [%s]' %\n (headers.map { |k, v| [k, v].join(': ') }.join(', ')))\n end", "code_tokens": ["def", "log_headers", "(", "headers", ")", "@api", ".", "logger", ".", "debug", "(", "'HTTP headers: [%s]'", "%", "(", "headers", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ",", "v", "]", ".", "join", "(", "': '", ")", "}", ".", "join", "(", "', '", ")", ")", ")", "end"], "docstring": "Logs HTTP headers on debug level.", "docstring_tokens": ["Logs", "HTTP", "headers", "on", "debug", "level", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L272-L275", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.check_for_errors", "original_string": "def check_for_errors(response)\n # Check for error code.\n if response.code != 200\n # Check for error in body.\n report_body = response.body\n check_for_xml_error(report_body, response.code)\n # No XML error found nor raised, falling back to a default message.\n raise AdwordsApi::Errors::ReportError.new(response.code,\n 'HTTP code: %d, body: %s' % [response.code, response.body])\n end\n return nil\n end", "language": "ruby", "code": "def check_for_errors(response)\n # Check for error code.\n if response.code != 200\n # Check for error in body.\n report_body = response.body\n check_for_xml_error(report_body, response.code)\n # No XML error found nor raised, falling back to a default message.\n raise AdwordsApi::Errors::ReportError.new(response.code,\n 'HTTP code: %d, body: %s' % [response.code, response.body])\n end\n return nil\n end", "code_tokens": ["def", "check_for_errors", "(", "response", ")", "if", "response", ".", "code", "!=", "200", "report_body", "=", "response", ".", "body", "check_for_xml_error", "(", "report_body", ",", "response", ".", "code", ")", "raise", "AdwordsApi", "::", "Errors", "::", "ReportError", ".", "new", "(", "response", ".", "code", ",", "'HTTP code: %d, body: %s'", "%", "[", "response", ".", "code", ",", "response", ".", "body", "]", ")", "end", "return", "nil", "end"], "docstring": "Checks downloaded data for error signature. Raises ReportError if it\n detects an error.", "docstring_tokens": ["Checks", "downloaded", "data", "for", "error", "signature", ".", "Raises", "ReportError", "if", "it", "detects", "an", "error", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L279-L290", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.check_for_xml_error", "original_string": "def check_for_xml_error(report_body, response_code)\n unless report_body.nil?\n error_response = get_nori().parse(report_body)\n if error_response.include?(:report_download_error) and\n error_response[:report_download_error].include?(:api_error)\n api_error = error_response[:report_download_error][:api_error]\n raise AdwordsApi::Errors::ReportXmlError.new(response_code,\n api_error[:type], api_error[:trigger], api_error[:field_path])\n end\n end\n end", "language": "ruby", "code": "def check_for_xml_error(report_body, response_code)\n unless report_body.nil?\n error_response = get_nori().parse(report_body)\n if error_response.include?(:report_download_error) and\n error_response[:report_download_error].include?(:api_error)\n api_error = error_response[:report_download_error][:api_error]\n raise AdwordsApi::Errors::ReportXmlError.new(response_code,\n api_error[:type], api_error[:trigger], api_error[:field_path])\n end\n end\n end", "code_tokens": ["def", "check_for_xml_error", "(", "report_body", ",", "response_code", ")", "unless", "report_body", ".", "nil?", "error_response", "=", "get_nori", "(", ")", ".", "parse", "(", "report_body", ")", "if", "error_response", ".", "include?", "(", ":report_download_error", ")", "and", "error_response", "[", ":report_download_error", "]", ".", "include?", "(", ":api_error", ")", "api_error", "=", "error_response", "[", ":report_download_error", "]", "[", ":api_error", "]", "raise", "AdwordsApi", "::", "Errors", "::", "ReportXmlError", ".", "new", "(", "response_code", ",", "api_error", "[", ":type", "]", ",", "api_error", "[", ":trigger", "]", ",", "api_error", "[", ":field_path", "]", ")", "end", "end", "end"], "docstring": "Checks for an XML error in the response body and raises an exception if\n it was found.", "docstring_tokens": ["Checks", "for", "an", "XML", "error", "in", "the", "response", "body", "and", "raises", "an", "exception", "if", "it", "was", "found", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L294-L304", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.report_definition_to_xml", "original_string": "def report_definition_to_xml(report_definition)\n check_report_definition_hash(report_definition)\n add_report_definition_hash_order(report_definition)\n begin\n return Gyoku.xml({:report_definition => report_definition})\n rescue ArgumentError => e\n if e.message.include?(\"order!\")\n unknown_fields =\n e.message.slice(e.message.index('['), e.message.length)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n \"Unknown report definition field(s): %s\" % unknown_fields\n end\n raise e\n end\n end", "language": "ruby", "code": "def report_definition_to_xml(report_definition)\n check_report_definition_hash(report_definition)\n add_report_definition_hash_order(report_definition)\n begin\n return Gyoku.xml({:report_definition => report_definition})\n rescue ArgumentError => e\n if e.message.include?(\"order!\")\n unknown_fields =\n e.message.slice(e.message.index('['), e.message.length)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n \"Unknown report definition field(s): %s\" % unknown_fields\n end\n raise e\n end\n end", "code_tokens": ["def", "report_definition_to_xml", "(", "report_definition", ")", "check_report_definition_hash", "(", "report_definition", ")", "add_report_definition_hash_order", "(", "report_definition", ")", "begin", "return", "Gyoku", ".", "xml", "(", "{", ":report_definition", "=>", "report_definition", "}", ")", "rescue", "ArgumentError", "=>", "e", "if", "e", ".", "message", ".", "include?", "(", "\"order!\"", ")", "unknown_fields", "=", "e", ".", "message", ".", "slice", "(", "e", ".", "message", ".", "index", "(", "'['", ")", ",", "e", ".", "message", ".", "length", ")", "raise", "AdwordsApi", "::", "Errors", "::", "InvalidReportDefinitionError", ",", "\"Unknown report definition field(s): %s\"", "%", "unknown_fields", "end", "raise", "e", "end", "end"], "docstring": "Renders a report definition hash into XML text.", "docstring_tokens": ["Renders", "a", "report", "definition", "hash", "into", "XML", "text", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L307-L321", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.check_report_definition_hash", "original_string": "def check_report_definition_hash(report_definition)\n # Minimal set of fields required.\n REQUIRED_FIELDS.each do |field|\n unless report_definition.include?(field)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n \"Required field '%s' is missing in the definition\" % field\n end\n end\n # Fields list is also required.\n unless report_definition[:selector].include?(:fields)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n 'Fields list is required'\n end\n # 'Fields' must be an Array.\n unless report_definition[:selector][:fields].kind_of?(Array)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n 'Fields list must be an array'\n end\n # We should request at least one field.\n if report_definition[:selector][:fields].empty?\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n 'At least one field needs to be requested'\n end\n end", "language": "ruby", "code": "def check_report_definition_hash(report_definition)\n # Minimal set of fields required.\n REQUIRED_FIELDS.each do |field|\n unless report_definition.include?(field)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n \"Required field '%s' is missing in the definition\" % field\n end\n end\n # Fields list is also required.\n unless report_definition[:selector].include?(:fields)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n 'Fields list is required'\n end\n # 'Fields' must be an Array.\n unless report_definition[:selector][:fields].kind_of?(Array)\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n 'Fields list must be an array'\n end\n # We should request at least one field.\n if report_definition[:selector][:fields].empty?\n raise AdwordsApi::Errors::InvalidReportDefinitionError,\n 'At least one field needs to be requested'\n end\n end", "code_tokens": ["def", "check_report_definition_hash", "(", "report_definition", ")", "REQUIRED_FIELDS", ".", "each", "do", "|", "field", "|", "unless", "report_definition", ".", "include?", "(", "field", ")", "raise", "AdwordsApi", "::", "Errors", "::", "InvalidReportDefinitionError", ",", "\"Required field '%s' is missing in the definition\"", "%", "field", "end", "end", "unless", "report_definition", "[", ":selector", "]", ".", "include?", "(", ":fields", ")", "raise", "AdwordsApi", "::", "Errors", "::", "InvalidReportDefinitionError", ",", "'Fields list is required'", "end", "unless", "report_definition", "[", ":selector", "]", "[", ":fields", "]", ".", "kind_of?", "(", "Array", ")", "raise", "AdwordsApi", "::", "Errors", "::", "InvalidReportDefinitionError", ",", "'Fields list must be an array'", "end", "if", "report_definition", "[", ":selector", "]", "[", ":fields", "]", ".", "empty?", "raise", "AdwordsApi", "::", "Errors", "::", "InvalidReportDefinitionError", ",", "'At least one field needs to be requested'", "end", "end"], "docstring": "Checks if the report definition looks correct.", "docstring_tokens": ["Checks", "if", "the", "report", "definition", "looks", "correct", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L324-L347", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_utils.rb", "func_name": "AdwordsApi.ReportUtils.add_report_definition_hash_order", "original_string": "def add_report_definition_hash_order(node, name = :root)\n def_order = REPORT_DEFINITION_ORDER[name]\n var_order = def_order.reject { |field| !node.include?(field) }\n node.keys.each do |key|\n if REPORT_DEFINITION_ORDER.include?(key)\n case node[key]\n when Hash\n add_report_definition_hash_order(node[key], key)\n when Array\n node[key].each do |item|\n add_report_definition_hash_order(item, key)\n end\n end\n end\n end\n node[:order!] = var_order\n return nil\n end", "language": "ruby", "code": "def add_report_definition_hash_order(node, name = :root)\n def_order = REPORT_DEFINITION_ORDER[name]\n var_order = def_order.reject { |field| !node.include?(field) }\n node.keys.each do |key|\n if REPORT_DEFINITION_ORDER.include?(key)\n case node[key]\n when Hash\n add_report_definition_hash_order(node[key], key)\n when Array\n node[key].each do |item|\n add_report_definition_hash_order(item, key)\n end\n end\n end\n end\n node[:order!] = var_order\n return nil\n end", "code_tokens": ["def", "add_report_definition_hash_order", "(", "node", ",", "name", "=", ":root", ")", "def_order", "=", "REPORT_DEFINITION_ORDER", "[", "name", "]", "var_order", "=", "def_order", ".", "reject", "{", "|", "field", "|", "!", "node", ".", "include?", "(", "field", ")", "}", "node", ".", "keys", ".", "each", "do", "|", "key", "|", "if", "REPORT_DEFINITION_ORDER", ".", "include?", "(", "key", ")", "case", "node", "[", "key", "]", "when", "Hash", "add_report_definition_hash_order", "(", "node", "[", "key", "]", ",", "key", ")", "when", "Array", "node", "[", "key", "]", ".", "each", "do", "|", "item", "|", "add_report_definition_hash_order", "(", "item", ",", "key", ")", "end", "end", "end", "end", "node", "[", ":order!", "]", "=", "var_order", "return", "nil", "end"], "docstring": "Adds fields order hint to generator based on specification.", "docstring_tokens": ["Adds", "fields", "order", "hint", "to", "generator", "based", "on", "specification", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_utils.rb#L350-L367", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "adwords_api/lib/adwords_api/report_header_handler.rb", "func_name": "AdwordsApi.ReportHeaderHandler.headers", "original_string": "def headers(url, cid)\n override = (cid.nil?) ? nil : {:client_customer_id => cid}\n credentials = @credential_handler.credentials(override)\n headers = {\n 'Content-Type' => 'application/x-www-form-urlencoded',\n 'Authorization' => @auth_handler.auth_string(credentials),\n 'User-Agent' => @credential_handler.generate_user_agent(),\n 'clientCustomerId' => credentials[:client_customer_id].to_s,\n 'developerToken' => credentials[:developer_token]\n }\n skip_report_header = @config.read('library.skip_report_header')\n unless skip_report_header.nil?\n headers['skipReportHeader'] = skip_report_header.to_s\n end\n skip_report_summary = @config.read('library.skip_report_summary')\n unless skip_report_summary.nil?\n headers['skipReportSummary'] = skip_report_summary.to_s\n end\n skip_column_header = @config.read('library.skip_column_header')\n unless skip_column_header.nil?\n headers['skipColumnHeader'] = skip_column_header.to_s\n end\n include_zero_impressions =\n @config.read('library.include_zero_impressions')\n unless include_zero_impressions.nil?\n headers['includeZeroImpressions'] = include_zero_impressions.to_s\n end\n use_raw_enum_values =\n @config.read('library.use_raw_enum_values')\n unless use_raw_enum_values.nil?\n headers['useRawEnumValues'] = use_raw_enum_values.to_s\n end\n return headers\n end", "language": "ruby", "code": "def headers(url, cid)\n override = (cid.nil?) ? nil : {:client_customer_id => cid}\n credentials = @credential_handler.credentials(override)\n headers = {\n 'Content-Type' => 'application/x-www-form-urlencoded',\n 'Authorization' => @auth_handler.auth_string(credentials),\n 'User-Agent' => @credential_handler.generate_user_agent(),\n 'clientCustomerId' => credentials[:client_customer_id].to_s,\n 'developerToken' => credentials[:developer_token]\n }\n skip_report_header = @config.read('library.skip_report_header')\n unless skip_report_header.nil?\n headers['skipReportHeader'] = skip_report_header.to_s\n end\n skip_report_summary = @config.read('library.skip_report_summary')\n unless skip_report_summary.nil?\n headers['skipReportSummary'] = skip_report_summary.to_s\n end\n skip_column_header = @config.read('library.skip_column_header')\n unless skip_column_header.nil?\n headers['skipColumnHeader'] = skip_column_header.to_s\n end\n include_zero_impressions =\n @config.read('library.include_zero_impressions')\n unless include_zero_impressions.nil?\n headers['includeZeroImpressions'] = include_zero_impressions.to_s\n end\n use_raw_enum_values =\n @config.read('library.use_raw_enum_values')\n unless use_raw_enum_values.nil?\n headers['useRawEnumValues'] = use_raw_enum_values.to_s\n end\n return headers\n end", "code_tokens": ["def", "headers", "(", "url", ",", "cid", ")", "override", "=", "(", "cid", ".", "nil?", ")", "?", "nil", ":", "{", ":client_customer_id", "=>", "cid", "}", "credentials", "=", "@credential_handler", ".", "credentials", "(", "override", ")", "headers", "=", "{", "'Content-Type'", "=>", "'application/x-www-form-urlencoded'", ",", "'Authorization'", "=>", "@auth_handler", ".", "auth_string", "(", "credentials", ")", ",", "'User-Agent'", "=>", "@credential_handler", ".", "generate_user_agent", "(", ")", ",", "'clientCustomerId'", "=>", "credentials", "[", ":client_customer_id", "]", ".", "to_s", ",", "'developerToken'", "=>", "credentials", "[", ":developer_token", "]", "}", "skip_report_header", "=", "@config", ".", "read", "(", "'library.skip_report_header'", ")", "unless", "skip_report_header", ".", "nil?", "headers", "[", "'skipReportHeader'", "]", "=", "skip_report_header", ".", "to_s", "end", "skip_report_summary", "=", "@config", ".", "read", "(", "'library.skip_report_summary'", ")", "unless", "skip_report_summary", ".", "nil?", "headers", "[", "'skipReportSummary'", "]", "=", "skip_report_summary", ".", "to_s", "end", "skip_column_header", "=", "@config", ".", "read", "(", "'library.skip_column_header'", ")", "unless", "skip_column_header", ".", "nil?", "headers", "[", "'skipColumnHeader'", "]", "=", "skip_column_header", ".", "to_s", "end", "include_zero_impressions", "=", "@config", ".", "read", "(", "'library.include_zero_impressions'", ")", "unless", "include_zero_impressions", ".", "nil?", "headers", "[", "'includeZeroImpressions'", "]", "=", "include_zero_impressions", ".", "to_s", "end", "use_raw_enum_values", "=", "@config", ".", "read", "(", "'library.use_raw_enum_values'", ")", "unless", "use_raw_enum_values", ".", "nil?", "headers", "[", "'useRawEnumValues'", "]", "=", "use_raw_enum_values", ".", "to_s", "end", "return", "headers", "end"], "docstring": "Initializes a header handler.\n\n Args:\n - credential_handler: a header with credential data\n - auth_handler: a header with auth data\n - config: API config\n\n Returns the headers set for the report request.\n\n Args:\n - url: URL for the report requests\n - cid: clientCustomerId to use\n\n Returns:\n - a Hash with HTTP headers.", "docstring_tokens": ["Initializes", "a", "header", "handler", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api/report_header_handler.rb#L45-L78", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/credential_handler.rb", "func_name": "AdsCommon.CredentialHandler.credentials", "original_string": "def credentials(credentials_override = nil)\n credentials = @credentials.dup()\n credentials.merge!(credentials_override) unless credentials_override.nil?\n return credentials\n end", "language": "ruby", "code": "def credentials(credentials_override = nil)\n credentials = @credentials.dup()\n credentials.merge!(credentials_override) unless credentials_override.nil?\n return credentials\n end", "code_tokens": ["def", "credentials", "(", "credentials_override", "=", "nil", ")", "credentials", "=", "@credentials", ".", "dup", "(", ")", "credentials", ".", "merge!", "(", "credentials_override", ")", "unless", "credentials_override", ".", "nil?", "return", "credentials", "end"], "docstring": "Initializes CredentialHandler.\n Returns credentials set for the next call.", "docstring_tokens": ["Initializes", "CredentialHandler", ".", "Returns", "credentials", "set", "for", "the", "next", "call", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/credential_handler.rb#L36-L40", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/credential_handler.rb", "func_name": "AdsCommon.CredentialHandler.credentials=", "original_string": "def credentials=(new_credentials)\n # Find new and changed properties.\n diff = new_credentials.inject([]) do |result, (key, value)|\n result << [key, value] if value != @credentials[key]\n result\n end\n\n # Find removed properties.\n diff = @credentials.inject(diff) do |result, (key, _)|\n result << [key, nil] unless new_credentials.include?(key)\n result\n end\n\n # Set each property.\n diff.each { |entry| set_credential(entry[0], entry[1]) }\n\n return nil\n end", "language": "ruby", "code": "def credentials=(new_credentials)\n # Find new and changed properties.\n diff = new_credentials.inject([]) do |result, (key, value)|\n result << [key, value] if value != @credentials[key]\n result\n end\n\n # Find removed properties.\n diff = @credentials.inject(diff) do |result, (key, _)|\n result << [key, nil] unless new_credentials.include?(key)\n result\n end\n\n # Set each property.\n diff.each { |entry| set_credential(entry[0], entry[1]) }\n\n return nil\n end", "code_tokens": ["def", "credentials", "=", "(", "new_credentials", ")", "diff", "=", "new_credentials", ".", "inject", "(", "[", "]", ")", "do", "|", "result", ",", "(", "key", ",", "value", ")", "|", "result", "<<", "[", "key", ",", "value", "]", "if", "value", "!=", "@credentials", "[", "key", "]", "result", "end", "diff", "=", "@credentials", ".", "inject", "(", "diff", ")", "do", "|", "result", ",", "(", "key", ",", "_", ")", "|", "result", "<<", "[", "key", ",", "nil", "]", "unless", "new_credentials", ".", "include?", "(", "key", ")", "result", "end", "diff", ".", "each", "{", "|", "entry", "|", "set_credential", "(", "entry", "[", "0", "]", ",", "entry", "[", "1", "]", ")", "}", "return", "nil", "end"], "docstring": "Set the credentials hash to a new one. Calculate difference, and call the\n AuthHandler callback appropriately.", "docstring_tokens": ["Set", "the", "credentials", "hash", "to", "a", "new", "one", ".", "Calculate", "difference", "and", "call", "the", "AuthHandler", "callback", "appropriately", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/credential_handler.rb#L44-L61", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/credential_handler.rb", "func_name": "AdsCommon.CredentialHandler.generate_user_agent", "original_string": "def generate_user_agent(extra_ids = [], agent_app = nil)\n agent_app ||= File.basename($0)\n agent_data = extra_ids\n agent_data << 'Common-Ruby/%s' % AdsCommon::ApiConfig::CLIENT_LIB_VERSION\n agent_data << 'GoogleAdsSavon/%s' % GoogleAdsSavon::VERSION\n ruby_engine = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby'\n agent_data << [ruby_engine, RUBY_VERSION].join('/')\n agent_data << 'HTTPI/%s' % HTTPI::VERSION\n agent_data << HTTPI::Adapter.use.to_s\n agent_data += get_extra_user_agents()\n return '%s (%s)' % [agent_app, agent_data.join(', ')]\n end", "language": "ruby", "code": "def generate_user_agent(extra_ids = [], agent_app = nil)\n agent_app ||= File.basename($0)\n agent_data = extra_ids\n agent_data << 'Common-Ruby/%s' % AdsCommon::ApiConfig::CLIENT_LIB_VERSION\n agent_data << 'GoogleAdsSavon/%s' % GoogleAdsSavon::VERSION\n ruby_engine = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby'\n agent_data << [ruby_engine, RUBY_VERSION].join('/')\n agent_data << 'HTTPI/%s' % HTTPI::VERSION\n agent_data << HTTPI::Adapter.use.to_s\n agent_data += get_extra_user_agents()\n return '%s (%s)' % [agent_app, agent_data.join(', ')]\n end", "code_tokens": ["def", "generate_user_agent", "(", "extra_ids", "=", "[", "]", ",", "agent_app", "=", "nil", ")", "agent_app", "||=", "File", ".", "basename", "(", "$0", ")", "agent_data", "=", "extra_ids", "agent_data", "<<", "'Common-Ruby/%s'", "%", "AdsCommon", "::", "ApiConfig", "::", "CLIENT_LIB_VERSION", "agent_data", "<<", "'GoogleAdsSavon/%s'", "%", "GoogleAdsSavon", "::", "VERSION", "ruby_engine", "=", "defined?", "(", "RUBY_ENGINE", ")", "?", "RUBY_ENGINE", ":", "'ruby'", "agent_data", "<<", "[", "ruby_engine", ",", "RUBY_VERSION", "]", ".", "join", "(", "'/'", ")", "agent_data", "<<", "'HTTPI/%s'", "%", "HTTPI", "::", "VERSION", "agent_data", "<<", "HTTPI", "::", "Adapter", ".", "use", ".", "to_s", "agent_data", "+=", "get_extra_user_agents", "(", ")", "return", "'%s (%s)'", "%", "[", "agent_app", ",", "agent_data", ".", "join", "(", "', '", ")", "]", "end"], "docstring": "Generates string for UserAgent to put into headers.", "docstring_tokens": ["Generates", "string", "for", "UserAgent", "to", "put", "into", "headers", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/credential_handler.rb#L83-L94", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/credential_handler.rb", "func_name": "AdsCommon.CredentialHandler.get_extra_user_agents", "original_string": "def get_extra_user_agents()\n @extra_user_agents_lock.synchronize do\n user_agents = @extra_user_agents.collect do |k, v|\n v.nil? ? k : '%s/%s' % [k, v]\n end\n @extra_user_agents.clear\n return user_agents\n end\n end", "language": "ruby", "code": "def get_extra_user_agents()\n @extra_user_agents_lock.synchronize do\n user_agents = @extra_user_agents.collect do |k, v|\n v.nil? ? k : '%s/%s' % [k, v]\n end\n @extra_user_agents.clear\n return user_agents\n end\n end", "code_tokens": ["def", "get_extra_user_agents", "(", ")", "@extra_user_agents_lock", ".", "synchronize", "do", "user_agents", "=", "@extra_user_agents", ".", "collect", "do", "|", "k", ",", "v", "|", "v", ".", "nil?", "?", "k", ":", "'%s/%s'", "%", "[", "k", ",", "v", "]", "end", "@extra_user_agents", ".", "clear", "return", "user_agents", "end", "end"], "docstring": "Generates an array of extra user agents to include in the user agent\n string.", "docstring_tokens": ["Generates", "an", "array", "of", "extra", "user", "agents", "to", "include", "in", "the", "user", "agent", "string", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/credential_handler.rb#L116-L124", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.extract_header_data", "original_string": "def extract_header_data(response)\n header_type = get_full_type_signature(:SoapResponseHeader)\n headers = response.header[:response_header].dup\n process_attributes(headers, false)\n headers = normalize_fields(headers, header_type[:fields])\n return headers\n end", "language": "ruby", "code": "def extract_header_data(response)\n header_type = get_full_type_signature(:SoapResponseHeader)\n headers = response.header[:response_header].dup\n process_attributes(headers, false)\n headers = normalize_fields(headers, header_type[:fields])\n return headers\n end", "code_tokens": ["def", "extract_header_data", "(", "response", ")", "header_type", "=", "get_full_type_signature", "(", ":SoapResponseHeader", ")", "headers", "=", "response", ".", "header", "[", ":response_header", "]", ".", "dup", "process_attributes", "(", "headers", ",", "false", ")", "headers", "=", "normalize_fields", "(", "headers", ",", "header_type", "[", ":fields", "]", ")", "return", "headers", "end"], "docstring": "Extracts misc data from response header.", "docstring_tokens": ["Extracts", "misc", "data", "from", "response", "header", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L44-L50", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.extract_exception_data", "original_string": "def extract_exception_data(soap_fault, exception_name)\n exception_type = get_full_type_signature(exception_name)\n process_attributes(soap_fault, false)\n soap_fault = normalize_fields(soap_fault, exception_type[:fields])\n return soap_fault\n end", "language": "ruby", "code": "def extract_exception_data(soap_fault, exception_name)\n exception_type = get_full_type_signature(exception_name)\n process_attributes(soap_fault, false)\n soap_fault = normalize_fields(soap_fault, exception_type[:fields])\n return soap_fault\n end", "code_tokens": ["def", "extract_exception_data", "(", "soap_fault", ",", "exception_name", ")", "exception_type", "=", "get_full_type_signature", "(", "exception_name", ")", "process_attributes", "(", "soap_fault", ",", "false", ")", "soap_fault", "=", "normalize_fields", "(", "soap_fault", ",", "exception_type", "[", ":fields", "]", ")", "return", "soap_fault", "end"], "docstring": "Extracts misc data from SOAP fault.", "docstring_tokens": ["Extracts", "misc", "data", "from", "SOAP", "fault", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L53-L58", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.normalize_fields", "original_string": "def normalize_fields(data, fields)\n fields.each do |field|\n field_name = field[:name]\n if data.include?(field_name)\n field_data = data[field_name]\n field_data = normalize_output_field(field_data, field)\n field_data = check_array_collapse(field_data, field)\n data[field_name] = field_data unless field_data.nil?\n end\n end\n return data\n end", "language": "ruby", "code": "def normalize_fields(data, fields)\n fields.each do |field|\n field_name = field[:name]\n if data.include?(field_name)\n field_data = data[field_name]\n field_data = normalize_output_field(field_data, field)\n field_data = check_array_collapse(field_data, field)\n data[field_name] = field_data unless field_data.nil?\n end\n end\n return data\n end", "code_tokens": ["def", "normalize_fields", "(", "data", ",", "fields", ")", "fields", ".", "each", "do", "|", "field", "|", "field_name", "=", "field", "[", ":name", "]", "if", "data", ".", "include?", "(", "field_name", ")", "field_data", "=", "data", "[", "field_name", "]", "field_data", "=", "normalize_output_field", "(", "field_data", ",", "field", ")", "field_data", "=", "check_array_collapse", "(", "field_data", ",", "field", ")", "data", "[", "field_name", "]", "=", "field_data", "unless", "field_data", ".", "nil?", "end", "end", "return", "data", "end"], "docstring": "Normalizes all fields for the given data based on the fields list\n provided.", "docstring_tokens": ["Normalizes", "all", "fields", "for", "the", "given", "data", "based", "on", "the", "fields", "list", "provided", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L70-L81", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.normalize_output_field", "original_string": "def normalize_output_field(field_data, field_def)\n return case field_data\n when Array\n normalize_array_field(field_data, field_def)\n when Hash\n normalize_hash_field(field_data, field_def)\n else\n normalize_item(field_data, field_def)\n end\n end", "language": "ruby", "code": "def normalize_output_field(field_data, field_def)\n return case field_data\n when Array\n normalize_array_field(field_data, field_def)\n when Hash\n normalize_hash_field(field_data, field_def)\n else\n normalize_item(field_data, field_def)\n end\n end", "code_tokens": ["def", "normalize_output_field", "(", "field_data", ",", "field_def", ")", "return", "case", "field_data", "when", "Array", "normalize_array_field", "(", "field_data", ",", "field_def", ")", "when", "Hash", "normalize_hash_field", "(", "field_data", ",", "field_def", ")", "else", "normalize_item", "(", "field_data", ",", "field_def", ")", "end", "end"], "docstring": "Normalizes one field of a given data recursively.\n\n Args:\n - field_data: XML data to normalize\n - field_def: field type definition for the data", "docstring_tokens": ["Normalizes", "one", "field", "of", "a", "given", "data", "recursively", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L89-L98", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.normalize_array_field", "original_string": "def normalize_array_field(data, field_def)\n result = data\n # Convert a specific structure to a handy hash if detected.\n if check_key_value_struct(result)\n result = convert_key_value_to_hash(result).inject({}) do |s, (k,v)|\n s[k] = normalize_output_field(v, field_def)\n s\n end\n else\n result = data.map {|item| normalize_output_field(item, field_def)}\n end\n return result\n end", "language": "ruby", "code": "def normalize_array_field(data, field_def)\n result = data\n # Convert a specific structure to a handy hash if detected.\n if check_key_value_struct(result)\n result = convert_key_value_to_hash(result).inject({}) do |s, (k,v)|\n s[k] = normalize_output_field(v, field_def)\n s\n end\n else\n result = data.map {|item| normalize_output_field(item, field_def)}\n end\n return result\n end", "code_tokens": ["def", "normalize_array_field", "(", "data", ",", "field_def", ")", "result", "=", "data", "if", "check_key_value_struct", "(", "result", ")", "result", "=", "convert_key_value_to_hash", "(", "result", ")", ".", "inject", "(", "{", "}", ")", "do", "|", "s", ",", "(", "k", ",", "v", ")", "|", "s", "[", "k", "]", "=", "normalize_output_field", "(", "v", ",", "field_def", ")", "s", "end", "else", "result", "=", "data", ".", "map", "{", "|", "item", "|", "normalize_output_field", "(", "item", ",", "field_def", ")", "}", "end", "return", "result", "end"], "docstring": "Normalizes every item of an Array.", "docstring_tokens": ["Normalizes", "every", "item", "of", "an", "Array", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L101-L113", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.normalize_hash_field", "original_string": "def normalize_hash_field(field, field_def)\n process_attributes(field, true)\n field_type = field_def[:type]\n field_def = get_full_type_signature(field_type)\n\n # First checking for xsi:type provided.\n xsi_type_override = determine_xsi_type_override(field, field_def)\n unless xsi_type_override.nil?\n field_def = get_full_type_signature(xsi_type_override)\n return (field_def.nil?) ? field :\n normalize_fields(field, field_def[:fields])\n end\n\n result = field\n\n # Now checking for choice options from wsdl.\n choice_type_override = determine_choice_type_override(field, field_def)\n unless choice_type_override.nil?\n # For overrides we need to process sub-field and than return it\n # in the original structure.\n field_key = field.keys.first\n field_data = field[field_key]\n field_def = get_full_type_signature(choice_type_override)\n if !field_def.nil? and field_data.kind_of?(Hash)\n field_data = normalize_fields(field_data, field_def[:fields])\n end\n result = {field_key => field_data}\n else\n # Otherwise using the best we have.\n unless field_def.nil?\n result = normalize_fields(field, field_def[:fields])\n end\n end\n\n # Convert a single key-value hash to a proper hash if detected.\n if check_key_value_struct(result)\n result = convert_key_value_to_hash(result)\n end\n\n return result\n end", "language": "ruby", "code": "def normalize_hash_field(field, field_def)\n process_attributes(field, true)\n field_type = field_def[:type]\n field_def = get_full_type_signature(field_type)\n\n # First checking for xsi:type provided.\n xsi_type_override = determine_xsi_type_override(field, field_def)\n unless xsi_type_override.nil?\n field_def = get_full_type_signature(xsi_type_override)\n return (field_def.nil?) ? field :\n normalize_fields(field, field_def[:fields])\n end\n\n result = field\n\n # Now checking for choice options from wsdl.\n choice_type_override = determine_choice_type_override(field, field_def)\n unless choice_type_override.nil?\n # For overrides we need to process sub-field and than return it\n # in the original structure.\n field_key = field.keys.first\n field_data = field[field_key]\n field_def = get_full_type_signature(choice_type_override)\n if !field_def.nil? and field_data.kind_of?(Hash)\n field_data = normalize_fields(field_data, field_def[:fields])\n end\n result = {field_key => field_data}\n else\n # Otherwise using the best we have.\n unless field_def.nil?\n result = normalize_fields(field, field_def[:fields])\n end\n end\n\n # Convert a single key-value hash to a proper hash if detected.\n if check_key_value_struct(result)\n result = convert_key_value_to_hash(result)\n end\n\n return result\n end", "code_tokens": ["def", "normalize_hash_field", "(", "field", ",", "field_def", ")", "process_attributes", "(", "field", ",", "true", ")", "field_type", "=", "field_def", "[", ":type", "]", "field_def", "=", "get_full_type_signature", "(", "field_type", ")", "xsi_type_override", "=", "determine_xsi_type_override", "(", "field", ",", "field_def", ")", "unless", "xsi_type_override", ".", "nil?", "field_def", "=", "get_full_type_signature", "(", "xsi_type_override", ")", "return", "(", "field_def", ".", "nil?", ")", "?", "field", ":", "normalize_fields", "(", "field", ",", "field_def", "[", ":fields", "]", ")", "end", "result", "=", "field", "choice_type_override", "=", "determine_choice_type_override", "(", "field", ",", "field_def", ")", "unless", "choice_type_override", ".", "nil?", "field_key", "=", "field", ".", "keys", ".", "first", "field_data", "=", "field", "[", "field_key", "]", "field_def", "=", "get_full_type_signature", "(", "choice_type_override", ")", "if", "!", "field_def", ".", "nil?", "and", "field_data", ".", "kind_of?", "(", "Hash", ")", "field_data", "=", "normalize_fields", "(", "field_data", ",", "field_def", "[", ":fields", "]", ")", "end", "result", "=", "{", "field_key", "=>", "field_data", "}", "else", "unless", "field_def", ".", "nil?", "result", "=", "normalize_fields", "(", "field", ",", "field_def", "[", ":fields", "]", ")", "end", "end", "if", "check_key_value_struct", "(", "result", ")", "result", "=", "convert_key_value_to_hash", "(", "result", ")", "end", "return", "result", "end"], "docstring": "Normalizes every item of a Hash.", "docstring_tokens": ["Normalizes", "every", "item", "of", "a", "Hash", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L116-L156", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.determine_choice_type_override", "original_string": "def determine_choice_type_override(field_data, field_def)\n result = nil\n if field_data.kind_of?(Hash) and field_def.include?(:choices)\n result = determine_choice(field_data, field_def[:choices])\n end\n return result\n end", "language": "ruby", "code": "def determine_choice_type_override(field_data, field_def)\n result = nil\n if field_data.kind_of?(Hash) and field_def.include?(:choices)\n result = determine_choice(field_data, field_def[:choices])\n end\n return result\n end", "code_tokens": ["def", "determine_choice_type_override", "(", "field_data", ",", "field_def", ")", "result", "=", "nil", "if", "field_data", ".", "kind_of?", "(", "Hash", ")", "and", "field_def", ".", "include?", "(", ":choices", ")", "result", "=", "determine_choice", "(", "field_data", ",", "field_def", "[", ":choices", "]", ")", "end", "return", "result", "end"], "docstring": "Determines a choice type override for for the field. Returns nil if no\n override found.", "docstring_tokens": ["Determines", "a", "choice", "type", "override", "for", "for", "the", "field", ".", "Returns", "nil", "if", "no", "override", "found", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L204-L210", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.determine_choice", "original_string": "def determine_choice(field_data, field_choices)\n result = nil\n key_name = field_data.keys.first\n unless key_name.nil?\n choice = find_named_entry(field_choices, key_name)\n result = choice[:type] unless choice.nil?\n end\n return result\n end", "language": "ruby", "code": "def determine_choice(field_data, field_choices)\n result = nil\n key_name = field_data.keys.first\n unless key_name.nil?\n choice = find_named_entry(field_choices, key_name)\n result = choice[:type] unless choice.nil?\n end\n return result\n end", "code_tokens": ["def", "determine_choice", "(", "field_data", ",", "field_choices", ")", "result", "=", "nil", "key_name", "=", "field_data", ".", "keys", ".", "first", "unless", "key_name", ".", "nil?", "choice", "=", "find_named_entry", "(", "field_choices", ",", "key_name", ")", "result", "=", "choice", "[", ":type", "]", "unless", "choice", ".", "nil?", "end", "return", "result", "end"], "docstring": "Finds the choice option matching data provided.", "docstring_tokens": ["Finds", "the", "choice", "option", "matching", "data", "provided", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L213-L221", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.normalize_item", "original_string": "def normalize_item(item, field_def)\n return case field_def[:type]\n when 'long', 'int' then Integer(item)\n when 'double', 'float' then Float(item)\n when 'boolean' then item.kind_of?(String) ?\n item.casecmp('true') == 0 : item\n else item\n end\n end", "language": "ruby", "code": "def normalize_item(item, field_def)\n return case field_def[:type]\n when 'long', 'int' then Integer(item)\n when 'double', 'float' then Float(item)\n when 'boolean' then item.kind_of?(String) ?\n item.casecmp('true') == 0 : item\n else item\n end\n end", "code_tokens": ["def", "normalize_item", "(", "item", ",", "field_def", ")", "return", "case", "field_def", "[", ":type", "]", "when", "'long'", ",", "'int'", "then", "Integer", "(", "item", ")", "when", "'double'", ",", "'float'", "then", "Float", "(", "item", ")", "when", "'boolean'", "then", "item", ".", "kind_of?", "(", "String", ")", "?", "item", ".", "casecmp", "(", "'true'", ")", "==", "0", ":", "item", "else", "item", "end", "end"], "docstring": "Converts one leaf item to a built-in type.", "docstring_tokens": ["Converts", "one", "leaf", "item", "to", "a", "built", "-", "in", "type", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L230-L238", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.check_array_collapse", "original_string": "def check_array_collapse(data, field_def)\n result = data\n if !field_def[:min_occurs].nil? &&\n (field_def[:max_occurs] == :unbounded ||\n (!field_def[:max_occurs].nil? && field_def[:max_occurs] > 1)) &&\n !(field_def[:type] =~ /MapEntry$/)\n result = arrayize(result)\n end\n return result\n end", "language": "ruby", "code": "def check_array_collapse(data, field_def)\n result = data\n if !field_def[:min_occurs].nil? &&\n (field_def[:max_occurs] == :unbounded ||\n (!field_def[:max_occurs].nil? && field_def[:max_occurs] > 1)) &&\n !(field_def[:type] =~ /MapEntry$/)\n result = arrayize(result)\n end\n return result\n end", "code_tokens": ["def", "check_array_collapse", "(", "data", ",", "field_def", ")", "result", "=", "data", "if", "!", "field_def", "[", ":min_occurs", "]", ".", "nil?", "&&", "(", "field_def", "[", ":max_occurs", "]", "==", ":unbounded", "||", "(", "!", "field_def", "[", ":max_occurs", "]", ".", "nil?", "&&", "field_def", "[", ":max_occurs", "]", ">", "1", ")", ")", "&&", "!", "(", "field_def", "[", ":type", "]", "=~", "/", "/", ")", "result", "=", "arrayize", "(", "result", ")", "end", "return", "result", "end"], "docstring": "Checks if the field signature allows an array and forces array structure\n even for a signle item.", "docstring_tokens": ["Checks", "if", "the", "field", "signature", "allows", "an", "array", "and", "forces", "array", "structure", "even", "for", "a", "signle", "item", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L242-L251", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/results_extractor.rb", "func_name": "AdsCommon.ResultsExtractor.process_attributes", "original_string": "def process_attributes(data, keep_xsi_type = false)\n if keep_xsi_type\n xsi_type = data.delete(:\"@xsi:type\")\n data[:xsi_type] = xsi_type if xsi_type\n end\n data.reject! {|key, value| key.to_s.start_with?('@')}\n end", "language": "ruby", "code": "def process_attributes(data, keep_xsi_type = false)\n if keep_xsi_type\n xsi_type = data.delete(:\"@xsi:type\")\n data[:xsi_type] = xsi_type if xsi_type\n end\n data.reject! {|key, value| key.to_s.start_with?('@')}\n end", "code_tokens": ["def", "process_attributes", "(", "data", ",", "keep_xsi_type", "=", "false", ")", "if", "keep_xsi_type", "xsi_type", "=", "data", ".", "delete", "(", ":\"", "\"", ")", "data", "[", ":xsi_type", "]", "=", "xsi_type", "if", "xsi_type", "end", "data", ".", "reject!", "{", "|", "key", ",", "value", "|", "key", ".", "to_s", ".", "start_with?", "(", "'@'", ")", "}", "end"], "docstring": "Handles attributes received from Savon.", "docstring_tokens": ["Handles", "attributes", "received", "from", "Savon", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/results_extractor.rb#L282-L288", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.service", "original_string": "def service(name, version = nil)\n name = name.to_sym\n version = (version.nil?) ? api_config.default_version : version.to_sym\n\n # Check if the combination is available.\n validate_service_request(version, name)\n\n # Try to re-use the service for this version if it was requested before.\n wrapper = if @wrappers.include?(version) && @wrappers[version][name]\n @wrappers[version][name]\n else\n @wrappers[version] ||= {}\n @wrappers[version][name] = prepare_wrapper(version, name)\n end\n return wrapper\n end", "language": "ruby", "code": "def service(name, version = nil)\n name = name.to_sym\n version = (version.nil?) ? api_config.default_version : version.to_sym\n\n # Check if the combination is available.\n validate_service_request(version, name)\n\n # Try to re-use the service for this version if it was requested before.\n wrapper = if @wrappers.include?(version) && @wrappers[version][name]\n @wrappers[version][name]\n else\n @wrappers[version] ||= {}\n @wrappers[version][name] = prepare_wrapper(version, name)\n end\n return wrapper\n end", "code_tokens": ["def", "service", "(", "name", ",", "version", "=", "nil", ")", "name", "=", "name", ".", "to_sym", "version", "=", "(", "version", ".", "nil?", ")", "?", "api_config", ".", "default_version", ":", "version", ".", "to_sym", "validate_service_request", "(", "version", ",", "name", ")", "wrapper", "=", "if", "@wrappers", ".", "include?", "(", "version", ")", "&&", "@wrappers", "[", "version", "]", "[", "name", "]", "@wrappers", "[", "version", "]", "[", "name", "]", "else", "@wrappers", "[", "version", "]", "||=", "{", "}", "@wrappers", "[", "version", "]", "[", "name", "]", "=", "prepare_wrapper", "(", "version", ",", "name", ")", "end", "return", "wrapper", "end"], "docstring": "Obtain an API service, given a version and its name.\n\n Args:\n - name: name for the intended service\n - version: intended API version.\n\n Returns:\n - the service wrapper for the intended service.", "docstring_tokens": ["Obtain", "an", "API", "service", "given", "a", "version", "and", "its", "name", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L70-L85", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.authorize", "original_string": "def authorize(parameters = {}, &block)\n parameters.each_pair do |key, value|\n @credential_handler.set_credential(key, value)\n end\n\n auth_handler = get_auth_handler()\n token = auth_handler.get_token()\n\n # If token is invalid ask for a new one.\n if token.nil?\n begin\n credentials = @credential_handler.credentials\n token = auth_handler.get_token(credentials)\n rescue AdsCommon::Errors::OAuth2VerificationRequired => e\n verification_code = (block_given?) ? yield(e.oauth_url) : nil\n # Retry with verification code if one provided.\n if verification_code\n @credential_handler.set_credential(\n :oauth2_verification_code, verification_code)\n retry\n else\n raise e\n end\n end\n end\n return token\n end", "language": "ruby", "code": "def authorize(parameters = {}, &block)\n parameters.each_pair do |key, value|\n @credential_handler.set_credential(key, value)\n end\n\n auth_handler = get_auth_handler()\n token = auth_handler.get_token()\n\n # If token is invalid ask for a new one.\n if token.nil?\n begin\n credentials = @credential_handler.credentials\n token = auth_handler.get_token(credentials)\n rescue AdsCommon::Errors::OAuth2VerificationRequired => e\n verification_code = (block_given?) ? yield(e.oauth_url) : nil\n # Retry with verification code if one provided.\n if verification_code\n @credential_handler.set_credential(\n :oauth2_verification_code, verification_code)\n retry\n else\n raise e\n end\n end\n end\n return token\n end", "code_tokens": ["def", "authorize", "(", "parameters", "=", "{", "}", ",", "&", "block", ")", "parameters", ".", "each_pair", "do", "|", "key", ",", "value", "|", "@credential_handler", ".", "set_credential", "(", "key", ",", "value", ")", "end", "auth_handler", "=", "get_auth_handler", "(", ")", "token", "=", "auth_handler", ".", "get_token", "(", ")", "if", "token", ".", "nil?", "begin", "credentials", "=", "@credential_handler", ".", "credentials", "token", "=", "auth_handler", ".", "get_token", "(", "credentials", ")", "rescue", "AdsCommon", "::", "Errors", "::", "OAuth2VerificationRequired", "=>", "e", "verification_code", "=", "(", "block_given?", ")", "?", "yield", "(", "e", ".", "oauth_url", ")", ":", "nil", "if", "verification_code", "@credential_handler", ".", "set_credential", "(", ":oauth2_verification_code", ",", "verification_code", ")", "retry", "else", "raise", "e", "end", "end", "end", "return", "token", "end"], "docstring": "Authorize with specified authentication method.\n\n Args:\n - parameters - hash of credentials to add to configuration\n - block - code block to handle auth login url\n\n Returns:\n - Auth token for the method\n\n Throws:\n - AdsCommon::Errors::AuthError or derived if authetication error has\n occured", "docstring_tokens": ["Authorize", "with", "specified", "authentication", "method", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L100-L126", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.save_oauth2_token", "original_string": "def save_oauth2_token(token)\n raise AdsCommon::Errors::Error, \"Can't save nil token\" if token.nil?\n AdsCommon::Utils.save_oauth2_token(\n File.join(ENV['HOME'], api_config.default_config_filename), token)\n end", "language": "ruby", "code": "def save_oauth2_token(token)\n raise AdsCommon::Errors::Error, \"Can't save nil token\" if token.nil?\n AdsCommon::Utils.save_oauth2_token(\n File.join(ENV['HOME'], api_config.default_config_filename), token)\n end", "code_tokens": ["def", "save_oauth2_token", "(", "token", ")", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Can't save nil token\"", "if", "token", ".", "nil?", "AdsCommon", "::", "Utils", ".", "save_oauth2_token", "(", "File", ".", "join", "(", "ENV", "[", "'HOME'", "]", ",", "api_config", ".", "default_config_filename", ")", ",", "token", ")", "end"], "docstring": "Updates default configuration file to include OAuth2 token information.", "docstring_tokens": ["Updates", "default", "configuration", "file", "to", "include", "OAuth2", "token", "information", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L143-L147", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.validate_service_request", "original_string": "def validate_service_request(version, service)\n # Check if the current config supports the requested version.\n unless api_config.has_version(version)\n raise AdsCommon::Errors::Error,\n \"Version '%s' not recognized\" % version.to_s\n end\n\n # Check if the specified version has the requested service.\n unless api_config.version_has_service(version, service)\n raise AdsCommon::Errors::Error,\n \"Version '%s' does not contain service '%s'\" %\n [version.to_s, service.to_s]\n end\n end", "language": "ruby", "code": "def validate_service_request(version, service)\n # Check if the current config supports the requested version.\n unless api_config.has_version(version)\n raise AdsCommon::Errors::Error,\n \"Version '%s' not recognized\" % version.to_s\n end\n\n # Check if the specified version has the requested service.\n unless api_config.version_has_service(version, service)\n raise AdsCommon::Errors::Error,\n \"Version '%s' does not contain service '%s'\" %\n [version.to_s, service.to_s]\n end\n end", "code_tokens": ["def", "validate_service_request", "(", "version", ",", "service", ")", "unless", "api_config", ".", "has_version", "(", "version", ")", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Version '%s' not recognized\"", "%", "version", ".", "to_s", "end", "unless", "api_config", ".", "version_has_service", "(", "version", ",", "service", ")", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Version '%s' does not contain service '%s'\"", "%", "[", "version", ".", "to_s", ",", "service", ".", "to_s", "]", "end", "end"], "docstring": "Auxiliary method to test parameters correctness for the service request.", "docstring_tokens": ["Auxiliary", "method", "to", "test", "parameters", "correctness", "for", "the", "service", "request", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L152-L165", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.create_auth_handler", "original_string": "def create_auth_handler()\n auth_method = @config.read('authentication.method', :OAUTH2)\n return case auth_method\n when :OAUTH\n raise AdsCommon::Errors::Error,\n 'OAuth authorization method is deprecated, use OAuth2 instead.'\n when :OAUTH2\n AdsCommon::Auth::OAuth2Handler.new(\n @config,\n api_config.config(:oauth_scope)\n )\n when :OAUTH2_SERVICE_ACCOUNT\n AdsCommon::Auth::OAuth2ServiceAccountHandler.new(\n @config,\n api_config.config(:oauth_scope)\n )\n else\n raise AdsCommon::Errors::Error,\n \"Unknown authentication method '%s'\" % auth_method\n end\n end", "language": "ruby", "code": "def create_auth_handler()\n auth_method = @config.read('authentication.method', :OAUTH2)\n return case auth_method\n when :OAUTH\n raise AdsCommon::Errors::Error,\n 'OAuth authorization method is deprecated, use OAuth2 instead.'\n when :OAUTH2\n AdsCommon::Auth::OAuth2Handler.new(\n @config,\n api_config.config(:oauth_scope)\n )\n when :OAUTH2_SERVICE_ACCOUNT\n AdsCommon::Auth::OAuth2ServiceAccountHandler.new(\n @config,\n api_config.config(:oauth_scope)\n )\n else\n raise AdsCommon::Errors::Error,\n \"Unknown authentication method '%s'\" % auth_method\n end\n end", "code_tokens": ["def", "create_auth_handler", "(", ")", "auth_method", "=", "@config", ".", "read", "(", "'authentication.method'", ",", ":OAUTH2", ")", "return", "case", "auth_method", "when", ":OAUTH", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "'OAuth authorization method is deprecated, use OAuth2 instead.'", "when", ":OAUTH2", "AdsCommon", "::", "Auth", "::", "OAuth2Handler", ".", "new", "(", "@config", ",", "api_config", ".", "config", "(", ":oauth_scope", ")", ")", "when", ":OAUTH2_SERVICE_ACCOUNT", "AdsCommon", "::", "Auth", "::", "OAuth2ServiceAccountHandler", ".", "new", "(", "@config", ",", "api_config", ".", "config", "(", ":oauth_scope", ")", ")", "else", "raise", "AdsCommon", "::", "Errors", "::", "Error", ",", "\"Unknown authentication method '%s'\"", "%", "auth_method", "end", "end"], "docstring": "Auxiliary method to create an authentication handler.\n\n Returns:\n - auth handler", "docstring_tokens": ["Auxiliary", "method", "to", "create", "an", "authentication", "handler", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L190-L210", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.prepare_wrapper", "original_string": "def prepare_wrapper(version, service)\n api_config.do_require(version, service)\n endpoint = api_config.endpoint(version, service)\n interface_class_name = api_config.interface_name(version, service)\n\n wrapper = class_for_path(interface_class_name).new(@config, endpoint)\n auth_handler = get_auth_handler()\n header_ns = api_config.config(:header_ns) + version.to_s\n soap_handler = soap_header_handler(auth_handler, version, header_ns,\n wrapper.namespace)\n wrapper.header_handler = soap_handler\n\n return wrapper\n end", "language": "ruby", "code": "def prepare_wrapper(version, service)\n api_config.do_require(version, service)\n endpoint = api_config.endpoint(version, service)\n interface_class_name = api_config.interface_name(version, service)\n\n wrapper = class_for_path(interface_class_name).new(@config, endpoint)\n auth_handler = get_auth_handler()\n header_ns = api_config.config(:header_ns) + version.to_s\n soap_handler = soap_header_handler(auth_handler, version, header_ns,\n wrapper.namespace)\n wrapper.header_handler = soap_handler\n\n return wrapper\n end", "code_tokens": ["def", "prepare_wrapper", "(", "version", ",", "service", ")", "api_config", ".", "do_require", "(", "version", ",", "service", ")", "endpoint", "=", "api_config", ".", "endpoint", "(", "version", ",", "service", ")", "interface_class_name", "=", "api_config", ".", "interface_name", "(", "version", ",", "service", ")", "wrapper", "=", "class_for_path", "(", "interface_class_name", ")", ".", "new", "(", "@config", ",", "endpoint", ")", "auth_handler", "=", "get_auth_handler", "(", ")", "header_ns", "=", "api_config", ".", "config", "(", ":header_ns", ")", "+", "version", ".", "to_s", "soap_handler", "=", "soap_header_handler", "(", "auth_handler", ",", "version", ",", "header_ns", ",", "wrapper", ".", "namespace", ")", "wrapper", ".", "header_handler", "=", "soap_handler", "return", "wrapper", "end"], "docstring": "Handle loading of a single service.\n Creates the wrapper, sets up handlers and creates an instance of it.\n\n Args:\n - version: intended API version, must be a symbol\n - service: name for the intended service\n\n Returns:\n - a simplified wrapper generated for the service", "docstring_tokens": ["Handle", "loading", "of", "a", "single", "service", ".", "Creates", "the", "wrapper", "sets", "up", "handlers", "and", "creates", "an", "instance", "of", "it", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L222-L235", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.create_default_logger", "original_string": "def create_default_logger()\n logger = Logger.new(STDOUT)\n logger.level = get_log_level_for_string(\n @config.read('library.log_level', 'INFO'))\n return logger\n end", "language": "ruby", "code": "def create_default_logger()\n logger = Logger.new(STDOUT)\n logger.level = get_log_level_for_string(\n @config.read('library.log_level', 'INFO'))\n return logger\n end", "code_tokens": ["def", "create_default_logger", "(", ")", "logger", "=", "Logger", ".", "new", "(", "STDOUT", ")", "logger", ".", "level", "=", "get_log_level_for_string", "(", "@config", ".", "read", "(", "'library.log_level'", ",", "'INFO'", ")", ")", "return", "logger", "end"], "docstring": "Auxiliary method to create a default Logger.", "docstring_tokens": ["Auxiliary", "method", "to", "create", "a", "default", "Logger", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L238-L243", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.load_config", "original_string": "def load_config(provided_config = nil)\n @config = (provided_config.nil?) ?\n AdsCommon::Config.new(\n File.join(ENV['HOME'], api_config.default_config_filename)) :\n AdsCommon::Config.new(provided_config)\n init_config()\n end", "language": "ruby", "code": "def load_config(provided_config = nil)\n @config = (provided_config.nil?) ?\n AdsCommon::Config.new(\n File.join(ENV['HOME'], api_config.default_config_filename)) :\n AdsCommon::Config.new(provided_config)\n init_config()\n end", "code_tokens": ["def", "load_config", "(", "provided_config", "=", "nil", ")", "@config", "=", "(", "provided_config", ".", "nil?", ")", "?", "AdsCommon", "::", "Config", ".", "new", "(", "File", ".", "join", "(", "ENV", "[", "'HOME'", "]", ",", "api_config", ".", "default_config_filename", ")", ")", ":", "AdsCommon", "::", "Config", ".", "new", "(", "provided_config", ")", "init_config", "(", ")", "end"], "docstring": "Helper method to load the default configuration file or a given config.", "docstring_tokens": ["Helper", "method", "to", "load", "the", "default", "configuration", "file", "or", "a", "given", "config", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L246-L252", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.init_config", "original_string": "def init_config()\n # Set up logger.\n provided_logger = @config.read('library.logger')\n self.logger = (provided_logger.nil?) ?\n create_default_logger() : provided_logger\n\n # Set up default HTTPI adapter.\n provided_adapter = @config.read('connection.adapter')\n @config.set('connection.adapter', :httpclient) if provided_adapter.nil?\n\n # Make sure Auth param is a symbol.\n symbolize_config_value('authentication.method')\n end", "language": "ruby", "code": "def init_config()\n # Set up logger.\n provided_logger = @config.read('library.logger')\n self.logger = (provided_logger.nil?) ?\n create_default_logger() : provided_logger\n\n # Set up default HTTPI adapter.\n provided_adapter = @config.read('connection.adapter')\n @config.set('connection.adapter', :httpclient) if provided_adapter.nil?\n\n # Make sure Auth param is a symbol.\n symbolize_config_value('authentication.method')\n end", "code_tokens": ["def", "init_config", "(", ")", "provided_logger", "=", "@config", ".", "read", "(", "'library.logger'", ")", "self", ".", "logger", "=", "(", "provided_logger", ".", "nil?", ")", "?", "create_default_logger", "(", ")", ":", "provided_logger", "provided_adapter", "=", "@config", ".", "read", "(", "'connection.adapter'", ")", "@config", ".", "set", "(", "'connection.adapter'", ",", ":httpclient", ")", "if", "provided_adapter", ".", "nil?", "symbolize_config_value", "(", "'authentication.method'", ")", "end"], "docstring": "Initializes config with default values and converts existing if required.", "docstring_tokens": ["Initializes", "config", "with", "default", "values", "and", "converts", "existing", "if", "required", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L255-L267", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.symbolize_config_value", "original_string": "def symbolize_config_value(key)\n value_str = @config.read(key).to_s\n if !value_str.nil? and !value_str.empty?\n value = value_str.upcase.to_sym\n @config.set(key, value)\n end\n end", "language": "ruby", "code": "def symbolize_config_value(key)\n value_str = @config.read(key).to_s\n if !value_str.nil? and !value_str.empty?\n value = value_str.upcase.to_sym\n @config.set(key, value)\n end\n end", "code_tokens": ["def", "symbolize_config_value", "(", "key", ")", "value_str", "=", "@config", ".", "read", "(", "key", ")", ".", "to_s", "if", "!", "value_str", ".", "nil?", "and", "!", "value_str", ".", "empty?", "value", "=", "value_str", ".", "upcase", ".", "to_sym", "@config", ".", "set", "(", "key", ",", "value", ")", "end", "end"], "docstring": "Converts value of a config key to uppercase symbol.", "docstring_tokens": ["Converts", "value", "of", "a", "config", "key", "to", "uppercase", "symbol", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L270-L276", "partition": "valid"}
{"repo": "googleads/google-api-ads-ruby", "path": "ads_common/lib/ads_common/api.rb", "func_name": "AdsCommon.Api.class_for_path", "original_string": "def class_for_path(path)\n path.split('::').inject(Kernel) do |scope, const_name|\n scope.const_get(const_name)\n end\n end", "language": "ruby", "code": "def class_for_path(path)\n path.split('::').inject(Kernel) do |scope, const_name|\n scope.const_get(const_name)\n end\n end", "code_tokens": ["def", "class_for_path", "(", "path", ")", "path", ".", "split", "(", "'::'", ")", ".", "inject", "(", "Kernel", ")", "do", "|", "scope", ",", "const_name", "|", "scope", ".", "const_get", "(", "const_name", ")", "end", "end"], "docstring": "Converts complete class path into class object.", "docstring_tokens": ["Converts", "complete", "class", "path", "into", "class", "object", "."], "sha": "bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b", "url": "https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/api.rb#L284-L288", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/node/farm.rb", "func_name": "Zold.Farm.to_json", "original_string": "def to_json\n {\n threads: @threads.to_json,\n pipeline: @pipeline.size,\n best: best.map(&:to_mnemo).join(', '),\n farmer: @farmer.class.name\n }\n end", "language": "ruby", "code": "def to_json\n {\n threads: @threads.to_json,\n pipeline: @pipeline.size,\n best: best.map(&:to_mnemo).join(', '),\n farmer: @farmer.class.name\n }\n end", "code_tokens": ["def", "to_json", "{", "threads", ":", "@threads", ".", "to_json", ",", "pipeline", ":", "@pipeline", ".", "size", ",", "best", ":", "best", ".", "map", "(", "&", ":to_mnemo", ")", ".", "join", "(", "', '", ")", ",", "farmer", ":", "@farmer", ".", "class", ".", "name", "}", "end"], "docstring": "Renders the Farm into JSON to show for the end-user in front.rb.", "docstring_tokens": ["Renders", "the", "Farm", "into", "JSON", "to", "show", "for", "the", "end", "-", "user", "in", "front", ".", "rb", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/node/farm.rb#L91-L98", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/node/async_entrance.rb", "func_name": "Zold.AsyncEntrance.exists?", "original_string": "def exists?(id, body)\n DirItems.new(@dir).fetch.each do |f|\n next unless f.start_with?(\"#{id}-\")\n return true if safe_read(File.join(@dir, f)) == body\n end\n false\n end", "language": "ruby", "code": "def exists?(id, body)\n DirItems.new(@dir).fetch.each do |f|\n next unless f.start_with?(\"#{id}-\")\n return true if safe_read(File.join(@dir, f)) == body\n end\n false\n end", "code_tokens": ["def", "exists?", "(", "id", ",", "body", ")", "DirItems", ".", "new", "(", "@dir", ")", ".", "fetch", ".", "each", "do", "|", "f", "|", "next", "unless", "f", ".", "start_with?", "(", "\"#{id}-\"", ")", "return", "true", "if", "safe_read", "(", "File", ".", "join", "(", "@dir", ",", "f", ")", ")", "==", "body", "end", "false", "end"], "docstring": "Returns TRUE if a file for this wallet is already in the queue.", "docstring_tokens": ["Returns", "TRUE", "if", "a", "file", "for", "this", "wallet", "is", "already", "in", "the", "queue", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/node/async_entrance.rb#L116-L122", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/tax.rb", "func_name": "Zold.Tax.exists?", "original_string": "def exists?(details)\n !@wallet.txns.find { |t| t.details.start_with?(\"#{PREFIX} \") && t.details == details }.nil?\n end", "language": "ruby", "code": "def exists?(details)\n !@wallet.txns.find { |t| t.details.start_with?(\"#{PREFIX} \") && t.details == details }.nil?\n end", "code_tokens": ["def", "exists?", "(", "details", ")", "!", "@wallet", ".", "txns", ".", "find", "{", "|", "t", "|", "t", ".", "details", ".", "start_with?", "(", "\"#{PREFIX} \"", ")", "&&", "t", ".", "details", "==", "details", "}", ".", "nil?", "end"], "docstring": "Check whether this tax payment already exists in the wallet.", "docstring_tokens": ["Check", "whether", "this", "tax", "payment", "already", "exists", "in", "the", "wallet", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/tax.rb#L76-L78", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/node/spread_entrance.rb", "func_name": "Zold.SpreadEntrance.push", "original_string": "def push(id, body)\n mods = @entrance.push(id, body)\n return mods if @remotes.all.empty?\n mods.each do |m|\n next if @seen.include?(m)\n @mutex.synchronize { @seen << m }\n @modified.push(m)\n @log.debug(\"Spread-push scheduled for #{m}, queue size is #{@modified.size}\")\n end\n mods\n end", "language": "ruby", "code": "def push(id, body)\n mods = @entrance.push(id, body)\n return mods if @remotes.all.empty?\n mods.each do |m|\n next if @seen.include?(m)\n @mutex.synchronize { @seen << m }\n @modified.push(m)\n @log.debug(\"Spread-push scheduled for #{m}, queue size is #{@modified.size}\")\n end\n mods\n end", "code_tokens": ["def", "push", "(", "id", ",", "body", ")", "mods", "=", "@entrance", ".", "push", "(", "id", ",", "body", ")", "return", "mods", "if", "@remotes", ".", "all", ".", "empty?", "mods", ".", "each", "do", "|", "m", "|", "next", "if", "@seen", ".", "include?", "(", "m", ")", "@mutex", ".", "synchronize", "{", "@seen", "<<", "m", "}", "@modified", ".", "push", "(", "m", ")", "@log", ".", "debug", "(", "\"Spread-push scheduled for #{m}, queue size is #{@modified.size}\"", ")", "end", "mods", "end"], "docstring": "This method is thread-safe", "docstring_tokens": ["This", "method", "is", "thread", "-", "safe"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/node/spread_entrance.rb#L97-L107", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.init", "original_string": "def init(id, pubkey, overwrite: false, network: 'test')\n raise \"File '#{path}' already exists\" if File.exist?(path) && !overwrite\n raise \"Invalid network name '#{network}'\" unless network =~ /^[a-z]{4,16}$/\n FileUtils.mkdir_p(File.dirname(path))\n IO.write(path, \"#{network}\\n#{PROTOCOL}\\n#{id}\\n#{pubkey.to_pub}\\n\\n\")\n @txns.flush\n @head.flush\n end", "language": "ruby", "code": "def init(id, pubkey, overwrite: false, network: 'test')\n raise \"File '#{path}' already exists\" if File.exist?(path) && !overwrite\n raise \"Invalid network name '#{network}'\" unless network =~ /^[a-z]{4,16}$/\n FileUtils.mkdir_p(File.dirname(path))\n IO.write(path, \"#{network}\\n#{PROTOCOL}\\n#{id}\\n#{pubkey.to_pub}\\n\\n\")\n @txns.flush\n @head.flush\n end", "code_tokens": ["def", "init", "(", "id", ",", "pubkey", ",", "overwrite", ":", "false", ",", "network", ":", "'test'", ")", "raise", "\"File '#{path}' already exists\"", "if", "File", ".", "exist?", "(", "path", ")", "&&", "!", "overwrite", "raise", "\"Invalid network name '#{network}'\"", "unless", "network", "=~", "/", "/", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "path", ")", ")", "IO", ".", "write", "(", "path", ",", "\"#{network}\\n#{PROTOCOL}\\n#{id}\\n#{pubkey.to_pub}\\n\\n\"", ")", "@txns", ".", "flush", "@head", ".", "flush", "end"], "docstring": "Creates an empty wallet with the specified ID and public key.", "docstring_tokens": ["Creates", "an", "empty", "wallet", "with", "the", "specified", "ID", "and", "public", "key", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L113-L120", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.balance", "original_string": "def balance\n txns.inject(Amount::ZERO) { |sum, t| sum + t.amount }\n end", "language": "ruby", "code": "def balance\n txns.inject(Amount::ZERO) { |sum, t| sum + t.amount }\n end", "code_tokens": ["def", "balance", "txns", ".", "inject", "(", "Amount", "::", "ZERO", ")", "{", "|", "sum", ",", "t", "|", "sum", "+", "t", ".", "amount", "}", "end"], "docstring": "Returns current wallet balance.", "docstring_tokens": ["Returns", "current", "wallet", "balance", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L133-L135", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.sub", "original_string": "def sub(amount, invoice, pvt, details = '-', time: Time.now)\n raise 'The amount has to be of type Amount' unless amount.is_a?(Amount)\n raise \"The amount can't be negative: #{amount}\" if amount.negative?\n raise 'The pvt has to be of type Key' unless pvt.is_a?(Key)\n prefix, target = invoice.split('@')\n tid = max + 1\n raise 'Too many transactions already, can\\'t add more' if max > 0xffff\n txn = Txn.new(\n tid,\n time,\n amount * -1,\n prefix,\n Id.new(target),\n details\n )\n txn = txn.signed(pvt, id)\n raise \"Invalid private key for the wallet #{id}\" unless Signature.new(network).valid?(key, id, txn)\n add(txn)\n txn\n end", "language": "ruby", "code": "def sub(amount, invoice, pvt, details = '-', time: Time.now)\n raise 'The amount has to be of type Amount' unless amount.is_a?(Amount)\n raise \"The amount can't be negative: #{amount}\" if amount.negative?\n raise 'The pvt has to be of type Key' unless pvt.is_a?(Key)\n prefix, target = invoice.split('@')\n tid = max + 1\n raise 'Too many transactions already, can\\'t add more' if max > 0xffff\n txn = Txn.new(\n tid,\n time,\n amount * -1,\n prefix,\n Id.new(target),\n details\n )\n txn = txn.signed(pvt, id)\n raise \"Invalid private key for the wallet #{id}\" unless Signature.new(network).valid?(key, id, txn)\n add(txn)\n txn\n end", "code_tokens": ["def", "sub", "(", "amount", ",", "invoice", ",", "pvt", ",", "details", "=", "'-'", ",", "time", ":", "Time", ".", "now", ")", "raise", "'The amount has to be of type Amount'", "unless", "amount", ".", "is_a?", "(", "Amount", ")", "raise", "\"The amount can't be negative: #{amount}\"", "if", "amount", ".", "negative?", "raise", "'The pvt has to be of type Key'", "unless", "pvt", ".", "is_a?", "(", "Key", ")", "prefix", ",", "target", "=", "invoice", ".", "split", "(", "'@'", ")", "tid", "=", "max", "+", "1", "raise", "'Too many transactions already, can\\'t add more'", "if", "max", ">", "0xffff", "txn", "=", "Txn", ".", "new", "(", "tid", ",", "time", ",", "amount", "*", "-", "1", ",", "prefix", ",", "Id", ".", "new", "(", "target", ")", ",", "details", ")", "txn", "=", "txn", ".", "signed", "(", "pvt", ",", "id", ")", "raise", "\"Invalid private key for the wallet #{id}\"", "unless", "Signature", ".", "new", "(", "network", ")", ".", "valid?", "(", "key", ",", "id", ",", "txn", ")", "add", "(", "txn", ")", "txn", "end"], "docstring": "Add a payment transaction to the wallet.", "docstring_tokens": ["Add", "a", "payment", "transaction", "to", "the", "wallet", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L138-L157", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.add", "original_string": "def add(txn)\n raise 'The txn has to be of type Txn' unless txn.is_a?(Txn)\n raise \"Wallet #{id} can't pay itself: #{txn}\" if txn.bnf == id\n raise \"The amount can't be zero in #{id}: #{txn}\" if txn.amount.zero?\n if txn.amount.negative? && includes_negative?(txn.id)\n raise \"Negative transaction with the same ID #{txn.id} already exists in #{id}\"\n end\n if txn.amount.positive? && includes_positive?(txn.id, txn.bnf)\n raise \"Positive transaction with the same ID #{txn.id} and BNF #{txn.bnf} already exists in #{id}\"\n end\n raise \"The tax payment already exists in #{id}: #{txn}\" if Tax.new(self).exists?(txn.details)\n File.open(path, 'a') { |f| f.print \"#{txn}\\n\" }\n @txns.flush\n end", "language": "ruby", "code": "def add(txn)\n raise 'The txn has to be of type Txn' unless txn.is_a?(Txn)\n raise \"Wallet #{id} can't pay itself: #{txn}\" if txn.bnf == id\n raise \"The amount can't be zero in #{id}: #{txn}\" if txn.amount.zero?\n if txn.amount.negative? && includes_negative?(txn.id)\n raise \"Negative transaction with the same ID #{txn.id} already exists in #{id}\"\n end\n if txn.amount.positive? && includes_positive?(txn.id, txn.bnf)\n raise \"Positive transaction with the same ID #{txn.id} and BNF #{txn.bnf} already exists in #{id}\"\n end\n raise \"The tax payment already exists in #{id}: #{txn}\" if Tax.new(self).exists?(txn.details)\n File.open(path, 'a') { |f| f.print \"#{txn}\\n\" }\n @txns.flush\n end", "code_tokens": ["def", "add", "(", "txn", ")", "raise", "'The txn has to be of type Txn'", "unless", "txn", ".", "is_a?", "(", "Txn", ")", "raise", "\"Wallet #{id} can't pay itself: #{txn}\"", "if", "txn", ".", "bnf", "==", "id", "raise", "\"The amount can't be zero in #{id}: #{txn}\"", "if", "txn", ".", "amount", ".", "zero?", "if", "txn", ".", "amount", ".", "negative?", "&&", "includes_negative?", "(", "txn", ".", "id", ")", "raise", "\"Negative transaction with the same ID #{txn.id} already exists in #{id}\"", "end", "if", "txn", ".", "amount", ".", "positive?", "&&", "includes_positive?", "(", "txn", ".", "id", ",", "txn", ".", "bnf", ")", "raise", "\"Positive transaction with the same ID #{txn.id} and BNF #{txn.bnf} already exists in #{id}\"", "end", "raise", "\"The tax payment already exists in #{id}: #{txn}\"", "if", "Tax", ".", "new", "(", "self", ")", ".", "exists?", "(", "txn", ".", "details", ")", "File", ".", "open", "(", "path", ",", "'a'", ")", "{", "|", "f", "|", "f", ".", "print", "\"#{txn}\\n\"", "}", "@txns", ".", "flush", "end"], "docstring": "Add a transaction to the wallet.", "docstring_tokens": ["Add", "a", "transaction", "to", "the", "wallet", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L160-L173", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.includes_negative?", "original_string": "def includes_negative?(id, bnf = nil)\n raise 'The txn ID has to be of type Integer' unless id.is_a?(Integer)\n !txns.find { |t| t.id == id && (bnf.nil? || t.bnf == bnf) && t.amount.negative? }.nil?\n end", "language": "ruby", "code": "def includes_negative?(id, bnf = nil)\n raise 'The txn ID has to be of type Integer' unless id.is_a?(Integer)\n !txns.find { |t| t.id == id && (bnf.nil? || t.bnf == bnf) && t.amount.negative? }.nil?\n end", "code_tokens": ["def", "includes_negative?", "(", "id", ",", "bnf", "=", "nil", ")", "raise", "'The txn ID has to be of type Integer'", "unless", "id", ".", "is_a?", "(", "Integer", ")", "!", "txns", ".", "find", "{", "|", "t", "|", "t", ".", "id", "==", "id", "&&", "(", "bnf", ".", "nil?", "||", "t", ".", "bnf", "==", "bnf", ")", "&&", "t", ".", "amount", ".", "negative?", "}", ".", "nil?", "end"], "docstring": "Returns TRUE if the wallet contains a payment sent with the specified\n ID, which was sent to the specified beneficiary.", "docstring_tokens": ["Returns", "TRUE", "if", "the", "wallet", "contains", "a", "payment", "sent", "with", "the", "specified", "ID", "which", "was", "sent", "to", "the", "specified", "beneficiary", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L177-L180", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.includes_positive?", "original_string": "def includes_positive?(id, bnf)\n raise 'The txn ID has to be of type Integer' unless id.is_a?(Integer)\n raise 'The bnf has to be of type Id' unless bnf.is_a?(Id)\n !txns.find { |t| t.id == id && t.bnf == bnf && !t.amount.negative? }.nil?\n end", "language": "ruby", "code": "def includes_positive?(id, bnf)\n raise 'The txn ID has to be of type Integer' unless id.is_a?(Integer)\n raise 'The bnf has to be of type Id' unless bnf.is_a?(Id)\n !txns.find { |t| t.id == id && t.bnf == bnf && !t.amount.negative? }.nil?\n end", "code_tokens": ["def", "includes_positive?", "(", "id", ",", "bnf", ")", "raise", "'The txn ID has to be of type Integer'", "unless", "id", ".", "is_a?", "(", "Integer", ")", "raise", "'The bnf has to be of type Id'", "unless", "bnf", ".", "is_a?", "(", "Id", ")", "!", "txns", ".", "find", "{", "|", "t", "|", "t", ".", "id", "==", "id", "&&", "t", ".", "bnf", "==", "bnf", "&&", "!", "t", ".", "amount", ".", "negative?", "}", ".", "nil?", "end"], "docstring": "Returns TRUE if the wallet contains a payment received with the specified\n ID, which was sent by the specified beneficiary.", "docstring_tokens": ["Returns", "TRUE", "if", "the", "wallet", "contains", "a", "payment", "received", "with", "the", "specified", "ID", "which", "was", "sent", "by", "the", "specified", "beneficiary", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L184-L188", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.age", "original_string": "def age\n list = txns\n list.empty? ? 0 : (Time.now - list.min_by(&:date).date) / (60 * 60)\n end", "language": "ruby", "code": "def age\n list = txns\n list.empty? ? 0 : (Time.now - list.min_by(&:date).date) / (60 * 60)\n end", "code_tokens": ["def", "age", "list", "=", "txns", "list", ".", "empty?", "?", "0", ":", "(", "Time", ".", "now", "-", "list", ".", "min_by", "(", "&", ":date", ")", ".", "date", ")", "/", "(", "60", "*", "60", ")", "end"], "docstring": "Age of wallet in hours.", "docstring_tokens": ["Age", "of", "wallet", "in", "hours", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L212-L215", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/wallet.rb", "func_name": "Zold.Wallet.max", "original_string": "def max\n negative = txns.select { |t| t.amount.negative? }\n negative.empty? ? 0 : negative.max_by(&:id).id\n end", "language": "ruby", "code": "def max\n negative = txns.select { |t| t.amount.negative? }\n negative.empty? ? 0 : negative.max_by(&:id).id\n end", "code_tokens": ["def", "max", "negative", "=", "txns", ".", "select", "{", "|", "t", "|", "t", ".", "amount", ".", "negative?", "}", "negative", ".", "empty?", "?", "0", ":", "negative", ".", "max_by", "(", "&", ":id", ")", ".", "id", "end"], "docstring": "Calculate the maximum transaction ID visible currently in the wallet.\n We go through them all and find the largest number. If there are\n no transactions, zero is returned.", "docstring_tokens": ["Calculate", "the", "maximum", "transaction", "ID", "visible", "currently", "in", "the", "wallet", ".", "We", "go", "through", "them", "all", "and", "find", "the", "largest", "number", ".", "If", "there", "are", "no", "transactions", "zero", "is", "returned", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/wallet.rb#L250-L253", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/commands/propagate.rb", "func_name": "Zold.Propagate.propagate", "original_string": "def propagate(id, _)\n start = Time.now\n modified = []\n total = 0\n network = @wallets.acq(id, &:network)\n @wallets.acq(id, &:txns).select { |t| t.amount.negative? }.each do |t|\n total += 1\n if t.bnf == id\n @log.error(\"Paying itself in #{id}? #{t}\")\n next\n end\n @wallets.acq(t.bnf, exclusive: true) do |target|\n unless target.exists?\n @log.debug(\"#{t.amount * -1} from #{id} to #{t.bnf}: wallet is absent\")\n next\n end\n unless target.network == network\n @log.debug(\"#{t.amount * -1} to #{t.bnf}: network mismatch, '#{target.network}'!='#{network}'\")\n next\n end\n next if target.includes_positive?(t.id, id)\n unless target.prefix?(t.prefix)\n @log.debug(\"#{t.amount * -1} from #{id} to #{t.bnf}: wrong prefix \\\"#{t.prefix}\\\" in \\\"#{t}\\\"\")\n next\n end\n target.add(t.inverse(id))\n @log.info(\"#{t.amount * -1} arrived to #{t.bnf}: #{t.details}\")\n modified << t.bnf\n end\n end\n modified.uniq!\n @log.debug(\"Wallet #{id} propagated successfully, #{total} txns \\\nin #{Age.new(start, limit: 20 + total * 0.005)}, #{modified.count} wallets affected\")\n modified.each do |w|\n @wallets.acq(w, &:refurbish)\n end\n modified\n end", "language": "ruby", "code": "def propagate(id, _)\n start = Time.now\n modified = []\n total = 0\n network = @wallets.acq(id, &:network)\n @wallets.acq(id, &:txns).select { |t| t.amount.negative? }.each do |t|\n total += 1\n if t.bnf == id\n @log.error(\"Paying itself in #{id}? #{t}\")\n next\n end\n @wallets.acq(t.bnf, exclusive: true) do |target|\n unless target.exists?\n @log.debug(\"#{t.amount * -1} from #{id} to #{t.bnf}: wallet is absent\")\n next\n end\n unless target.network == network\n @log.debug(\"#{t.amount * -1} to #{t.bnf}: network mismatch, '#{target.network}'!='#{network}'\")\n next\n end\n next if target.includes_positive?(t.id, id)\n unless target.prefix?(t.prefix)\n @log.debug(\"#{t.amount * -1} from #{id} to #{t.bnf}: wrong prefix \\\"#{t.prefix}\\\" in \\\"#{t}\\\"\")\n next\n end\n target.add(t.inverse(id))\n @log.info(\"#{t.amount * -1} arrived to #{t.bnf}: #{t.details}\")\n modified << t.bnf\n end\n end\n modified.uniq!\n @log.debug(\"Wallet #{id} propagated successfully, #{total} txns \\\nin #{Age.new(start, limit: 20 + total * 0.005)}, #{modified.count} wallets affected\")\n modified.each do |w|\n @wallets.acq(w, &:refurbish)\n end\n modified\n end", "code_tokens": ["def", "propagate", "(", "id", ",", "_", ")", "start", "=", "Time", ".", "now", "modified", "=", "[", "]", "total", "=", "0", "network", "=", "@wallets", ".", "acq", "(", "id", ",", "&", ":network", ")", "@wallets", ".", "acq", "(", "id", ",", "&", ":txns", ")", ".", "select", "{", "|", "t", "|", "t", ".", "amount", ".", "negative?", "}", ".", "each", "do", "|", "t", "|", "total", "+=", "1", "if", "t", ".", "bnf", "==", "id", "@log", ".", "error", "(", "\"Paying itself in #{id}? #{t}\"", ")", "next", "end", "@wallets", ".", "acq", "(", "t", ".", "bnf", ",", "exclusive", ":", "true", ")", "do", "|", "target", "|", "unless", "target", ".", "exists?", "@log", ".", "debug", "(", "\"#{t.amount * -1} from #{id} to #{t.bnf}: wallet is absent\"", ")", "next", "end", "unless", "target", ".", "network", "==", "network", "@log", ".", "debug", "(", "\"#{t.amount * -1} to #{t.bnf}: network mismatch, '#{target.network}'!='#{network}'\"", ")", "next", "end", "next", "if", "target", ".", "includes_positive?", "(", "t", ".", "id", ",", "id", ")", "unless", "target", ".", "prefix?", "(", "t", ".", "prefix", ")", "@log", ".", "debug", "(", "\"#{t.amount * -1} from #{id} to #{t.bnf}: wrong prefix \\\"#{t.prefix}\\\" in \\\"#{t}\\\"\"", ")", "next", "end", "target", ".", "add", "(", "t", ".", "inverse", "(", "id", ")", ")", "@log", ".", "info", "(", "\"#{t.amount * -1} arrived to #{t.bnf}: #{t.details}\"", ")", "modified", "<<", "t", ".", "bnf", "end", "end", "modified", ".", "uniq!", "@log", ".", "debug", "(", "\"Wallet #{id} propagated successfully, #{total} txns \\in #{Age.new(start, limit: 20 + total * 0.005)}, #{modified.count} wallets affected\"", ")", "modified", ".", "each", "do", "|", "w", "|", "@wallets", ".", "acq", "(", "w", ",", "&", ":refurbish", ")", "end", "modified", "end"], "docstring": "Returns list of Wallet IDs which were affected", "docstring_tokens": ["Returns", "list", "of", "Wallet", "IDs", "which", "were", "affected"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/commands/propagate.rb#L65-L102", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/commands/node.rb", "func_name": "Zold.Node.exec", "original_string": "def exec(cmd, nohup_log)\n start = Time.now\n Open3.popen2e({ 'MALLOC_ARENA_MAX' => '2' }, cmd) do |stdin, stdout, thr|\n nohup_log.print(\"Started process ##{thr.pid} from process ##{Process.pid}: #{cmd}\\n\")\n stdin.close\n until stdout.eof?\n begin\n line = stdout.gets\n rescue IOError => e\n line = Backtrace.new(e).to_s\n end\n nohup_log.print(line)\n end\n nohup_log.print(\"Nothing else left to read from ##{thr.pid}\\n\")\n code = thr.value.to_i\n nohup_log.print(\"Exit code of process ##{thr.pid} is #{code}, was alive for #{Age.new(start)}: #{cmd}\\n\")\n code\n end\n end", "language": "ruby", "code": "def exec(cmd, nohup_log)\n start = Time.now\n Open3.popen2e({ 'MALLOC_ARENA_MAX' => '2' }, cmd) do |stdin, stdout, thr|\n nohup_log.print(\"Started process ##{thr.pid} from process ##{Process.pid}: #{cmd}\\n\")\n stdin.close\n until stdout.eof?\n begin\n line = stdout.gets\n rescue IOError => e\n line = Backtrace.new(e).to_s\n end\n nohup_log.print(line)\n end\n nohup_log.print(\"Nothing else left to read from ##{thr.pid}\\n\")\n code = thr.value.to_i\n nohup_log.print(\"Exit code of process ##{thr.pid} is #{code}, was alive for #{Age.new(start)}: #{cmd}\\n\")\n code\n end\n end", "code_tokens": ["def", "exec", "(", "cmd", ",", "nohup_log", ")", "start", "=", "Time", ".", "now", "Open3", ".", "popen2e", "(", "{", "'MALLOC_ARENA_MAX'", "=>", "'2'", "}", ",", "cmd", ")", "do", "|", "stdin", ",", "stdout", ",", "thr", "|", "nohup_log", ".", "print", "(", "\"Started process ##{thr.pid} from process ##{Process.pid}: #{cmd}\\n\"", ")", "stdin", ".", "close", "until", "stdout", ".", "eof?", "begin", "line", "=", "stdout", ".", "gets", "rescue", "IOError", "=>", "e", "line", "=", "Backtrace", ".", "new", "(", "e", ")", ".", "to_s", "end", "nohup_log", ".", "print", "(", "line", ")", "end", "nohup_log", ".", "print", "(", "\"Nothing else left to read from ##{thr.pid}\\n\"", ")", "code", "=", "thr", ".", "value", ".", "to_i", "nohup_log", ".", "print", "(", "\"Exit code of process ##{thr.pid} is #{code}, was alive for #{Age.new(start)}: #{cmd}\\n\"", ")", "code", "end", "end"], "docstring": "Returns exit code", "docstring_tokens": ["Returns", "exit", "code"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/commands/node.rb#L374-L392", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/thread_pool.rb", "func_name": "Zold.ThreadPool.add", "original_string": "def add\n raise 'Block must be given to start()' unless block_given?\n latch = Concurrent::CountDownLatch.new(1)\n thread = Thread.start do\n Thread.current.name = @title\n VerboseThread.new(@log).run do\n latch.count_down\n yield\n end\n end\n latch.wait\n Thread.current.thread_variable_set(\n :kids,\n (Thread.current.thread_variable_get(:kids) || []) + [thread]\n )\n @threads << thread\n end", "language": "ruby", "code": "def add\n raise 'Block must be given to start()' unless block_given?\n latch = Concurrent::CountDownLatch.new(1)\n thread = Thread.start do\n Thread.current.name = @title\n VerboseThread.new(@log).run do\n latch.count_down\n yield\n end\n end\n latch.wait\n Thread.current.thread_variable_set(\n :kids,\n (Thread.current.thread_variable_get(:kids) || []) + [thread]\n )\n @threads << thread\n end", "code_tokens": ["def", "add", "raise", "'Block must be given to start()'", "unless", "block_given?", "latch", "=", "Concurrent", "::", "CountDownLatch", ".", "new", "(", "1", ")", "thread", "=", "Thread", ".", "start", "do", "Thread", ".", "current", ".", "name", "=", "@title", "VerboseThread", ".", "new", "(", "@log", ")", ".", "run", "do", "latch", ".", "count_down", "yield", "end", "end", "latch", ".", "wait", "Thread", ".", "current", ".", "thread_variable_set", "(", ":kids", ",", "(", "Thread", ".", "current", ".", "thread_variable_get", "(", ":kids", ")", "||", "[", "]", ")", "+", "[", "thread", "]", ")", "@threads", "<<", "thread", "end"], "docstring": "Add a new thread", "docstring_tokens": ["Add", "a", "new", "thread"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/thread_pool.rb#L42-L58", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/thread_pool.rb", "func_name": "Zold.ThreadPool.kill", "original_string": "def kill\n if @threads.empty?\n @log.debug(\"Thread pool \\\"#{@title}\\\" terminated with no threads\")\n return\n end\n @log.debug(\"Stopping \\\"#{@title}\\\" thread pool with #{@threads.count} threads: \\\n#{@threads.map { |t| \"#{t.name}/#{t.status}\" }.join(', ')}...\")\n start = Time.new\n begin\n join(0.1)\n ensure\n @threads.each do |t|\n (t.thread_variable_get(:kids) || []).each(&:kill)\n t.kill\n sleep(0.001) while t.alive? # I believe it's a bug in Ruby, this line fixes it\n Thread.current.thread_variable_set(\n :kids,\n (Thread.current.thread_variable_get(:kids) || []) - [t]\n )\n end\n @log.debug(\"Thread pool \\\"#{@title}\\\" terminated all threads in #{Age.new(start)}, \\\nit was alive for #{Age.new(@start)}: #{@threads.map { |t| \"#{t.name}/#{t.status}\" }.join(', ')}\")\n @threads.clear\n end\n end", "language": "ruby", "code": "def kill\n if @threads.empty?\n @log.debug(\"Thread pool \\\"#{@title}\\\" terminated with no threads\")\n return\n end\n @log.debug(\"Stopping \\\"#{@title}\\\" thread pool with #{@threads.count} threads: \\\n#{@threads.map { |t| \"#{t.name}/#{t.status}\" }.join(', ')}...\")\n start = Time.new\n begin\n join(0.1)\n ensure\n @threads.each do |t|\n (t.thread_variable_get(:kids) || []).each(&:kill)\n t.kill\n sleep(0.001) while t.alive? # I believe it's a bug in Ruby, this line fixes it\n Thread.current.thread_variable_set(\n :kids,\n (Thread.current.thread_variable_get(:kids) || []) - [t]\n )\n end\n @log.debug(\"Thread pool \\\"#{@title}\\\" terminated all threads in #{Age.new(start)}, \\\nit was alive for #{Age.new(@start)}: #{@threads.map { |t| \"#{t.name}/#{t.status}\" }.join(', ')}\")\n @threads.clear\n end\n end", "code_tokens": ["def", "kill", "if", "@threads", ".", "empty?", "@log", ".", "debug", "(", "\"Thread pool \\\"#{@title}\\\" terminated with no threads\"", ")", "return", "end", "@log", ".", "debug", "(", "\"Stopping \\\"#{@title}\\\" thread pool with #{@threads.count} threads: \\#{@threads.map { |t| \"#{t.name}/#{t.status}\" }.join(', ')}...\"", ")", "start", "=", "Time", ".", "new", "begin", "join", "(", "0.1", ")", "ensure", "@threads", ".", "each", "do", "|", "t", "|", "(", "t", ".", "thread_variable_get", "(", ":kids", ")", "||", "[", "]", ")", ".", "each", "(", "&", ":kill", ")", "t", ".", "kill", "sleep", "(", "0.001", ")", "while", "t", ".", "alive?", "Thread", ".", "current", ".", "thread_variable_set", "(", ":kids", ",", "(", "Thread", ".", "current", ".", "thread_variable_get", "(", ":kids", ")", "||", "[", "]", ")", "-", "[", "t", "]", ")", "end", "@log", ".", "debug", "(", "\"Thread pool \\\"#{@title}\\\" terminated all threads in #{Age.new(start)}, \\it was alive for #{Age.new(@start)}: #{@threads.map { |t| \"#{t.name}/#{t.status}\" }.join(', ')}\"", ")", "@threads", ".", "clear", "end", "end"], "docstring": "Kill them all immediately and close the pool", "docstring_tokens": ["Kill", "them", "all", "immediately", "and", "close", "the", "pool"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/thread_pool.rb#L65-L89", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/thread_pool.rb", "func_name": "Zold.ThreadPool.to_json", "original_string": "def to_json\n @threads.map do |t|\n {\n name: t.name,\n status: t.status,\n alive: t.alive?,\n vars: Hash[t.thread_variables.map { |v| [v.to_s, t.thread_variable_get(v)] }]\n }\n end\n end", "language": "ruby", "code": "def to_json\n @threads.map do |t|\n {\n name: t.name,\n status: t.status,\n alive: t.alive?,\n vars: Hash[t.thread_variables.map { |v| [v.to_s, t.thread_variable_get(v)] }]\n }\n end\n end", "code_tokens": ["def", "to_json", "@threads", ".", "map", "do", "|", "t", "|", "{", "name", ":", "t", ".", "name", ",", "status", ":", "t", ".", "status", ",", "alive", ":", "t", ".", "alive?", ",", "vars", ":", "Hash", "[", "t", ".", "thread_variables", ".", "map", "{", "|", "v", "|", "[", "v", ".", "to_s", ",", "t", ".", "thread_variable_get", "(", "v", ")", "]", "}", "]", "}", "end", "end"], "docstring": "As a hash map", "docstring_tokens": ["As", "a", "hash", "map"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/thread_pool.rb#L107-L116", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/thread_pool.rb", "func_name": "Zold.ThreadPool.to_s", "original_string": "def to_s\n @threads.map do |t|\n [\n \"#{t.name}: status=#{t.status}; alive=#{t.alive?}\",\n 'Vars: ' + t.thread_variables.map { |v| \"#{v}=\\\"#{t.thread_variable_get(v)}\\\"\" }.join('; '),\n t.backtrace.nil? ? 'NO BACKTRACE' : \" #{t.backtrace.join(\"\\n \")}\"\n ].join(\"\\n\")\n end\n end", "language": "ruby", "code": "def to_s\n @threads.map do |t|\n [\n \"#{t.name}: status=#{t.status}; alive=#{t.alive?}\",\n 'Vars: ' + t.thread_variables.map { |v| \"#{v}=\\\"#{t.thread_variable_get(v)}\\\"\" }.join('; '),\n t.backtrace.nil? ? 'NO BACKTRACE' : \" #{t.backtrace.join(\"\\n \")}\"\n ].join(\"\\n\")\n end\n end", "code_tokens": ["def", "to_s", "@threads", ".", "map", "do", "|", "t", "|", "[", "\"#{t.name}: status=#{t.status}; alive=#{t.alive?}\"", ",", "'Vars: '", "+", "t", ".", "thread_variables", ".", "map", "{", "|", "v", "|", "\"#{v}=\\\"#{t.thread_variable_get(v)}\\\"\"", "}", ".", "join", "(", "'; '", ")", ",", "t", ".", "backtrace", ".", "nil?", "?", "'NO BACKTRACE'", ":", "\" #{t.backtrace.join(\"\\n \")}\"", "]", ".", "join", "(", "\"\\n\"", ")", "end", "end"], "docstring": "As a text", "docstring_tokens": ["As", "a", "text"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/thread_pool.rb#L119-L127", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/patch.rb", "func_name": "Zold.Patch.legacy", "original_string": "def legacy(wallet, hours: 24)\n raise 'You can\\'t add legacy to a non-empty patch' unless @id.nil?\n wallet.txns.each do |txn|\n @txns << txn if txn.amount.negative? && txn.date < Time.now - hours * 60 * 60\n end\n end", "language": "ruby", "code": "def legacy(wallet, hours: 24)\n raise 'You can\\'t add legacy to a non-empty patch' unless @id.nil?\n wallet.txns.each do |txn|\n @txns << txn if txn.amount.negative? && txn.date < Time.now - hours * 60 * 60\n end\n end", "code_tokens": ["def", "legacy", "(", "wallet", ",", "hours", ":", "24", ")", "raise", "'You can\\'t add legacy to a non-empty patch'", "unless", "@id", ".", "nil?", "wallet", ".", "txns", ".", "each", "do", "|", "txn", "|", "@txns", "<<", "txn", "if", "txn", ".", "amount", ".", "negative?", "&&", "txn", ".", "date", "<", "Time", ".", "now", "-", "hours", "*", "60", "*", "60", "end", "end"], "docstring": "Add legacy transactions first, since they are negative and can't\n be deleted ever. This method is called by merge.rb in order to add\n legacy negative transactions to the patch before everything else. They\n are not supposed to be disputed, ever.", "docstring_tokens": ["Add", "legacy", "transactions", "first", "since", "they", "are", "negative", "and", "can", "t", "be", "deleted", "ever", ".", "This", "method", "is", "called", "by", "merge", ".", "rb", "in", "order", "to", "add", "legacy", "negative", "transactions", "to", "the", "patch", "before", "everything", "else", ".", "They", "are", "not", "supposed", "to", "be", "disputed", "ever", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/patch.rb#L51-L56", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/patch.rb", "func_name": "Zold.Patch.save", "original_string": "def save(file, overwrite: false, allow_negative_balance: false)\n raise 'You have to join at least one wallet in' if empty?\n before = ''\n wallet = Wallet.new(file)\n before = wallet.digest if wallet.exists?\n Tempfile.open([@id, Wallet::EXT]) do |f|\n temp = Wallet.new(f.path)\n temp.init(@id, @key, overwrite: overwrite, network: @network)\n File.open(f.path, 'a') do |t|\n @txns.each do |txn|\n next if Id::BANNED.include?(txn.bnf.to_s)\n t.print \"#{txn}\\n\"\n end\n end\n temp.refurbish\n if temp.balance.negative? && !temp.id.root? && !allow_negative_balance\n if wallet.exists?\n @log.info(\"The balance is negative, won't merge #{temp.mnemo} on top of #{wallet.mnemo}\")\n else\n @log.info(\"The balance is negative, won't save #{temp.mnemo}\")\n end\n else\n FileUtils.mkdir_p(File.dirname(file))\n IO.write(file, IO.read(f.path))\n end\n end\n before != wallet.digest\n end", "language": "ruby", "code": "def save(file, overwrite: false, allow_negative_balance: false)\n raise 'You have to join at least one wallet in' if empty?\n before = ''\n wallet = Wallet.new(file)\n before = wallet.digest if wallet.exists?\n Tempfile.open([@id, Wallet::EXT]) do |f|\n temp = Wallet.new(f.path)\n temp.init(@id, @key, overwrite: overwrite, network: @network)\n File.open(f.path, 'a') do |t|\n @txns.each do |txn|\n next if Id::BANNED.include?(txn.bnf.to_s)\n t.print \"#{txn}\\n\"\n end\n end\n temp.refurbish\n if temp.balance.negative? && !temp.id.root? && !allow_negative_balance\n if wallet.exists?\n @log.info(\"The balance is negative, won't merge #{temp.mnemo} on top of #{wallet.mnemo}\")\n else\n @log.info(\"The balance is negative, won't save #{temp.mnemo}\")\n end\n else\n FileUtils.mkdir_p(File.dirname(file))\n IO.write(file, IO.read(f.path))\n end\n end\n before != wallet.digest\n end", "code_tokens": ["def", "save", "(", "file", ",", "overwrite", ":", "false", ",", "allow_negative_balance", ":", "false", ")", "raise", "'You have to join at least one wallet in'", "if", "empty?", "before", "=", "''", "wallet", "=", "Wallet", ".", "new", "(", "file", ")", "before", "=", "wallet", ".", "digest", "if", "wallet", ".", "exists?", "Tempfile", ".", "open", "(", "[", "@id", ",", "Wallet", "::", "EXT", "]", ")", "do", "|", "f", "|", "temp", "=", "Wallet", ".", "new", "(", "f", ".", "path", ")", "temp", ".", "init", "(", "@id", ",", "@key", ",", "overwrite", ":", "overwrite", ",", "network", ":", "@network", ")", "File", ".", "open", "(", "f", ".", "path", ",", "'a'", ")", "do", "|", "t", "|", "@txns", ".", "each", "do", "|", "txn", "|", "next", "if", "Id", "::", "BANNED", ".", "include?", "(", "txn", ".", "bnf", ".", "to_s", ")", "t", ".", "print", "\"#{txn}\\n\"", "end", "end", "temp", ".", "refurbish", "if", "temp", ".", "balance", ".", "negative?", "&&", "!", "temp", ".", "id", ".", "root?", "&&", "!", "allow_negative_balance", "if", "wallet", ".", "exists?", "@log", ".", "info", "(", "\"The balance is negative, won't merge #{temp.mnemo} on top of #{wallet.mnemo}\"", ")", "else", "@log", ".", "info", "(", "\"The balance is negative, won't save #{temp.mnemo}\"", ")", "end", "else", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "file", ")", ")", "IO", ".", "write", "(", "file", ",", "IO", ".", "read", "(", "f", ".", "path", ")", ")", "end", "end", "before", "!=", "wallet", ".", "digest", "end"], "docstring": "Returns TRUE if the file was actually modified", "docstring_tokens": ["Returns", "TRUE", "if", "the", "file", "was", "actually", "modified"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/patch.rb#L186-L213", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/copies.rb", "func_name": "Zold.Copies.clean", "original_string": "def clean(max: 24 * 60 * 60)\n Futex.new(file, log: @log).open do\n list = load\n list.reject! do |s|\n if s[:time] >= Time.now - max\n false\n else\n @log.debug(\"Copy ##{s[:name]}/#{s[:host]}:#{s[:port]} is too old, over #{Age.new(s[:time])}\")\n true\n end\n end\n save(list)\n deleted = 0\n files.each do |f|\n next unless list.find { |s| s[:name] == File.basename(f, Copies::EXT) }.nil?\n file = File.join(@dir, f)\n size = File.size(file)\n File.delete(file)\n @log.debug(\"Copy at #{f} deleted: #{Size.new(size)}\")\n deleted += 1\n end\n list.select! do |s|\n cp = File.join(@dir, \"#{s[:name]}#{Copies::EXT}\")\n wallet = Wallet.new(cp)\n begin\n wallet.refurbish\n raise \"Invalid protocol #{wallet.protocol} in #{cp}\" unless wallet.protocol == Zold::PROTOCOL\n true\n rescue StandardError => e\n FileUtils.rm_rf(cp)\n @log.debug(\"Copy at #{cp} deleted: #{Backtrace.new(e)}\")\n deleted += 1\n false\n end\n end\n save(list)\n deleted\n end\n end", "language": "ruby", "code": "def clean(max: 24 * 60 * 60)\n Futex.new(file, log: @log).open do\n list = load\n list.reject! do |s|\n if s[:time] >= Time.now - max\n false\n else\n @log.debug(\"Copy ##{s[:name]}/#{s[:host]}:#{s[:port]} is too old, over #{Age.new(s[:time])}\")\n true\n end\n end\n save(list)\n deleted = 0\n files.each do |f|\n next unless list.find { |s| s[:name] == File.basename(f, Copies::EXT) }.nil?\n file = File.join(@dir, f)\n size = File.size(file)\n File.delete(file)\n @log.debug(\"Copy at #{f} deleted: #{Size.new(size)}\")\n deleted += 1\n end\n list.select! do |s|\n cp = File.join(@dir, \"#{s[:name]}#{Copies::EXT}\")\n wallet = Wallet.new(cp)\n begin\n wallet.refurbish\n raise \"Invalid protocol #{wallet.protocol} in #{cp}\" unless wallet.protocol == Zold::PROTOCOL\n true\n rescue StandardError => e\n FileUtils.rm_rf(cp)\n @log.debug(\"Copy at #{cp} deleted: #{Backtrace.new(e)}\")\n deleted += 1\n false\n end\n end\n save(list)\n deleted\n end\n end", "code_tokens": ["def", "clean", "(", "max", ":", "24", "*", "60", "*", "60", ")", "Futex", ".", "new", "(", "file", ",", "log", ":", "@log", ")", ".", "open", "do", "list", "=", "load", "list", ".", "reject!", "do", "|", "s", "|", "if", "s", "[", ":time", "]", ">=", "Time", ".", "now", "-", "max", "false", "else", "@log", ".", "debug", "(", "\"Copy ##{s[:name]}/#{s[:host]}:#{s[:port]} is too old, over #{Age.new(s[:time])}\"", ")", "true", "end", "end", "save", "(", "list", ")", "deleted", "=", "0", "files", ".", "each", "do", "|", "f", "|", "next", "unless", "list", ".", "find", "{", "|", "s", "|", "s", "[", ":name", "]", "==", "File", ".", "basename", "(", "f", ",", "Copies", "::", "EXT", ")", "}", ".", "nil?", "file", "=", "File", ".", "join", "(", "@dir", ",", "f", ")", "size", "=", "File", ".", "size", "(", "file", ")", "File", ".", "delete", "(", "file", ")", "@log", ".", "debug", "(", "\"Copy at #{f} deleted: #{Size.new(size)}\"", ")", "deleted", "+=", "1", "end", "list", ".", "select!", "do", "|", "s", "|", "cp", "=", "File", ".", "join", "(", "@dir", ",", "\"#{s[:name]}#{Copies::EXT}\"", ")", "wallet", "=", "Wallet", ".", "new", "(", "cp", ")", "begin", "wallet", ".", "refurbish", "raise", "\"Invalid protocol #{wallet.protocol} in #{cp}\"", "unless", "wallet", ".", "protocol", "==", "Zold", "::", "PROTOCOL", "true", "rescue", "StandardError", "=>", "e", "FileUtils", ".", "rm_rf", "(", "cp", ")", "@log", ".", "debug", "(", "\"Copy at #{cp} deleted: #{Backtrace.new(e)}\"", ")", "deleted", "+=", "1", "false", "end", "end", "save", "(", "list", ")", "deleted", "end", "end"], "docstring": "Delete all copies that are older than the \"max\" age provided, in seconds.", "docstring_tokens": ["Delete", "all", "copies", "that", "are", "older", "than", "the", "max", "age", "provided", "in", "seconds", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/copies.rb#L57-L95", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/copies.rb", "func_name": "Zold.Copies.add", "original_string": "def add(content, host, port, score, time: Time.now, master: false)\n raise \"Content can't be empty\" if content.empty?\n raise 'TCP port must be of type Integer' unless port.is_a?(Integer)\n raise \"TCP port can't be negative: #{port}\" if port.negative?\n raise 'Time must be of type Time' unless time.is_a?(Time)\n raise \"Time must be in the past: #{time}\" if time > Time.now\n raise 'Score must be Integer' unless score.is_a?(Integer)\n raise \"Score can't be negative: #{score}\" if score.negative?\n FileUtils.mkdir_p(@dir)\n Futex.new(file, log: @log).open do\n list = load\n target = list.find do |s|\n f = File.join(@dir, \"#{s[:name]}#{Copies::EXT}\")\n digest = OpenSSL::Digest::SHA256.new(content).hexdigest\n File.exist?(f) && OpenSSL::Digest::SHA256.file(f).hexdigest == digest\n end\n if target.nil?\n max = DirItems.new(@dir).fetch\n .select { |f| File.basename(f, Copies::EXT) =~ /^[0-9]+$/ }\n .map(&:to_i)\n .max\n max = 0 if max.nil?\n name = (max + 1).to_s\n IO.write(File.join(@dir, \"#{name}#{Copies::EXT}\"), content)\n else\n name = target[:name]\n end\n list.reject! { |s| s[:host] == host && s[:port] == port }\n list << {\n name: name,\n host: host,\n port: port,\n score: score,\n time: time,\n master: master\n }\n save(list)\n name\n end\n end", "language": "ruby", "code": "def add(content, host, port, score, time: Time.now, master: false)\n raise \"Content can't be empty\" if content.empty?\n raise 'TCP port must be of type Integer' unless port.is_a?(Integer)\n raise \"TCP port can't be negative: #{port}\" if port.negative?\n raise 'Time must be of type Time' unless time.is_a?(Time)\n raise \"Time must be in the past: #{time}\" if time > Time.now\n raise 'Score must be Integer' unless score.is_a?(Integer)\n raise \"Score can't be negative: #{score}\" if score.negative?\n FileUtils.mkdir_p(@dir)\n Futex.new(file, log: @log).open do\n list = load\n target = list.find do |s|\n f = File.join(@dir, \"#{s[:name]}#{Copies::EXT}\")\n digest = OpenSSL::Digest::SHA256.new(content).hexdigest\n File.exist?(f) && OpenSSL::Digest::SHA256.file(f).hexdigest == digest\n end\n if target.nil?\n max = DirItems.new(@dir).fetch\n .select { |f| File.basename(f, Copies::EXT) =~ /^[0-9]+$/ }\n .map(&:to_i)\n .max\n max = 0 if max.nil?\n name = (max + 1).to_s\n IO.write(File.join(@dir, \"#{name}#{Copies::EXT}\"), content)\n else\n name = target[:name]\n end\n list.reject! { |s| s[:host] == host && s[:port] == port }\n list << {\n name: name,\n host: host,\n port: port,\n score: score,\n time: time,\n master: master\n }\n save(list)\n name\n end\n end", "code_tokens": ["def", "add", "(", "content", ",", "host", ",", "port", ",", "score", ",", "time", ":", "Time", ".", "now", ",", "master", ":", "false", ")", "raise", "\"Content can't be empty\"", "if", "content", ".", "empty?", "raise", "'TCP port must be of type Integer'", "unless", "port", ".", "is_a?", "(", "Integer", ")", "raise", "\"TCP port can't be negative: #{port}\"", "if", "port", ".", "negative?", "raise", "'Time must be of type Time'", "unless", "time", ".", "is_a?", "(", "Time", ")", "raise", "\"Time must be in the past: #{time}\"", "if", "time", ">", "Time", ".", "now", "raise", "'Score must be Integer'", "unless", "score", ".", "is_a?", "(", "Integer", ")", "raise", "\"Score can't be negative: #{score}\"", "if", "score", ".", "negative?", "FileUtils", ".", "mkdir_p", "(", "@dir", ")", "Futex", ".", "new", "(", "file", ",", "log", ":", "@log", ")", ".", "open", "do", "list", "=", "load", "target", "=", "list", ".", "find", "do", "|", "s", "|", "f", "=", "File", ".", "join", "(", "@dir", ",", "\"#{s[:name]}#{Copies::EXT}\"", ")", "digest", "=", "OpenSSL", "::", "Digest", "::", "SHA256", ".", "new", "(", "content", ")", ".", "hexdigest", "File", ".", "exist?", "(", "f", ")", "&&", "OpenSSL", "::", "Digest", "::", "SHA256", ".", "file", "(", "f", ")", ".", "hexdigest", "==", "digest", "end", "if", "target", ".", "nil?", "max", "=", "DirItems", ".", "new", "(", "@dir", ")", ".", "fetch", ".", "select", "{", "|", "f", "|", "File", ".", "basename", "(", "f", ",", "Copies", "::", "EXT", ")", "=~", "/", "/", "}", ".", "map", "(", "&", ":to_i", ")", ".", "max", "max", "=", "0", "if", "max", ".", "nil?", "name", "=", "(", "max", "+", "1", ")", ".", "to_s", "IO", ".", "write", "(", "File", ".", "join", "(", "@dir", ",", "\"#{name}#{Copies::EXT}\"", ")", ",", "content", ")", "else", "name", "=", "target", "[", ":name", "]", "end", "list", ".", "reject!", "{", "|", "s", "|", "s", "[", ":host", "]", "==", "host", "&&", "s", "[", ":port", "]", "==", "port", "}", "list", "<<", "{", "name", ":", "name", ",", "host", ":", "host", ",", "port", ":", "port", ",", "score", ":", "score", ",", "time", ":", "time", ",", "master", ":", "master", "}", "save", "(", "list", ")", "name", "end", "end"], "docstring": "Returns the name of the copy", "docstring_tokens": ["Returns", "the", "name", "of", "the", "copy"], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/copies.rb#L104-L143", "partition": "valid"}
{"repo": "zold-io/zold", "path": "lib/zold/remotes.rb", "func_name": "Zold.Remotes.iterate", "original_string": "def iterate(log, farm: Farm::Empty.new, threads: 1)\n raise 'Log can\\'t be nil' if log.nil?\n raise 'Farm can\\'t be nil' if farm.nil?\n Hands.exec(threads, all) do |r, idx|\n Thread.current.name = \"remotes-#{idx}@#{r[:host]}:#{r[:port]}\"\n start = Time.now\n best = farm.best[0]\n node = RemoteNode.new(\n host: r[:host],\n port: r[:port],\n score: best.nil? ? Score::ZERO : best,\n idx: idx,\n master: master?(r[:host], r[:port]),\n log: log,\n network: @network\n )\n begin\n yield node\n raise 'Took too long to execute' if (Time.now - start).round > @timeout\n unerror(r[:host], r[:port]) if node.touched\n rescue StandardError => e\n error(r[:host], r[:port])\n if e.is_a?(RemoteNode::CantAssert) || e.is_a?(Fetch::Error)\n log.debug(\"#{Rainbow(node).red}: \\\"#{e.message.strip}\\\" in #{Age.new(start)}\")\n else\n log.info(\"#{Rainbow(node).red}: \\\"#{e.message.strip}\\\" in #{Age.new(start)}\")\n log.debug(Backtrace.new(e).to_s)\n end\n remove(r[:host], r[:port]) if r[:errors] > TOLERANCE\n end\n end\n end", "language": "ruby", "code": "def iterate(log, farm: Farm::Empty.new, threads: 1)\n raise 'Log can\\'t be nil' if log.nil?\n raise 'Farm can\\'t be nil' if farm.nil?\n Hands.exec(threads, all) do |r, idx|\n Thread.current.name = \"remotes-#{idx}@#{r[:host]}:#{r[:port]}\"\n start = Time.now\n best = farm.best[0]\n node = RemoteNode.new(\n host: r[:host],\n port: r[:port],\n score: best.nil? ? Score::ZERO : best,\n idx: idx,\n master: master?(r[:host], r[:port]),\n log: log,\n network: @network\n )\n begin\n yield node\n raise 'Took too long to execute' if (Time.now - start).round > @timeout\n unerror(r[:host], r[:port]) if node.touched\n rescue StandardError => e\n error(r[:host], r[:port])\n if e.is_a?(RemoteNode::CantAssert) || e.is_a?(Fetch::Error)\n log.debug(\"#{Rainbow(node).red}: \\\"#{e.message.strip}\\\" in #{Age.new(start)}\")\n else\n log.info(\"#{Rainbow(node).red}: \\\"#{e.message.strip}\\\" in #{Age.new(start)}\")\n log.debug(Backtrace.new(e).to_s)\n end\n remove(r[:host], r[:port]) if r[:errors] > TOLERANCE\n end\n end\n end", "code_tokens": ["def", "iterate", "(", "log", ",", "farm", ":", "Farm", "::", "Empty", ".", "new", ",", "threads", ":", "1", ")", "raise", "'Log can\\'t be nil'", "if", "log", ".", "nil?", "raise", "'Farm can\\'t be nil'", "if", "farm", ".", "nil?", "Hands", ".", "exec", "(", "threads", ",", "all", ")", "do", "|", "r", ",", "idx", "|", "Thread", ".", "current", ".", "name", "=", "\"remotes-#{idx}@#{r[:host]}:#{r[:port]}\"", "start", "=", "Time", ".", "now", "best", "=", "farm", ".", "best", "[", "0", "]", "node", "=", "RemoteNode", ".", "new", "(", "host", ":", "r", "[", ":host", "]", ",", "port", ":", "r", "[", ":port", "]", ",", "score", ":", "best", ".", "nil?", "?", "Score", "::", "ZERO", ":", "best", ",", "idx", ":", "idx", ",", "master", ":", "master?", "(", "r", "[", ":host", "]", ",", "r", "[", ":port", "]", ")", ",", "log", ":", "log", ",", "network", ":", "@network", ")", "begin", "yield", "node", "raise", "'Took too long to execute'", "if", "(", "Time", ".", "now", "-", "start", ")", ".", "round", ">", "@timeout", "unerror", "(", "r", "[", ":host", "]", ",", "r", "[", ":port", "]", ")", "if", "node", ".", "touched", "rescue", "StandardError", "=>", "e", "error", "(", "r", "[", ":host", "]", ",", "r", "[", ":port", "]", ")", "if", "e", ".", "is_a?", "(", "RemoteNode", "::", "CantAssert", ")", "||", "e", ".", "is_a?", "(", "Fetch", "::", "Error", ")", "log", ".", "debug", "(", "\"#{Rainbow(node).red}: \\\"#{e.message.strip}\\\" in #{Age.new(start)}\"", ")", "else", "log", ".", "info", "(", "\"#{Rainbow(node).red}: \\\"#{e.message.strip}\\\" in #{Age.new(start)}\"", ")", "log", ".", "debug", "(", "Backtrace", ".", "new", "(", "e", ")", ".", "to_s", ")", "end", "remove", "(", "r", "[", ":host", "]", ",", "r", "[", ":port", "]", ")", "if", "r", "[", ":errors", "]", ">", "TOLERANCE", "end", "end", "end"], "docstring": "Go through the list of remotes and call a provided block for each\n of them. See how it's used, for example, in fetch.rb.", "docstring_tokens": ["Go", "through", "the", "list", "of", "remotes", "and", "call", "a", "provided", "block", "for", "each", "of", "them", ".", "See", "how", "it", "s", "used", "for", "example", "in", "fetch", ".", "rb", "."], "sha": "7e0f69307786846186bc3436dcc72d91d393ddd4", "url": "https://github.com/zold-io/zold/blob/7e0f69307786846186bc3436dcc72d91d393ddd4/lib/zold/remotes.rb#L206-L237", "partition": "valid"}
{"repo": "thredded/thredded", "path": "app/models/concerns/thredded/post_common.rb", "func_name": "Thredded.PostCommon.mark_as_unread", "original_string": "def mark_as_unread(user)\n if previous_post.nil?\n read_state = postable.user_read_states.find_by(user_id: user.id)\n read_state.destroy if read_state\n else\n postable.user_read_states.touch!(user.id, previous_post, overwrite_newer: true)\n end\n end", "language": "ruby", "code": "def mark_as_unread(user)\n if previous_post.nil?\n read_state = postable.user_read_states.find_by(user_id: user.id)\n read_state.destroy if read_state\n else\n postable.user_read_states.touch!(user.id, previous_post, overwrite_newer: true)\n end\n end", "code_tokens": ["def", "mark_as_unread", "(", "user", ")", "if", "previous_post", ".", "nil?", "read_state", "=", "postable", ".", "user_read_states", ".", "find_by", "(", "user_id", ":", "user", ".", "id", ")", "read_state", ".", "destroy", "if", "read_state", "else", "postable", ".", "user_read_states", ".", "touch!", "(", "user", ".", "id", ",", "previous_post", ",", "overwrite_newer", ":", "true", ")", "end", "end"], "docstring": "Marks all the posts from the given one as unread for the given user\n @param [Thredded.user_class] user", "docstring_tokens": ["Marks", "all", "the", "posts", "from", "the", "given", "one", "as", "unread", "for", "the", "given", "user"], "sha": "f1874fba333444255979c0789ba17f8dc24a4d6f", "url": "https://github.com/thredded/thredded/blob/f1874fba333444255979c0789ba17f8dc24a4d6f/app/models/concerns/thredded/post_common.rb#L67-L74", "partition": "valid"}
{"repo": "thredded/thredded", "path": "app/mailers/thredded/base_mailer.rb", "func_name": "Thredded.BaseMailer.find_record", "original_string": "def find_record(klass, id_or_record)\n # Check by name because in development the Class might have been reloaded after id was initialized\n id_or_record.class.name == klass.name ? id_or_record : klass.find(id_or_record)\n end", "language": "ruby", "code": "def find_record(klass, id_or_record)\n # Check by name because in development the Class might have been reloaded after id was initialized\n id_or_record.class.name == klass.name ? id_or_record : klass.find(id_or_record)\n end", "code_tokens": ["def", "find_record", "(", "klass", ",", "id_or_record", ")", "id_or_record", ".", "class", ".", "name", "==", "klass", ".", "name", "?", "id_or_record", ":", "klass", ".", "find", "(", "id_or_record", ")", "end"], "docstring": "Find a record by ID, or return the passed record.\n @param [Class \"\n text = open + text.gsub(/\\r\\n?/, \"\\n\"). # \\r\\n and \\r -> \\n\n gsub(/\\n\\n+/, \"
') + # 1 newline -> br\n \"
\"\n text = open + text.gsub(/\\r\\n?/, \"\\n\"). # \\r\\n and \\r -> \\n\n gsub(/\\n\\n+/, \"
\\n\\n#{open}\"). # 2+ newline -> paragraph\n gsub(/([^\\n]\\n)(?=[^\\n])/, '\\1\"", "text", "=", "open", "+", "text", ".", "gsub", "(", "/", "\\r", "\\n", "/", ",", "\"\\n\"", ")", ".", "gsub", "(", "/", "\\n", "\\n", "/", ",", "\"
\\n\\n#{open}\"", ")", ".", "gsub", "(", "/", "\\n", "\\n", "\\n", "/", ",", "'\\1#{help_text}
}\n _html << %{#{help_text}
}\n _html << %{#{help_text}
}", "_html", "<<", "%{Relative frequency of search traffic for this keyword across multiple search engines, as measured by WordTracker.
\n